code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package mailgun
import (
"strconv"
"time"
)
// Bounce aggregates data relating to undeliverable messages to a specific intended recipient,
// identified by Address.
// Code provides the SMTP error code causing the bounce,
// while Error provides a human readable reason why.
// CreatedAt provides the time at which Mailgun detected the bounce.
type Bounce struct {
CreatedAt string `json:"created_at"`
code interface{} `json:"code"`
Address string `json:"address"`
Error string `json:"error"`
}
type Paging struct {
First string `json:"first"`
Next string `json:"next"`
Previous string `json:"previous"`
Last string `json:"last"`
}
type bounceEnvelope struct {
Items []Bounce `json:"items"`
Paging Paging `json:"paging"`
}
// GetCreatedAt parses the textual, RFC-822 timestamp into a standard Go-compatible
// Time structure.
func (i Bounce) GetCreatedAt() (t time.Time, err error) {
return parseMailgunTime(i.CreatedAt)
}
// GetCode will return the bounce code for the message, regardless if it was
// returned as a string or as an integer. This method overcomes a protocol
// bug in the Mailgun API.
func (b Bounce) GetCode() (int, error) {
switch c := b.code.(type) {
case int:
return c, nil
case string:
return strconv.Atoi(c)
default:
return -1, strconv.ErrSyntax
}
}
// GetBounces returns a complete set of bounces logged against the sender's domain, if any.
// The results include the total number of bounces (regardless of skip or limit settings),
// and the slice of bounces specified, if successful.
// Note that the length of the slice may be smaller than the total number of bounces.
func (m *MailgunImpl) GetBounces(limit, skip int) (int, []Bounce, error) {
r := newHTTPRequest(generateApiUrl(m, bouncesEndpoint))
if limit != -1 {
r.addParameter("limit", strconv.Itoa(limit))
}
if skip != -1 {
r.addParameter("skip", strconv.Itoa(skip))
}
r.setClient(m.Client())
r.setBasicAuth(basicAuthUser, m.ApiKey())
var response bounceEnvelope
err := getResponseFromJSON(r, &response)
if err != nil {
return -1, nil, err
}
return len(response.Items), response.Items, nil
}
// GetSingleBounce retrieves a single bounce record, if any exist, for the given recipient address.
func (m *MailgunImpl) GetSingleBounce(address string) (Bounce, error) {
r := newHTTPRequest(generateApiUrl(m, bouncesEndpoint) + "/" + address)
r.setClient(m.Client())
r.setBasicAuth(basicAuthUser, m.ApiKey())
var response Bounce
err := getResponseFromJSON(r, &response)
return response, err
}
// AddBounce files a bounce report.
// Address identifies the intended recipient of the message that bounced.
// Code corresponds to the numeric response given by the e-mail server which rejected the message.
// Error providees the corresponding human readable reason for the problem.
// For example,
// here's how the these two fields relate.
// Suppose the SMTP server responds with an error, as below.
// Then, . . .
//
// 550 Requested action not taken: mailbox unavailable
// \___/\_______________________________________________/
// | |
// `-- Code `-- Error
//
// Note that both code and error exist as strings, even though
// code will report as a number.
func (m *MailgunImpl) AddBounce(address, code, error string) error {
r := newHTTPRequest(generateApiUrl(m, bouncesEndpoint))
r.setClient(m.Client())
r.setBasicAuth(basicAuthUser, m.ApiKey())
payload := newUrlEncodedPayload()
payload.addValue("address", address)
if code != "" {
payload.addValue("code", code)
}
if error != "" {
payload.addValue("error", error)
}
_, err := makePostRequest(r, payload)
return err
}
// DeleteBounce removes all bounces associted with the provided e-mail address.
func (m *MailgunImpl) DeleteBounce(address string) error {
r := newHTTPRequest(generateApiUrl(m, bouncesEndpoint) + "/" + address)
r.setClient(m.Client())
r.setBasicAuth(basicAuthUser, m.ApiKey())
_, err := makeDeleteRequest(r)
return err
}
| larsha/brynn.se-go | vendor/gopkg.in/mailgun/mailgun-go.v1/bounces.go | GO | mit | 4,055 |
import convert = require("convert-source-map");
var json = convert
.fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.toJSON();
var modified = convert
.fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.setProperty('sources', ['CONSOLE.LOG("HI");'])
.toJSON();
console.log(json);
console.log(modified);
| psnider/DefinitelyTyped | convert-source-map/convert-source-map-tests.ts | TypeScript | mit | 641 |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.eclipse.che.ide.util.input;
import org.eclipse.che.ide.util.input.SignalEvent.KeySignalType;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Event;
import java.util.HashSet;
import java.util.Set;
/**
* Instances of this class encapsulate the event to signal mapping logic for a
* specific environment (os/browser).
* <p/>
* Contains as much of the signal event logic as possible in a POJO testable
* manner.
*
* @author [email protected] (Daniel Danilatos)
*/
public final class SignalKeyLogic {
/**
* For webkit + IE
* I think also all browsers on windows?
*/
public static final int IME_CODE = 229;
//TODO(danilatos): Use int map
private static final Set<Integer> NAVIGATION_KEYS = new HashSet<>();
static {
NAVIGATION_KEYS.add(KeyCodes.KEY_LEFT);
NAVIGATION_KEYS.add(KeyCodes.KEY_RIGHT);
NAVIGATION_KEYS.add(KeyCodes.KEY_UP);
NAVIGATION_KEYS.add(KeyCodes.KEY_DOWN);
NAVIGATION_KEYS.add(KeyCodes.KEY_PAGEUP);
NAVIGATION_KEYS.add(KeyCodes.KEY_PAGEDOWN);
NAVIGATION_KEYS.add(KeyCodes.KEY_HOME);
NAVIGATION_KEYS.add(KeyCodes.KEY_END);
}
public enum UserAgentType {
WEBKIT, GECKO, IE
}
public enum OperatingSystem {
WINDOWS, MAC, LINUX
}
public static class Result {
public int keyCode;
// Sentinal by default for testing purposes
public KeySignalType type = KeySignalType.SENTINAL;
}
private final UserAgentType userAgent;
private final boolean commandIsCtrl;
// Hack, get rid of this
final boolean commandComboDoesntGiveKeypress;
/**
* @param userAgent
* @param os
* Operating system
*/
public SignalKeyLogic(UserAgentType userAgent, OperatingSystem os, boolean commandComboDoesntGiveKeypress) {
this.userAgent = userAgent;
this.commandComboDoesntGiveKeypress = commandComboDoesntGiveKeypress;
commandIsCtrl = os != OperatingSystem.MAC;
}
public boolean commandIsCtrl() {
return commandIsCtrl;
}
public void computeKeySignalType(Result result, String typeName, int keyCode, int which, String keyIdentifier,
boolean metaKey, boolean ctrlKey, boolean altKey, boolean shiftKey) {
boolean ret = true;
int typeInt;
if ("keydown".equals(typeName)) {
typeInt = Event.ONKEYDOWN;
} else if ("keypress".equals(typeName)) {
typeInt = Event.ONKEYPRESS;
} else if ("keyup".equals(typeName)) {
result.type = null;
return;
} else {
throw new AssertionError("Non-key-event passed to computeKeySignalType");
}
KeySignalType type;
int computedKeyCode = which != 0 ? which : keyCode;
if (computedKeyCode == 10) {
computedKeyCode = KeyCodes.KEY_ENTER;
}
// For non-firefox browsers, we only get keydown events for IME, no keypress
boolean isIME = computedKeyCode == IME_CODE;
boolean commandKey = commandIsCtrl ? ctrlKey : metaKey;
switch (userAgent) {
case WEBKIT:
// This is a bit tricky because there are significant differences
// between safari 3.0 and safari 3.1...
// We could probably actually almost use the same code that we use for IE
// for safari 3.1, because with 3.1 the webkit folks made a big shift to
// get the events to be in line with IE for compatibility. 3.0 events
// are a lot more similar to FF, but different enough to need special
// handling. Weird special large keycode numbers for safari 3.0, where it gives
// us keypress events (though they happen after the dom is changed,
// for some things like delete. So not too useful). The number
// 63200 is known as the cutoff mark.
if (typeInt == Event.ONKEYDOWN && computedKeyCode > 63200) {
result.type = null;
return;
} else if (typeInt == Event.ONKEYPRESS) {
// Skip keypress for tab and escape, because they are the only non-input keys
// that don't have keycodes above 63200. This is to prevent them from being treated
// as INPUT in the || = keypress below. See (X) below
if (computedKeyCode == KeyCodes.KEY_ESCAPE || computedKeyCode == KeyCodes.KEY_TAB) {
result.type = null;
return;
}
}
// Need to use identifier for the delete key because the keycode conflicts
// with the keycode for the full stop.
boolean isActuallyCtrlInput = false;
if (isIME) {
if (typeInt == Event.ONKEYDOWN) {
//Don't actually react to press key with keyCode==229
result.type = null;
return;
} else {
type = KeySignalType.INPUT;
}
} else if ((computedKeyCode == KeyCodes.KEY_DELETE && typeInt == Event.ONKEYDOWN) ||
computedKeyCode == KeyCodes.KEY_BACKSPACE) {
type = KeySignalType.DELETE;
} else if (NAVIGATION_KEYS.contains(computedKeyCode) && typeInt == Event.ONKEYDOWN) {
type = KeySignalType.NAVIGATION;
// Escape, backspace and context-menu-key (U+0010) are, to my knowledge,
// the only non-navigation keys that
} else if (computedKeyCode == KeyCodes.KEY_ESCAPE) {
type = KeySignalType.NOEFFECT;
} else if (computedKeyCode < 63200 && // if it's not a safari 3.0 non-input key (See (X) above)
(typeInt == Event.ONKEYPRESS || // if it's a regular keypress
computedKeyCode == KeyCodes.KEY_ENTER)) {
type = KeySignalType.INPUT;
isActuallyCtrlInput = ctrlKey || (commandComboDoesntGiveKeypress && commandKey);
} else {
type = KeySignalType.NOEFFECT;
}
// Maybe nullify it with the same logic as IE, EXCEPT for the special
// Ctrl Input webkit behaviour, and IME for windows
if (isActuallyCtrlInput) {
if (computedKeyCode == KeyCodes.KEY_ENTER) {
ret = typeInt == Event.ONKEYDOWN;
}
// HACK(danilatos): Don't actually nullify isActuallyCtrlInput for key press.
// We get that for AltGr combos on non-mac computers.
} else if (keyCode == KeyCodes.KEY_TAB) {
ret = typeInt == Event.ONKEYDOWN;
} else {
ret = maybeNullWebkitIE(ret, typeInt, type);
}
if (!ret) {
result.type = null;
return;
}
break;
case GECKO:
boolean hasKeyCodeButNotWhich = keyCode != 0 && which == 0;
// Firefox is easy for deciding signal events, because it issues a keypress for
// whenever we would want a signal. So we can basically ignore all keydown events.
// It also, on all OSes, does any default action AFTER the keypress (even for
// things like Ctrl/Meta+C, etc). So keypress is perfect for us.
// Ctrl+Space is an exception, where we don't get a keypress
// Firefox also gives us keypress events even for Windows IME input
if (ctrlKey && !altKey && !shiftKey && computedKeyCode == ' ') {
if (typeInt != Event.ONKEYDOWN) {
result.type = null;
return;
}
} else if (typeInt == Event.ONKEYDOWN) {
result.type = null;
return;
}
// Backspace fails the !hasKeyCodeButNotWhich test, so check it explicitly first
if (computedKeyCode == KeyCodes.KEY_BACKSPACE) {
type = KeySignalType.DELETE;
// This 'keyCode' but not 'which' works very nicely for catching normal typing input keys,
// the only 'exceptions' I've seen so far are bksp & enter which have both
} else if (!hasKeyCodeButNotWhich || computedKeyCode == KeyCodes.KEY_ENTER
|| computedKeyCode == KeyCodes.KEY_TAB) {
type = KeySignalType.INPUT;
} else if (computedKeyCode == KeyCodes.KEY_DELETE) {
type = KeySignalType.DELETE;
} else if (NAVIGATION_KEYS.contains(computedKeyCode)) {
type = KeySignalType.NAVIGATION;
} else {
type = KeySignalType.NOEFFECT;
}
break;
case IE:
// Unfortunately IE gives us the least information, so there are no nifty tricks.
// So we pretty much need to use some educated guessing based on key codes.
// Experimentation page to the rescue.
boolean isKeydownForInputKey = isInputKeyCodeIE(computedKeyCode);
// IE has some strange behaviour with modifiers and whether or not there will
// be a keypress. Ctrl kills the keypress, unless shift is also held.
// Meta doesn't kill it. Alt always kills the keypress, overriding other rules.
boolean hasModifiersThatResultInNoKeyPress = altKey || (ctrlKey && !shiftKey);
if (typeInt == Event.ONKEYDOWN) {
if (isKeydownForInputKey) {
type = KeySignalType.INPUT;
} else if (computedKeyCode == KeyCodes.KEY_BACKSPACE || computedKeyCode == KeyCodes.KEY_DELETE) {
type = KeySignalType.DELETE;
} else if (NAVIGATION_KEYS.contains(computedKeyCode)) {
type = KeySignalType.NAVIGATION;
} else {
type = KeySignalType.NOEFFECT;
}
} else {
// Escape is the only non-input thing that has a keypress event
if (computedKeyCode == KeyCodes.KEY_ESCAPE) {
result.type = null;
return;
}
assert typeInt == Event.ONKEYPRESS;
// I think the guessCommandFromModifiers() check here isn't needed,
// but i feel safer putting it in.
type = KeySignalType.INPUT;
}
if (hasModifiersThatResultInNoKeyPress || computedKeyCode == KeyCodes.KEY_TAB) {
ret = typeInt == Event.ONKEYDOWN ? ret : false;
} else {
ret = maybeNullWebkitIE(ret, typeInt, type);
}
if (!ret) {
result.type = null;
return;
}
break;
default:
throw new UnsupportedOperationException("Unhandled user agent");
}
if (ret) {
result.type = type;
result.keyCode = computedKeyCode;
} else {
result.type = null;
return;
}
}
private static final boolean isInputKeyCodeIE(int keyCode) {
/*
DATA
----
For KEYDOWN:
"Input"
48-57 (numbers)
65-90 (a-z)
96-111 (Numpad digits & other keys, with numlock off. with numlock on, they
behave like their corresponding keys on the rest of the keyboard)
186-192 219-222 (random non-alphanumeric next to letters on RHS + backtick)
229 Code that the input has passed to an IME
Non-"input"
< 48 ('0')
91-93 (Left & Right Win keys, ContextMenu key)
112-123 (F1-F12)
144-5 (NUMLOCK,SCROLL LOCK)
For KEYPRESS: only "input" things get this event! yay! not even backspace!
Well, one exception: ESCAPE
*/
// boundaries in keycode ranges where the keycode for a keydown is for an input
// key. at "ON" it is, starting from the number going up, and the opposite for "OFF".
final int A_ON = 48;
final int B_OFF = 91;
final int C_ON = 96;
final int D_OFF = 112;
final int E_ON = 186;
return (keyCode == 9 || keyCode == 32 || keyCode == 13) || // And tab, enter & spacebar, of course!
(keyCode >= A_ON && keyCode < B_OFF) || (keyCode >= C_ON && keyCode < D_OFF) || (keyCode >= E_ON);
}
/**
* Common logic between Webkit and IE for deciding whether we want the keydown
* or the keypress
*/
private static boolean maybeNullWebkitIE(boolean ret, int typeInt, KeySignalType type) {
// Use keydown as the signal for everything except input.
// This is because the mutation always happens after the keypress for
// input (this is especially important for chrome,
// which interleaves deferred commands between keydown and keypress).
//
// For everything else, keypress is redundant with keydown, and also, the resulting default
// dom mutation (if any) often happens after the keydown but before the keypress in webkit.
// Also, if the 'Command' key is held for chrome/safari etc, we want to get the keydown
// event, NOT the keypress event, for everything because of things like ctrl+c etc.
// where sometimes it'll happen just after the keydown, or sometimes we just won't
// get a keypress at all
if (typeInt == (type == KeySignalType.INPUT ? Event.ONKEYDOWN : Event.ONKEYPRESS)) {
return false;
}
return ret;
}
}
| kaloyan-raev/che | ide/commons-gwt/src/main/java/org/eclipse/che/ide/util/input/SignalKeyLogic.java | Java | epl-1.0 | 14,900 |
<?php
/**
* Parse and evaluate a plural rule.
*
* http://unicode.org/reports/tr35/#Language_Plural_Rules
*
* @author Niklas Laxstrom, Tim Starling
*
* @copyright Copyright © 2010-2012, Niklas Laxström
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0
* or later
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*
* @file
* @since 1.20
*/
class CLDRPluralRuleEvaluator {
/**
* Evaluate a number against a set of plural rules. If a rule passes,
* return the index of plural rule.
*
* @param int The number to be evaluated against the rules
* @param array The associative array of plural rules in pluralform => rule format.
* @return int The index of the plural form which passed the evaluation
*/
public static function evaluate( $number, array $rules ) {
$rules = self::compile( $rules );
return self::evaluateCompiled( $number, $rules );
}
/**
* Convert a set of rules to a compiled form which is optimised for
* fast evaluation. The result will be an array of strings, and may be cached.
*
* @param $rules The rules to compile
* @return An array of compile rules.
*/
public static function compile( array $rules ) {
// We can't use array_map() for this because it generates a warning if
// there is an exception.
foreach ( $rules as &$rule ) {
$rule = CLDRPluralRuleConverter::convert( $rule );
}
return $rules;
}
/**
* Evaluate a compiled set of rules returned by compile(). Do not allow
* the user to edit the compiled form, or else PHP errors may result.
*/
public static function evaluateCompiled( $number, array $rules ) {
// The compiled form is RPN, with tokens strictly delimited by
// spaces, so this is a simple RPN evaluator.
foreach ( $rules as $i => $rule ) {
$stack = array();
$zero = ord( '0' );
$nine = ord( '9' );
foreach ( StringUtils::explode( ' ', $rule ) as $token ) {
$ord = ord( $token );
if ( $token === 'n' ) {
$stack[] = $number;
} elseif ( $ord >= $zero && $ord <= $nine ) {
$stack[] = intval( $token );
} else {
$right = array_pop( $stack );
$left = array_pop( $stack );
$result = self::doOperation( $token, $left, $right );
$stack[] = $result;
}
}
if ( $stack[0] ) {
return $i;
}
}
// None of the provided rules match. The number belongs to caregory
// 'other' which comes last.
return count( $rules );
}
/**
* Do a single operation
*
* @param $token string The token string
* @param $left The left operand. If it is an object, its state may be destroyed.
* @param $right The right operand
* @throws CLDRPluralRuleError
* @return mixed
*/
private static function doOperation( $token, $left, $right ) {
if ( in_array( $token, array( 'in', 'not-in', 'within', 'not-within' ) ) ) {
if ( !($right instanceof CLDRPluralRuleEvaluator_Range ) ) {
$right = new CLDRPluralRuleEvaluator_Range( $right );
}
}
switch ( $token ) {
case 'or':
return $left || $right;
case 'and':
return $left && $right;
case 'is':
return $left == $right;
case 'is-not':
return $left != $right;
case 'in':
return $right->isNumberIn( $left );
case 'not-in':
return !$right->isNumberIn( $left );
case 'within':
return $right->isNumberWithin( $left );
case 'not-within':
return !$right->isNumberWithin( $left );
case 'mod':
if ( is_int( $left ) ) {
return (int) fmod( $left, $right );
}
return fmod( $left, $right );
case ',':
if ( $left instanceof CLDRPluralRuleEvaluator_Range ) {
$range = $left;
} else {
$range = new CLDRPluralRuleEvaluator_Range( $left );
}
$range->add( $right );
return $range;
case '..':
return new CLDRPluralRuleEvaluator_Range( $left, $right );
default:
throw new CLDRPluralRuleError( "Invalid RPN token" );
}
}
}
/**
* Evaluator helper class representing a range list.
*/
class CLDRPluralRuleEvaluator_Range {
public $parts = array();
function __construct( $start, $end = false ) {
if ( $end === false ) {
$this->parts[] = $start;
} else {
$this->parts[] = array( $start, $end );
}
}
/**
* Determine if the given number is inside the range. If $integerConstraint
* is true, the number must additionally be an integer if it is to match
* any interval part.
*/
function isNumberIn( $number, $integerConstraint = true ) {
foreach ( $this->parts as $part ) {
if ( is_array( $part ) ) {
if ( ( !$integerConstraint || floor( $number ) === (float)$number )
&& $number >= $part[0] && $number <= $part[1] )
{
return true;
}
} else {
if ( $number == $part ) {
return true;
}
}
}
return false;
}
/**
* Readable alias for isNumberIn( $number, false ), and the implementation
* of the "within" operator.
*/
function isNumberWithin( $number ) {
return $this->isNumberIn( $number, false );
}
/**
* Add another part to this range. The supplied new part may either be a
* range object itself, or a single number.
*/
function add( $other ) {
if ( $other instanceof self ) {
$this->parts = array_merge( $this->parts, $other->parts );
} else {
$this->parts[] = $other;
}
}
/**
* For debugging
*/
function __toString() {
$s = 'Range(';
foreach ( $this->parts as $i => $part ) {
if ( $i ) {
$s .= ', ';
}
if ( is_array( $part ) ) {
$s .= $part[0] . '..' . $part[1];
} else {
$s .= $part;
}
}
$s .= ')';
return $s;
}
}
/**
* Helper class for converting rules to reverse polish notation (RPN).
*/
class CLDRPluralRuleConverter {
public $rule, $pos, $end;
public $operators = array();
public $operands = array();
/**
* Precedence levels. Note that there's no need to worry about associativity
* for the level 4 operators, since they return boolean and don't accept
* boolean inputs.
*/
static $precedence = array(
'or' => 2,
'and' => 3,
'is' => 4,
'is-not' => 4,
'in' => 4,
'not-in' => 4,
'within' => 4,
'not-within' => 4,
'mod' => 5,
',' => 6,
'..' => 7,
);
/**
* A character list defining whitespace, for use in strspn() etc.
*/
const WHITESPACE_CLASS = " \t\r\n";
/**
* Same for digits. Note that the grammar given in UTS #35 doesn't allow
* negative numbers or decimals.
*/
const NUMBER_CLASS = '0123456789';
/**
* An anchored regular expression which matches a word at the current offset.
*/
const WORD_REGEX = '/[a-zA-Z]+/A';
/**
* Convert a rule to RPN. This is the only public entry point.
*/
public static function convert( $rule ) {
$parser = new self( $rule );
return $parser->doConvert();
}
/**
* Private constructor.
*/
protected function __construct( $rule ) {
$this->rule = $rule;
$this->pos = 0;
$this->end = strlen( $rule );
}
/**
* Do the operation.
*/
protected function doConvert() {
$expectOperator = true;
// Iterate through all tokens, saving the operators and operands to a
// stack per Dijkstra's shunting yard algorithm.
while ( false !== ( $token = $this->nextToken() ) ) {
// In this grammar, there are only binary operators, so every valid
// rule string will alternate between operator and operand tokens.
$expectOperator = !$expectOperator;
if ( $token instanceof CLDRPluralRuleConverter_Expression ) {
// Operand
if ( $expectOperator ) {
$token->error( 'unexpected operand' );
}
$this->operands[] = $token;
continue;
} else {
// Operator
if ( !$expectOperator ) {
$token->error( 'unexpected operator' );
}
// Resolve higher precedence levels
$lastOp = end( $this->operators );
while ( $lastOp && self::$precedence[$token->name] <= self::$precedence[$lastOp->name] ) {
$this->doOperation( $lastOp, $this->operands );
array_pop( $this->operators );
$lastOp = end( $this->operators );
}
$this->operators[] = $token;
}
}
// Finish off the stack
while ( $op = array_pop( $this->operators ) ) {
$this->doOperation( $op, $this->operands );
}
// Make sure the result is sane. The first case is possible for an empty
// string input, the second should be unreachable.
if ( !count( $this->operands ) ) {
$this->error( 'condition expected' );
} elseif ( count( $this->operands ) > 1 ) {
$this->error( 'missing operator or too many operands' );
}
$value = $this->operands[0];
if ( $value->type !== 'boolean' ) {
$this->error( 'the result must have a boolean type' );
}
return $this->operands[0]->rpn;
}
/**
* Fetch the next token from the input string. Return it as a
* CLDRPluralRuleConverter_Fragment object.
*/
protected function nextToken() {
if ( $this->pos >= $this->end ) {
return false;
}
// Whitespace
$length = strspn( $this->rule, self::WHITESPACE_CLASS, $this->pos );
$this->pos += $length;
if ( $this->pos >= $this->end ) {
return false;
}
// Number
$length = strspn( $this->rule, self::NUMBER_CLASS, $this->pos );
if ( $length !== 0 ) {
$token = $this->newNumber( substr( $this->rule, $this->pos, $length ), $this->pos );
$this->pos += $length;
return $token;
}
// Comma
if ( $this->rule[$this->pos] === ',' ) {
$token = $this->newOperator( ',', $this->pos, 1 );
$this->pos ++;
return $token;
}
// Dot dot
if ( substr( $this->rule, $this->pos, 2 ) === '..' ) {
$token = $this->newOperator( '..', $this->pos, 2 );
$this->pos += 2;
return $token;
}
// Word
if ( !preg_match( self::WORD_REGEX, $this->rule, $m, 0, $this->pos ) ) {
$this->error( 'unexpected character "' . $this->rule[$this->pos] . '"' );
}
$word1 = strtolower( $m[0] );
$word2 = '';
$nextTokenPos = $this->pos + strlen( $word1 );
if ( $word1 === 'not' || $word1 === 'is' ) {
// Look ahead one word
$nextTokenPos += strspn( $this->rule, self::WHITESPACE_CLASS, $nextTokenPos );
if ( $nextTokenPos < $this->end
&& preg_match( self::WORD_REGEX, $this->rule, $m, 0, $nextTokenPos ) )
{
$word2 = strtolower( $m[0] );
$nextTokenPos += strlen( $word2 );
}
}
// Two-word operators like "is not" take precedence over single-word operators like "is"
if ( $word2 !== '' ) {
$bothWords = "{$word1}-{$word2}";
if ( isset( self::$precedence[$bothWords] ) ) {
$token = $this->newOperator( $bothWords, $this->pos, $nextTokenPos - $this->pos );
$this->pos = $nextTokenPos;
return $token;
}
}
// Single-word operators
if ( isset( self::$precedence[$word1] ) ) {
$token = $this->newOperator( $word1, $this->pos, strlen( $word1 ) );
$this->pos += strlen( $word1 );
return $token;
}
// The special numerical keyword "n"
if ( $word1 === 'n' ) {
$token = $this->newNumber( 'n', $this->pos );
$this->pos ++;
return $token;
}
$this->error( 'unrecognised word' );
}
/**
* For the binary operator $op, pop its operands off the stack and push
* a fragment with rpn and type members describing the result of that
* operation.
*/
protected function doOperation( $op ) {
if ( count( $this->operands ) < 2 ) {
$op->error( 'missing operand' );
}
$right = array_pop( $this->operands );
$left = array_pop( $this->operands );
$result = $op->operate( $left, $right );
$this->operands[] = $result;
}
/**
* Create a numerical expression object
*/
protected function newNumber( $text, $pos ) {
return new CLDRPluralRuleConverter_Expression( $this, 'number', $text, $pos, strlen( $text ) );
}
/**
* Create a binary operator
*/
protected function newOperator( $type, $pos, $length ) {
return new CLDRPluralRuleConverter_Operator( $this, $type, $pos, $length );
}
/**
* Throw an error
*/
protected function error( $message ) {
throw new CLDRPluralRuleError( $message );
}
}
/**
* Helper for CLDRPluralRuleConverter.
* The base class for operators and expressions, describing a region of the input string.
*/
class CLDRPluralRuleConverter_Fragment {
public $parser, $pos, $length, $end;
function __construct( $parser, $pos, $length ) {
$this->parser = $parser;
$this->pos = $pos;
$this->length = $length;
$this->end = $pos + $length;
}
public function error( $message ) {
$text = $this->getText();
throw new CLDRPluralRuleError( "$message at position " . ( $this->pos + 1 ) . ": \"$text\"" );
}
public function getText() {
return substr( $this->parser->rule, $this->pos, $this->length );
}
}
/**
* Helper for CLDRPluralRuleConverter.
* An expression object, representing a region of the input string (for error
* messages), the RPN notation used to evaluate it, and the result type for
* validation.
*/
class CLDRPluralRuleConverter_Expression extends CLDRPluralRuleConverter_Fragment {
public $type, $rpn;
function __construct( $parser, $type, $rpn, $pos, $length ) {
parent::__construct( $parser, $pos, $length );
$this->type = $type;
$this->rpn = $rpn;
}
public function isType( $type ) {
if ( $type === 'range' && ( $this->type === 'range' || $this->type === 'number' ) ) {
return true;
}
if ( $type === $this->type ) {
return true;
}
return false;
}
}
/**
* Helper for CLDRPluralRuleConverter.
* An operator object, representing a region of the input string (for error
* messages), and the binary operator at that location.
*/
class CLDRPluralRuleConverter_Operator extends CLDRPluralRuleConverter_Fragment {
public $name;
/**
* Each op type has three characters: left operand type, right operand type and result type
*
* b = boolean
* n = number
* r = range
*
* A number is a kind of range.
*/
static $opTypes = array(
'or' => 'bbb',
'and' => 'bbb',
'is' => 'nnb',
'is-not' => 'nnb',
'in' => 'nrb',
'not-in' => 'nrb',
'within' => 'nrb',
'not-within' => 'nrb',
'mod' => 'nnn',
',' => 'rrr',
'..' => 'nnr',
);
/**
* Map converting from the abbrevation to the full form.
*/
static $typeSpecMap = array(
'b' => 'boolean',
'n' => 'number',
'r' => 'range',
);
function __construct( $parser, $name, $pos, $length ) {
parent::__construct( $parser, $pos, $length );
$this->name = $name;
}
public function operate( $left, $right ) {
$typeSpec = self::$opTypes[$this->name];
$leftType = self::$typeSpecMap[$typeSpec[0]];
$rightType = self::$typeSpecMap[$typeSpec[1]];
$resultType = self::$typeSpecMap[$typeSpec[2]];
$start = min( $this->pos, $left->pos, $right->pos );
$end = max( $this->end, $left->end, $right->end );
$length = $end - $start;
$newExpr = new CLDRPluralRuleConverter_Expression( $this->parser, $resultType,
"{$left->rpn} {$right->rpn} {$this->name}",
$start, $length );
if ( !$left->isType( $leftType ) ) {
$newExpr->error( "invalid type for left operand: expected $leftType, got {$left->type}" );
}
if ( !$right->isType( $rightType ) ) {
$newExpr->error( "invalid type for right operand: expected $rightType, got {$right->type}" );
}
return $newExpr;
}
}
/**
* The exception class for all the classes in this file. This will be thrown
* back to the caller if there is any validation error.
*/
class CLDRPluralRuleError extends MWException {
function __construct( $message ) {
parent::__construct( 'CLDR plural rule error: ' . $message );
}
}
| ColFusion/ColfusionWeb | wiki/languages/utils/CLDRPluralRuleEvaluator.php | PHP | gpl-2.0 | 16,025 |
/*
* QEMU Grackle PCI host (heathrow OldWorld PowerMac)
*
* Copyright (c) 2006-2007 Fabrice Bellard
* Copyright (c) 2007 Jocelyn Mayer
*
* 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.
*/
#include "hw/pci/pci_host.h"
#include "hw/ppc/mac.h"
#include "hw/pci/pci.h"
/* debug Grackle */
//#define DEBUG_GRACKLE
#ifdef DEBUG_GRACKLE
#define GRACKLE_DPRINTF(fmt, ...) \
do { printf("GRACKLE: " fmt , ## __VA_ARGS__); } while (0)
#else
#define GRACKLE_DPRINTF(fmt, ...)
#endif
#define GRACKLE_PCI_HOST_BRIDGE(obj) \
OBJECT_CHECK(GrackleState, (obj), TYPE_GRACKLE_PCI_HOST_BRIDGE)
typedef struct GrackleState {
PCIHostState parent_obj;
MemoryRegion pci_mmio;
MemoryRegion pci_hole;
} GrackleState;
/* Don't know if this matches real hardware, but it agrees with OHW. */
static int pci_grackle_map_irq(PCIDevice *pci_dev, int irq_num)
{
return (irq_num + (pci_dev->devfn >> 3)) & 3;
}
static void pci_grackle_set_irq(void *opaque, int irq_num, int level)
{
qemu_irq *pic = opaque;
GRACKLE_DPRINTF("set_irq num %d level %d\n", irq_num, level);
qemu_set_irq(pic[irq_num + 0x15], level);
}
PCIBus *pci_grackle_init(uint32_t base, qemu_irq *pic,
MemoryRegion *address_space_mem,
MemoryRegion *address_space_io)
{
DeviceState *dev;
SysBusDevice *s;
PCIHostState *phb;
GrackleState *d;
dev = qdev_create(NULL, TYPE_GRACKLE_PCI_HOST_BRIDGE);
qdev_init_nofail(dev);
s = SYS_BUS_DEVICE(dev);
phb = PCI_HOST_BRIDGE(dev);
d = GRACKLE_PCI_HOST_BRIDGE(dev);
memory_region_init(&d->pci_mmio, OBJECT(s), "pci-mmio", 0x100000000ULL);
memory_region_init_alias(&d->pci_hole, OBJECT(s), "pci-hole", &d->pci_mmio,
0x80000000ULL, 0x7e000000ULL);
memory_region_add_subregion(address_space_mem, 0x80000000ULL,
&d->pci_hole);
phb->bus = pci_register_bus(dev, NULL,
pci_grackle_set_irq,
pci_grackle_map_irq,
pic,
&d->pci_mmio,
address_space_io,
0, 4, TYPE_PCI_BUS);
pci_create_simple(phb->bus, 0, "grackle");
sysbus_mmio_map(s, 0, base);
sysbus_mmio_map(s, 1, base + 0x00200000);
return phb->bus;
}
static int pci_grackle_init_device(SysBusDevice *dev)
{
PCIHostState *phb;
phb = PCI_HOST_BRIDGE(dev);
memory_region_init_io(&phb->conf_mem, OBJECT(dev), &pci_host_conf_le_ops,
dev, "pci-conf-idx", 0x1000);
memory_region_init_io(&phb->data_mem, OBJECT(dev), &pci_host_data_le_ops,
dev, "pci-data-idx", 0x1000);
sysbus_init_mmio(dev, &phb->conf_mem);
sysbus_init_mmio(dev, &phb->data_mem);
return 0;
}
static void grackle_pci_host_realize(PCIDevice *d, Error **errp)
{
d->config[0x09] = 0x01;
}
static void grackle_pci_class_init(ObjectClass *klass, void *data)
{
PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
DeviceClass *dc = DEVICE_CLASS(klass);
k->realize = grackle_pci_host_realize;
k->vendor_id = PCI_VENDOR_ID_MOTOROLA;
k->device_id = PCI_DEVICE_ID_MOTOROLA_MPC106;
k->revision = 0x00;
k->class_id = PCI_CLASS_BRIDGE_HOST;
/*
* PCI-facing part of the host bridge, not usable without the
* host-facing part, which can't be device_add'ed, yet.
*/
dc->cannot_instantiate_with_device_add_yet = true;
}
static const TypeInfo grackle_pci_info = {
.name = "grackle",
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(PCIDevice),
.class_init = grackle_pci_class_init,
};
static void pci_grackle_class_init(ObjectClass *klass, void *data)
{
SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
k->init = pci_grackle_init_device;
}
static const TypeInfo grackle_pci_host_info = {
.name = TYPE_GRACKLE_PCI_HOST_BRIDGE,
.parent = TYPE_PCI_HOST_BRIDGE,
.instance_size = sizeof(GrackleState),
.class_init = pci_grackle_class_init,
};
static void grackle_register_types(void)
{
type_register_static(&grackle_pci_info);
type_register_static(&grackle_pci_host_info);
}
type_init(grackle_register_types)
| BCLinux/qga-bc | qemu-master/hw/pci-host/grackle.c | C | gpl-2.0 | 5,377 |
// license:BSD-3-Clause
// copyright-holders:Curt Coder, Olivier Galibert
/*
TODO:
- rewrite shifter
- STe pixelofs
- blitter hog
- high resolution
*/
#include "emu.h"
#include "video/atarist.h"
#include "includes/atarist.h"
//**************************************************************************
// CONSTANTS / MACROS
//**************************************************************************
#define LOG 0
static const int BLITTER_NOPS[16][4] =
{
{ 1, 1, 1, 1 },
{ 2, 2, 3, 3 },
{ 2, 2, 3, 3 },
{ 1, 1, 2, 2 },
{ 2, 2, 3, 3 },
{ 2, 2, 2, 2 },
{ 2, 2, 3, 3 },
{ 2, 2, 3, 3 },
{ 2, 2, 3, 3 },
{ 2, 2, 3, 3 },
{ 2, 2, 2, 2 },
{ 2, 2, 3, 3 },
{ 1, 1, 2, 2 },
{ 2, 2, 3, 3 },
{ 2, 2, 3, 3 },
{ 1, 1, 1, 1 }
};
//**************************************************************************
// SHIFTER
//**************************************************************************
//-------------------------------------------------
// shift_mode_0 -
//-------------------------------------------------
inline pen_t st_state::shift_mode_0()
{
int color = (BIT(m_shifter_rr[3], 15) << 3) | (BIT(m_shifter_rr[2], 15) << 2) | (BIT(m_shifter_rr[1], 15) << 1) | BIT(m_shifter_rr[0], 15);
m_shifter_rr[0] <<= 1;
m_shifter_rr[1] <<= 1;
m_shifter_rr[2] <<= 1;
m_shifter_rr[3] <<= 1;
return m_palette->pen(color);
}
//-------------------------------------------------
// shift_mode_1 -
//-------------------------------------------------
inline pen_t st_state::shift_mode_1()
{
int color = (BIT(m_shifter_rr[1], 15) << 1) | BIT(m_shifter_rr[0], 15);
m_shifter_rr[0] <<= 1;
m_shifter_rr[1] <<= 1;
m_shifter_shift++;
if (m_shifter_shift == 16)
{
m_shifter_rr[0] = m_shifter_rr[2];
m_shifter_rr[1] = m_shifter_rr[3];
m_shifter_rr[2] = m_shifter_rr[3] = 0;
m_shifter_shift = 0;
}
return m_palette->pen(color);
}
//-------------------------------------------------
// shift_mode_2 -
//-------------------------------------------------
inline pen_t st_state::shift_mode_2()
{
int color = BIT(m_shifter_rr[0], 15);
m_shifter_rr[0] <<= 1;
m_shifter_shift++;
switch (m_shifter_shift)
{
case 16:
m_shifter_rr[0] = m_shifter_rr[1];
m_shifter_rr[1] = m_shifter_rr[2];
m_shifter_rr[2] = m_shifter_rr[3];
m_shifter_rr[3] = 0;
break;
case 32:
m_shifter_rr[0] = m_shifter_rr[1];
m_shifter_rr[1] = m_shifter_rr[2];
m_shifter_rr[2] = 0;
break;
case 48:
m_shifter_rr[0] = m_shifter_rr[1];
m_shifter_rr[1] = 0;
m_shifter_shift = 0;
break;
}
return m_palette->pen(color);
}
//-------------------------------------------------
// shifter_tick -
//-------------------------------------------------
void st_state::shifter_tick()
{
int y = m_screen->vpos();
int x = m_screen->hpos();
pen_t pen;
switch (m_shifter_mode)
{
case 0:
pen = shift_mode_0();
break;
case 1:
pen = shift_mode_1();
break;
case 2:
pen = shift_mode_2();
break;
default:
pen = m_palette->black_pen();
break;
}
m_bitmap.pix(y, x) = pen;
}
//-------------------------------------------------
// shifter_load -
//-------------------------------------------------
inline void st_state::shifter_load()
{
address_space &program = m_maincpu->space(AS_PROGRAM);
uint16_t data = program.read_word(m_shifter_ofs);
m_shifter_ir[m_shifter_bitplane] = data;
m_shifter_bitplane++;
m_shifter_ofs += 2;
if (m_shifter_bitplane == 4)
{
m_shifter_bitplane = 0;
m_shifter_rr[0] = m_shifter_ir[0];
m_shifter_rr[1] = m_shifter_ir[1];
m_shifter_rr[2] = m_shifter_ir[2];
m_shifter_rr[3] = m_shifter_ir[3];
}
}
//-------------------------------------------------
// glue_tick -
//-------------------------------------------------
void st_state::draw_pixel(int x, int y, u32 pen)
{
if(x < m_bitmap.width() && y < m_bitmap.height())
m_bitmap.pix(y, x) = pen;
}
void st_state::glue_tick()
{
int y = m_screen->vpos();
int x = m_screen->hpos();
int v = (y >= m_shifter_y_start) && (y < m_shifter_y_end);
int h = (x >= m_shifter_x_start) && (x < m_shifter_x_end);
if(m_shifter_mode == 1) {
int dt = 8;
h = (x >= m_shifter_x_start-dt) && (x < m_shifter_x_end-dt);
}
int de = h && v;
if(!x) {
m_shifter_bitplane = 0;
m_shifter_shift = 0;
}
if (de != m_shifter_de)
{
m_mfp->tbi_w(de);
m_shifter_de = de;
}
if (de)
{
shifter_load();
}
if ((y == m_shifter_vblank_start) && (x == 0))
{
m_maincpu->set_input_line(M68K_IRQ_4, HOLD_LINE);
m_shifter_ofs = m_shifter_base;
}
if (x == m_shifter_hblank_start)
{
m_maincpu->set_input_line(M68K_IRQ_2, HOLD_LINE);
// m_shifter_ofs += (m_shifter_lineofs * 2); // STe
}
pen_t pen;
switch (m_shifter_mode)
{
case 0:
pen = shift_mode_0();
draw_pixel(x, y, pen);
draw_pixel(x+1, y, pen);
pen = shift_mode_0();
draw_pixel(x+2, y, pen);
draw_pixel(x+3, y, pen);
pen = shift_mode_0();
draw_pixel(x+4, y, pen);
draw_pixel(x+5, y, pen);
pen = shift_mode_0();
draw_pixel(x+6, y, pen);
draw_pixel(x+7, y, pen);
break;
case 1:
pen = shift_mode_1();
draw_pixel(x, y, pen);
pen = shift_mode_1();
draw_pixel(x+1, y, pen);
pen = shift_mode_1();
draw_pixel(x+2, y, pen);
pen = shift_mode_1();
draw_pixel(x+3, y, pen);
pen = shift_mode_1();
draw_pixel(x+4, y, pen);
pen = shift_mode_1();
draw_pixel(x+5, y, pen);
pen = shift_mode_1();
draw_pixel(x+6, y, pen);
pen = shift_mode_1();
draw_pixel(x+7, y, pen);
break;
case 2:
pen = shift_mode_2();
break;
default:
pen = m_palette->black_pen();
break;
}
}
//-------------------------------------------------
// set_screen_parameters -
//-------------------------------------------------
void st_state::set_screen_parameters()
{
if (m_shifter_sync & 0x02)
{
m_shifter_x_start = ATARIST_HBDEND_PAL*2;
m_shifter_x_end = ATARIST_HBDSTART_PAL*2;
m_shifter_y_start = ATARIST_VBDEND_PAL;
m_shifter_y_end = ATARIST_VBDSTART_PAL;
m_shifter_hblank_start = ATARIST_HBSTART_PAL*2;
m_shifter_vblank_start = ATARIST_VBSTART_PAL;
}
else
{
m_shifter_x_start = ATARIST_HBDEND_NTSC*2;
m_shifter_x_end = ATARIST_HBDSTART_NTSC*2;
m_shifter_y_start = ATARIST_VBDEND_NTSC;
m_shifter_y_end = ATARIST_VBDSTART_NTSC;
m_shifter_hblank_start = ATARIST_HBSTART_NTSC*2;
m_shifter_vblank_start = ATARIST_VBSTART_NTSC;
}
}
//-------------------------------------------------
// shifter_base_r -
//-------------------------------------------------
uint8_t st_state::shifter_base_r(offs_t offset)
{
uint8_t data = 0;
switch (offset)
{
case 0x00:
data = (m_shifter_base >> 16) & 0x3f;
break;
case 0x01:
data = (m_shifter_base >> 8) & 0xff;
break;
}
return data;
}
//-------------------------------------------------
// shifter_base_w -
//-------------------------------------------------
void st_state::shifter_base_w(offs_t offset, uint8_t data)
{
switch (offset)
{
case 0x00:
m_shifter_base = (m_shifter_base & 0x00ff00) | (data & 0x3f) << 16;
logerror("SHIFTER Video Base Address %06x\n", m_shifter_base);
break;
case 0x01:
m_shifter_base = (m_shifter_base & 0x3f0000) | (data << 8);
logerror("SHIFTER Video Base Address %06x\n", m_shifter_base);
break;
}
}
//-------------------------------------------------
// shifter_counter_r -
//-------------------------------------------------
uint8_t st_state::shifter_counter_r(offs_t offset)
{
uint8_t data = 0;
switch (offset)
{
case 0x00:
data = (m_shifter_ofs >> 16) & 0x3f;
break;
case 0x01:
data = (m_shifter_ofs >> 8) & 0xff;
break;
case 0x02:
data = m_shifter_ofs & 0xff;
break;
}
return data;
}
//-------------------------------------------------
// shifter_sync_r -
//-------------------------------------------------
uint8_t st_state::shifter_sync_r()
{
return m_shifter_sync;
}
//-------------------------------------------------
// shifter_sync_w -
//-------------------------------------------------
void st_state::shifter_sync_w(uint8_t data)
{
m_shifter_sync = data;
logerror("SHIFTER Sync %x\n", m_shifter_sync);
set_screen_parameters();
}
//-------------------------------------------------
// shifter_mode_r -
//-------------------------------------------------
uint8_t st_state::shifter_mode_r()
{
return m_shifter_mode;
}
//-------------------------------------------------
// shifter_mode_w -
//-------------------------------------------------
void st_state::shifter_mode_w(uint8_t data)
{
m_shifter_mode = data;
logerror("SHIFTER Mode %x\n", m_shifter_mode);
}
//-------------------------------------------------
// shifter_palette_r -
//-------------------------------------------------
uint16_t st_state::shifter_palette_r(offs_t offset)
{
return m_shifter_palette[offset] | 0xf888;
}
//-------------------------------------------------
// shifter_palette_w -
//-------------------------------------------------
void st_state::shifter_palette_w(offs_t offset, uint16_t data)
{
m_shifter_palette[offset] = data;
// logerror("SHIFTER Palette[%x] = %x\n", offset, data);
m_palette->set_pen_color(offset, pal3bit(data >> 8), pal3bit(data >> 4), pal3bit(data));
}
//**************************************************************************
// STE SHIFTER
//**************************************************************************
//-------------------------------------------------
// shifter_base_low_r -
//-------------------------------------------------
uint8_t ste_state::shifter_base_low_r()
{
return m_shifter_base & 0xfe;
}
//-------------------------------------------------
// shifter_base_low_w -
//-------------------------------------------------
void ste_state::shifter_base_low_w(uint8_t data)
{
m_shifter_base = (m_shifter_base & 0x3fff00) | (data & 0xfe);
logerror("SHIFTER Video Base Address %06x\n", m_shifter_base);
}
//-------------------------------------------------
// shifter_counter_r -
//-------------------------------------------------
uint8_t ste_state::shifter_counter_r(offs_t offset)
{
uint8_t data = 0;
switch (offset)
{
case 0x00:
data = (m_shifter_ofs >> 16) & 0x3f;
break;
case 0x01:
data = (m_shifter_ofs >> 8) & 0xff;
break;
case 0x02:
data = m_shifter_ofs & 0xfe;
break;
}
return data;
}
//-------------------------------------------------
// shifter_counter_w -
//-------------------------------------------------
void ste_state::shifter_counter_w(offs_t offset, uint8_t data)
{
switch (offset)
{
case 0x00:
m_shifter_ofs = (m_shifter_ofs & 0x00fffe) | (data & 0x3f) << 16;
logerror("SHIFTER Video Address Counter %06x\n", m_shifter_ofs);
break;
case 0x01:
m_shifter_ofs = (m_shifter_ofs & 0x3f00fe) | (data << 8);
logerror("SHIFTER Video Address Counter %06x\n", m_shifter_ofs);
break;
case 0x02:
m_shifter_ofs = (m_shifter_ofs & 0x3fff00) | (data & 0xfe);
logerror("SHIFTER Video Address Counter %06x\n", m_shifter_ofs);
break;
}
}
//-------------------------------------------------
// shifter_palette_w -
//-------------------------------------------------
void ste_state::shifter_palette_w(offs_t offset, uint16_t data)
{
int r = ((data >> 7) & 0x0e) | BIT(data, 11);
int g = ((data >> 3) & 0x0e) | BIT(data, 7);
int b = ((data << 1) & 0x0e) | BIT(data, 3);
m_shifter_palette[offset] = data;
logerror("SHIFTER palette %x = %x\n", offset, data);
m_palette->set_pen_color(offset, r, g, b);
}
//-------------------------------------------------
// shifter_lineofs_r -
//-------------------------------------------------
uint8_t ste_state::shifter_lineofs_r()
{
return m_shifter_lineofs;
}
//-------------------------------------------------
// shifter_lineofs_w -
//-------------------------------------------------
void ste_state::shifter_lineofs_w(uint8_t data)
{
m_shifter_lineofs = data;
logerror("SHIFTER Line Offset %x\n", m_shifter_lineofs);
}
//-------------------------------------------------
// shifter_pixelofs_r -
//-------------------------------------------------
uint8_t ste_state::shifter_pixelofs_r()
{
return m_shifter_pixelofs;
}
//-------------------------------------------------
// shifter_pixelofs_w -
//-------------------------------------------------
void ste_state::shifter_pixelofs_w(uint8_t data)
{
m_shifter_pixelofs = data & 0x0f;
logerror("SHIFTER Pixel Offset %x\n", m_shifter_pixelofs);
}
//**************************************************************************
// BLITTER
//**************************************************************************
//-------------------------------------------------
// blitter_source -
//-------------------------------------------------
void st_state::blitter_source()
{
address_space &program = m_maincpu->space(AS_PROGRAM);
uint16_t data = program.read_word(m_blitter_src);
if (m_blitter_src_inc_x < 0)
{
m_blitter_srcbuf = (data << 16) | (m_blitter_srcbuf >> 16);
}
else
{
m_blitter_srcbuf = (m_blitter_srcbuf << 16) | data;
}
}
//-------------------------------------------------
// blitter_hop -
//-------------------------------------------------
uint16_t st_state::blitter_hop()
{
uint16_t source = m_blitter_srcbuf >> (m_blitter_skew & 0x0f);
uint16_t halftone = m_blitter_halftone[m_blitter_ctrl & 0x0f];
if (m_blitter_ctrl & ATARIST_BLITTER_CTRL_SMUDGE)
{
halftone = m_blitter_halftone[source & 0x0f];
}
switch (m_blitter_hop)
{
case 0:
return 0xffff;
case 1:
return halftone;
case 2:
return source;
case 3:
return source & halftone;
}
return 0;
}
//-------------------------------------------------
// blitter_op -
//-------------------------------------------------
void st_state::blitter_op(uint16_t s, uint32_t dstaddr, uint16_t mask)
{
address_space &program = m_maincpu->space(AS_PROGRAM);
uint16_t d = program.read_word(dstaddr);
uint16_t result = 0;
if (m_blitter_op & 0x08) result = (~s & ~d);
if (m_blitter_op & 0x04) result |= (~s & d);
if (m_blitter_op & 0x02) result |= (s & ~d);
if (m_blitter_op & 0x01) result |= (s & d);
program.write_word(dstaddr, result);
}
//-------------------------------------------------
// blitter_tick -
//-------------------------------------------------
void st_state::blitter_tick()
{
do
{
if (m_blitter_skew & ATARIST_BLITTER_SKEW_FXSR)
{
blitter_source();
m_blitter_src += m_blitter_src_inc_x;
}
blitter_source();
blitter_op(blitter_hop(), m_blitter_dst, m_blitter_endmask1);
m_blitter_xcount--;
while (m_blitter_xcount > 0)
{
m_blitter_src += m_blitter_src_inc_x;
m_blitter_dst += m_blitter_dst_inc_x;
if (m_blitter_xcount == 1)
{
if (!(m_blitter_skew & ATARIST_BLITTER_SKEW_NFSR))
{
blitter_source();
}
blitter_op(blitter_hop(), m_blitter_dst, m_blitter_endmask3);
}
else
{
blitter_source();
blitter_op(blitter_hop(), m_blitter_dst, m_blitter_endmask2);
}
m_blitter_xcount--;
}
m_blitter_src += m_blitter_src_inc_y;
m_blitter_dst += m_blitter_dst_inc_y;
if (m_blitter_dst_inc_y < 0)
{
m_blitter_ctrl = (m_blitter_ctrl & 0xf0) | (((m_blitter_ctrl & 0x0f) - 1) & 0x0f);
}
else
{
m_blitter_ctrl = (m_blitter_ctrl & 0xf0) | (((m_blitter_ctrl & 0x0f) + 1) & 0x0f);
}
m_blitter_xcount = m_blitter_xcountl;
m_blitter_ycount--;
}
while (m_blitter_ycount > 0);
m_blitter_ctrl &= 0x7f;
m_mfp->i3_w(0);
}
//-------------------------------------------------
// blitter_halftone_r -
//-------------------------------------------------
uint16_t st_state::blitter_halftone_r(offs_t offset)
{
return m_blitter_halftone[offset];
}
//-------------------------------------------------
// blitter_src_inc_x_r -
//-------------------------------------------------
uint16_t st_state::blitter_src_inc_x_r()
{
return m_blitter_src_inc_x;
}
//-------------------------------------------------
// blitter_src_inc_y_r -
//-------------------------------------------------
uint16_t st_state::blitter_src_inc_y_r()
{
return m_blitter_src_inc_y;
}
//-------------------------------------------------
// blitter_src_r -
//-------------------------------------------------
uint16_t st_state::blitter_src_r(offs_t offset)
{
switch (offset)
{
case 0:
return (m_blitter_src >> 16) & 0xff;
case 1:
return m_blitter_src & 0xfffe;
}
return 0;
}
//-------------------------------------------------
// blitter_end_mask_r -
//-------------------------------------------------
uint16_t st_state::blitter_end_mask_r(offs_t offset)
{
switch (offset)
{
case 0:
return m_blitter_endmask1;
case 1:
return m_blitter_endmask2;
case 2:
return m_blitter_endmask3;
}
return 0;
}
//-------------------------------------------------
// blitter_dst_inc_x_r -
//-------------------------------------------------
uint16_t st_state::blitter_dst_inc_x_r()
{
return m_blitter_dst_inc_x;
}
//-------------------------------------------------
// blitter_dst_inc_y_r -
//-------------------------------------------------
uint16_t st_state::blitter_dst_inc_y_r()
{
return m_blitter_dst_inc_y;
}
//-------------------------------------------------
// blitter_dst_r -
//-------------------------------------------------
uint16_t st_state::blitter_dst_r(offs_t offset)
{
switch (offset)
{
case 0:
return (m_blitter_dst >> 16) & 0xff;
case 1:
return m_blitter_dst & 0xfffe;
}
return 0;
}
//-------------------------------------------------
// blitter_count_x_r -
//-------------------------------------------------
uint16_t st_state::blitter_count_x_r()
{
return m_blitter_xcount;
}
//-------------------------------------------------
// blitter_count_y_r -
//-------------------------------------------------
uint16_t st_state::blitter_count_y_r()
{
return m_blitter_ycount;
}
//-------------------------------------------------
// blitter_op_r -
//-------------------------------------------------
uint16_t st_state::blitter_op_r(offs_t offset, uint16_t mem_mask)
{
if (ACCESSING_BITS_0_7)
{
return m_blitter_hop;
}
else
{
return m_blitter_op;
}
}
//-------------------------------------------------
// blitter_ctrl_r -
//-------------------------------------------------
uint16_t st_state::blitter_ctrl_r(offs_t offset, uint16_t mem_mask)
{
if (ACCESSING_BITS_0_7)
{
return m_blitter_ctrl;
}
else
{
return m_blitter_skew;
}
}
//-------------------------------------------------
// blitter_halftone_w -
//-------------------------------------------------
void st_state::blitter_halftone_w(offs_t offset, uint16_t data)
{
m_blitter_halftone[offset] = data;
}
//-------------------------------------------------
// blitter_src_inc_x_w -
//-------------------------------------------------
void st_state::blitter_src_inc_x_w(uint16_t data)
{
m_blitter_src_inc_x = data & 0xfffe;
}
//-------------------------------------------------
// blitter_src_inc_y_w -
//-------------------------------------------------
void st_state::blitter_src_inc_y_w(uint16_t data)
{
m_blitter_src_inc_y = data & 0xfffe;
}
//-------------------------------------------------
// blitter_src_w -
//-------------------------------------------------
void st_state::blitter_src_w(offs_t offset, uint16_t data)
{
switch (offset)
{
case 0:
m_blitter_src = (data & 0xff) | (m_blitter_src & 0xfffe);
break;
case 1:
m_blitter_src = (m_blitter_src & 0xff0000) | (data & 0xfffe);
break;
}
}
//-------------------------------------------------
// blitter_end_mask_w -
//-------------------------------------------------
void st_state::blitter_end_mask_w(offs_t offset, uint16_t data)
{
switch (offset)
{
case 0:
m_blitter_endmask1 = data;
break;
case 1:
m_blitter_endmask2 = data;
break;
case 2:
m_blitter_endmask3 = data;
break;
}
}
//-------------------------------------------------
// blitter_dst_inc_x_w -
//-------------------------------------------------
void st_state::blitter_dst_inc_x_w(uint16_t data)
{
m_blitter_dst_inc_x = data & 0xfffe;
}
//-------------------------------------------------
// blitter_dst_inc_y_w -
//-------------------------------------------------
void st_state::blitter_dst_inc_y_w(uint16_t data)
{
m_blitter_dst_inc_y = data & 0xfffe;
}
//-------------------------------------------------
// blitter_dst_w -
//-------------------------------------------------
void st_state::blitter_dst_w(offs_t offset, uint16_t data)
{
switch (offset)
{
case 0:
m_blitter_dst = (data & 0xff) | (m_blitter_dst & 0xfffe);
break;
case 1:
m_blitter_dst = (m_blitter_dst & 0xff0000) | (data & 0xfffe);
break;
}
}
//-------------------------------------------------
// blitter_count_x_w -
//-------------------------------------------------
void st_state::blitter_count_x_w(uint16_t data)
{
m_blitter_xcount = data;
}
//-------------------------------------------------
// blitter_count_y_w -
//-------------------------------------------------
void st_state::blitter_count_y_w(uint16_t data)
{
m_blitter_ycount = data;
}
//-------------------------------------------------
// blitter_op_w -
//-------------------------------------------------
void st_state::blitter_op_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
if (ACCESSING_BITS_0_7)
{
m_blitter_hop = (data >> 8) & 0x03;
}
else
{
m_blitter_op = data & 0x0f;
}
}
//-------------------------------------------------
// blitter_ctrl_w -
//-------------------------------------------------
void st_state::blitter_ctrl_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
if (ACCESSING_BITS_0_7)
{
m_blitter_ctrl = (data >> 8) & 0xef;
if (!(m_blitter_ctrl & ATARIST_BLITTER_CTRL_BUSY))
{
if ((data >> 8) & ATARIST_BLITTER_CTRL_BUSY)
{
m_mfp->i3_w(1);
int nops = BLITTER_NOPS[m_blitter_op][m_blitter_hop]; // each NOP takes 4 cycles
timer_set(attotime::from_hz((Y2/4)/(4*nops)), TIMER_BLITTER_TICK);
}
}
}
else
{
m_blitter_skew = data & 0xcf;
}
}
//**************************************************************************
// VIDEO
//**************************************************************************
void st_state::video_start()
{
m_shifter_timer = timer_alloc(TIMER_SHIFTER_TICK);
m_glue_timer = timer_alloc(TIMER_GLUE_TICK);
// m_shifter_timer->adjust(m_screen->time_until_pos(0), 0, attotime::from_hz(Y2/4)); // 125 ns
m_glue_timer->adjust(m_screen->time_until_pos(0), 0, attotime::from_hz(Y2/16)); // 500 ns
m_screen->register_screen_bitmap(m_bitmap);
/* register for state saving */
save_item(NAME(m_shifter_base));
save_item(NAME(m_shifter_ofs));
save_item(NAME(m_shifter_sync));
save_item(NAME(m_shifter_mode));
save_item(NAME(m_shifter_palette));
save_item(NAME(m_shifter_rr));
save_item(NAME(m_shifter_ir));
save_item(NAME(m_shifter_bitplane));
save_item(NAME(m_shifter_shift));
save_item(NAME(m_shifter_h));
save_item(NAME(m_shifter_v));
save_item(NAME(m_shifter_de));
save_item(NAME(m_blitter_halftone));
save_item(NAME(m_blitter_src_inc_x));
save_item(NAME(m_blitter_src_inc_y));
save_item(NAME(m_blitter_dst_inc_x));
save_item(NAME(m_blitter_dst_inc_y));
save_item(NAME(m_blitter_src));
save_item(NAME(m_blitter_dst));
save_item(NAME(m_blitter_endmask1));
save_item(NAME(m_blitter_endmask2));
save_item(NAME(m_blitter_endmask3));
save_item(NAME(m_blitter_xcount));
save_item(NAME(m_blitter_ycount));
save_item(NAME(m_blitter_xcountl));
save_item(NAME(m_blitter_hop));
save_item(NAME(m_blitter_op));
save_item(NAME(m_blitter_ctrl));
save_item(NAME(m_blitter_skew));
set_screen_parameters();
}
void ste_state::video_start()
{
st_state::video_start();
// register for state saving
save_item(NAME(m_shifter_lineofs));
save_item(NAME(m_shifter_pixelofs));
}
void stbook_state::video_start()
{
}
uint32_t st_state::screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
copybitmap(bitmap, m_bitmap, 0, 0, 0, 0, cliprect);
return 0;
}
| johnparker007/mame | src/mame/video/atarist.cpp | C++ | gpl-2.0 | 23,925 |
#define EM_GPIO_0 (1 << 0)
#define EM_GPIO_1 (1 << 1)
#define EM_GPIO_2 (1 << 2)
#define EM_GPIO_3 (1 << 3)
#define EM_GPIO_4 (1 << 4)
#define EM_GPIO_5 (1 << 5)
#define EM_GPIO_6 (1 << 6)
#define EM_GPIO_7 (1 << 7)
#define EM_GPO_0 (1 << 0)
#define EM_GPO_1 (1 << 1)
#define EM_GPO_2 (1 << 2)
#define EM_GPO_3 (1 << 3)
/* em2800 registers */
#define EM2800_R08_AUDIOSRC 0x08
/* em28xx registers */
#define EM28XX_R00_CHIPCFG 0x00
/* em28xx Chip Configuration 0x00 */
#define EM28XX_CHIPCFG_VENDOR_AUDIO 0x80
#define EM28XX_CHIPCFG_I2S_VOLUME_CAPABLE 0x40
#define EM28XX_CHIPCFG_I2S_5_SAMPRATES 0x30
#define EM28XX_CHIPCFG_I2S_3_SAMPRATES 0x20
#define EM28XX_CHIPCFG_AC97 0x10
#define EM28XX_CHIPCFG_AUDIOMASK 0x30
#define EM28XX_R01_CHIPCFG2 0x01
/* em28xx Chip Configuration 2 0x01 */
#define EM28XX_CHIPCFG2_TS_PRESENT 0x10
#define EM28XX_CHIPCFG2_TS_REQ_INTERVAL_MASK 0x0c /* bits 3-2 */
#define EM28XX_CHIPCFG2_TS_REQ_INTERVAL_1MF 0x00
#define EM28XX_CHIPCFG2_TS_REQ_INTERVAL_2MF 0x04
#define EM28XX_CHIPCFG2_TS_REQ_INTERVAL_4MF 0x08
#define EM28XX_CHIPCFG2_TS_REQ_INTERVAL_8MF 0x0c
#define EM28XX_CHIPCFG2_TS_PACKETSIZE_MASK 0x03 /* bits 0-1 */
#define EM28XX_CHIPCFG2_TS_PACKETSIZE_188 0x00
#define EM28XX_CHIPCFG2_TS_PACKETSIZE_376 0x01
#define EM28XX_CHIPCFG2_TS_PACKETSIZE_564 0x02
#define EM28XX_CHIPCFG2_TS_PACKETSIZE_752 0x03
/* GPIO/GPO registers */
#define EM2880_R04_GPO 0x04 /* em2880-em2883 only */
#define EM28XX_R08_GPIO 0x08 /* em2820 or upper */
#define EM28XX_R06_I2C_CLK 0x06
/* em28xx I2C Clock Register (0x06) */
#define EM28XX_I2C_CLK_ACK_LAST_READ 0x80
#define EM28XX_I2C_CLK_WAIT_ENABLE 0x40
#define EM28XX_I2C_EEPROM_ON_BOARD 0x08
#define EM28XX_I2C_EEPROM_KEY_VALID 0x04
#define EM2874_I2C_SECONDARY_BUS_SELECT 0x04 /* em2874 has two i2c busses */
#define EM28XX_I2C_FREQ_1_5_MHZ 0x03 /* bus frequency (bits [1-0]) */
#define EM28XX_I2C_FREQ_25_KHZ 0x02
#define EM28XX_I2C_FREQ_400_KHZ 0x01
#define EM28XX_I2C_FREQ_100_KHZ 0x00
#define EM28XX_R0A_CHIPID 0x0a
#define EM28XX_R0C_USBSUSP 0x0c /* */
#define EM28XX_R0E_AUDIOSRC 0x0e
#define EM28XX_R0F_XCLK 0x0f
/* em28xx XCLK Register (0x0f) */
#define EM28XX_XCLK_AUDIO_UNMUTE 0x80 /* otherwise audio muted */
#define EM28XX_XCLK_I2S_MSB_TIMING 0x40 /* otherwise standard timing */
#define EM28XX_XCLK_IR_RC5_MODE 0x20 /* otherwise NEC mode */
#define EM28XX_XCLK_IR_NEC_CHK_PARITY 0x10
#define EM28XX_XCLK_FREQUENCY_30MHZ 0x00 /* Freq. select (bits [3-0]) */
#define EM28XX_XCLK_FREQUENCY_15MHZ 0x01
#define EM28XX_XCLK_FREQUENCY_10MHZ 0x02
#define EM28XX_XCLK_FREQUENCY_7_5MHZ 0x03
#define EM28XX_XCLK_FREQUENCY_6MHZ 0x04
#define EM28XX_XCLK_FREQUENCY_5MHZ 0x05
#define EM28XX_XCLK_FREQUENCY_4_3MHZ 0x06
#define EM28XX_XCLK_FREQUENCY_12MHZ 0x07
#define EM28XX_XCLK_FREQUENCY_20MHZ 0x08
#define EM28XX_XCLK_FREQUENCY_20MHZ_2 0x09
#define EM28XX_XCLK_FREQUENCY_48MHZ 0x0a
#define EM28XX_XCLK_FREQUENCY_24MHZ 0x0b
#define EM28XX_R10_VINMODE 0x10
#define EM28XX_R11_VINCTRL 0x11
#define EM28XX_R12_VINENABLE 0x12 /* */
#define EM28XX_R14_GAMMA 0x14
#define EM28XX_R15_RGAIN 0x15
#define EM28XX_R16_GGAIN 0x16
#define EM28XX_R17_BGAIN 0x17
#define EM28XX_R18_ROFFSET 0x18
#define EM28XX_R19_GOFFSET 0x19
#define EM28XX_R1A_BOFFSET 0x1a
#define EM28XX_R1B_OFLOW 0x1b
#define EM28XX_R1C_HSTART 0x1c
#define EM28XX_R1D_VSTART 0x1d
#define EM28XX_R1E_CWIDTH 0x1e
#define EM28XX_R1F_CHEIGHT 0x1f
#define EM28XX_R20_YGAIN 0x20
#define EM28XX_R21_YOFFSET 0x21
#define EM28XX_R22_UVGAIN 0x22
#define EM28XX_R23_UOFFSET 0x23
#define EM28XX_R24_VOFFSET 0x24
#define EM28XX_R25_SHARPNESS 0x25
#define EM28XX_R26_COMPR 0x26
#define EM28XX_R27_OUTFMT 0x27
/* em28xx Output Format Register (0x27) */
#define EM28XX_OUTFMT_RGB_8_RGRG 0x00
#define EM28XX_OUTFMT_RGB_8_GRGR 0x01
#define EM28XX_OUTFMT_RGB_8_GBGB 0x02
#define EM28XX_OUTFMT_RGB_8_BGBG 0x03
#define EM28XX_OUTFMT_RGB_16_656 0x04
#define EM28XX_OUTFMT_RGB_8_BAYER 0x08 /* Pattern in Reg 0x10[1-0] */
#define EM28XX_OUTFMT_YUV211 0x10
#define EM28XX_OUTFMT_YUV422_Y0UY1V 0x14
#define EM28XX_OUTFMT_YUV422_Y1UY0V 0x15
#define EM28XX_OUTFMT_YUV411 0x18
#define EM28XX_R28_XMIN 0x28
#define EM28XX_R29_XMAX 0x29
#define EM28XX_R2A_YMIN 0x2a
#define EM28XX_R2B_YMAX 0x2b
#define EM28XX_R30_HSCALELOW 0x30
#define EM28XX_R31_HSCALEHIGH 0x31
#define EM28XX_R32_VSCALELOW 0x32
#define EM28XX_R33_VSCALEHIGH 0x33
#define EM28XX_R40_AC97LSB 0x40
#define EM28XX_R41_AC97MSB 0x41
#define EM28XX_R42_AC97ADDR 0x42
#define EM28XX_R43_AC97BUSY 0x43
#define EM28XX_R45_IR 0x45
/* 0x45 bit 7 - parity bit
bits 6-0 - count
0x46 IR brand
0x47 IR data
*/
/* em2874 registers */
#define EM2874_R50_IR_CONFIG 0x50
#define EM2874_R51_IR 0x51
#define EM2874_R5F_TS_ENABLE 0x5f
#define EM2874_R80_GPIO 0x80
/* em2874 IR config register (0x50) */
#define EM2874_IR_NEC 0x00
#define EM2874_IR_RC5 0x04
#define EM2874_IR_RC5_MODE_0 0x08
#define EM2874_IR_RC5_MODE_6A 0x0b
/* em2874 Transport Stream Enable Register (0x5f) */
#define EM2874_TS1_CAPTURE_ENABLE (1 << 0)
#define EM2874_TS1_FILTER_ENABLE (1 << 1)
#define EM2874_TS1_NULL_DISCARD (1 << 2)
#define EM2874_TS2_CAPTURE_ENABLE (1 << 4)
#define EM2874_TS2_FILTER_ENABLE (1 << 5)
#define EM2874_TS2_NULL_DISCARD (1 << 6)
/* register settings */
#define EM2800_AUDIO_SRC_TUNER 0x0d
#define EM2800_AUDIO_SRC_LINE 0x0c
#define EM28XX_AUDIO_SRC_TUNER 0xc0
#define EM28XX_AUDIO_SRC_LINE 0x80
/* FIXME: Need to be populated with the other chip ID's */
enum em28xx_chip_id {
CHIP_ID_EM2710 = 17,
CHIP_ID_EM2820 = 18, /* Also used by some em2710 */
CHIP_ID_EM2840 = 20,
CHIP_ID_EM2750 = 33,
CHIP_ID_EM2860 = 34,
CHIP_ID_EM2870 = 35,
CHIP_ID_EM2883 = 36,
CHIP_ID_EM2874 = 65,
};
/*
* Registers used by em202 and other AC97 chips
*/
/* Standard AC97 registers */
#define AC97_RESET 0x00
/* Output volumes */
#define AC97_MASTER_VOL 0x02
#define AC97_LINE_LEVEL_VOL 0x04 /* Some devices use for headphones */
#define AC97_MASTER_MONO_VOL 0x06
/* Input volumes */
#define AC97_PC_BEEP_VOL 0x0a
#define AC97_PHONE_VOL 0x0c
#define AC97_MIC_VOL 0x0e
#define AC97_LINEIN_VOL 0x10
#define AC97_CD_VOL 0x12
#define AC97_VIDEO_VOL 0x14
#define AC97_AUX_VOL 0x16
#define AC97_PCM_OUT_VOL 0x18
/* capture registers */
#define AC97_RECORD_SELECT 0x1a
#define AC97_RECORD_GAIN 0x1c
/* control registers */
#define AC97_GENERAL_PURPOSE 0x20
#define AC97_3D_CTRL 0x22
#define AC97_AUD_INT_AND_PAG 0x24
#define AC97_POWER_DOWN_CTRL 0x26
#define AC97_EXT_AUD_ID 0x28
#define AC97_EXT_AUD_CTRL 0x2a
/* Supported rate varies for each AC97 device
if write an unsupported value, it will return the closest one
*/
#define AC97_PCM_OUT_FRONT_SRATE 0x2c
#define AC97_PCM_OUT_SURR_SRATE 0x2e
#define AC97_PCM_OUT_LFE_SRATE 0x30
#define AC97_PCM_IN_SRATE 0x32
/* For devices with more than 2 channels, extra output volumes */
#define AC97_LFE_MASTER_VOL 0x36
#define AC97_SURR_MASTER_VOL 0x38
/* Digital SPDIF output control */
#define AC97_SPDIF_OUT_CTRL 0x3a
/* Vendor ID identifier */
#define AC97_VENDOR_ID1 0x7c
#define AC97_VENDOR_ID2 0x7e
/* EMP202 vendor registers */
#define EM202_EXT_MODEM_CTRL 0x3e
#define EM202_GPIO_CONF 0x4c
#define EM202_GPIO_POLARITY 0x4e
#define EM202_GPIO_STICKY 0x50
#define EM202_GPIO_MASK 0x52
#define EM202_GPIO_STATUS 0x54
#define EM202_SPDIF_OUT_SEL 0x6a
#define EM202_ANTIPOP 0x72
#define EM202_EAPD_GPIO_ACCESS 0x74
| stevelord/PR30 | linux-2.6.31/drivers/media/video/em28xx/em28xx-reg.h | C | gpl-2.0 | 7,720 |
<?php
namespace Drupal\media_library_test_widget\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\media_library\Plugin\Field\FieldWidget\MediaLibraryWidget;
/**
* Plugin implementation of the 'media_library_inception_widget' widget.
*
* This widget is used to simulate the media library widget nested inside
* another widget that performs validation of required fields before there is
* an opportunity to add media.
*
* @FieldWidget(
* id = "media_library_inception_widget",
* label = @Translation("Media library inception widget"),
* description = @Translation("Puts a widget in a widget for testing purposes."),
* field_types = {
* "entity_reference"
* },
* multiple_values = TRUE,
* )
*/
class MediaLibraryInceptionWidget extends MediaLibraryWidget {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
if (empty($element['#element_validate'])) {
$element['#element_validate'] = [];
}
$element['#element_validate'][] = [$this, 'elementValidate'];
return parent::formElement($items, $delta, $element, $form, $form_state);
}
/**
* {@inheritdoc}
*/
public function elementValidate($element, FormStateInterface $form_state, $form) {
$field_name = $element['#field_name'];
$entity = $form_state->getFormObject()->getEntity();
$input = $form_state->getUserInput();
if (!empty($input['_triggering_element_name']) && strpos($input['_triggering_element_name'], 'media-library-update') !== FALSE) {
// This will validate a required field before an upload is completed.
$display = EntityFormDisplay::collectRenderDisplay($entity, 'edit');
$display->extractFormValues($entity, $form, $form_state);
$display->validateFormValues($entity, $form, $form_state);
}
$form_value = $form_state->getValue($field_name);
if (!empty($form_value['media_library_selection'])) {
$entity->set($field_name, $form_value['media_library_selection']);
}
}
}
| tobiasbuhrer/tobiasb | web/core/modules/media_library/tests/modules/media_library_test_widget/src/Plugin/Field/FieldWidget/MediaLibraryInceptionWidget.php | PHP | gpl-2.0 | 2,199 |
#ifndef __ES209RA_PROXIMITY_H__
#define __ES209RA_PROXIMITY_H__
#define PROXIMITY_IOC_MAGIC 'A'
#define PROXIMITY_SET_POWER_STATE _IOW(PROXIMITY_IOC_MAGIC, 0x00, unsigned char)
#define PROXIMITY_GET_POWER_STATE _IOR(PROXIMITY_IOC_MAGIC, 0x01, unsigned char)
#define PROXIMITY_SET_DEVICE_MODE _IOW(PROXIMITY_IOC_MAGIC, 0x02, unsigned char)
#define PROXIMITY_GET_DEVICE_MODE _IOR(PROXIMITY_IOC_MAGIC, 0x03, unsigned char)
#define PROXIMITY_SET_LED_MODE _IOW(PROXIMITY_IOC_MAGIC, 0x04, unsigned char)
#define PROXIMITY_GET_LED_MODE _IOR(PROXIMITY_IOC_MAGIC, 0x05, unsigned char)
#define PROXIMITY_GET_DETECTION_STATE _IOR(PROXIMITY_IOC_MAGIC, 0x06, unsigned char)
#define PROXIMITY_SET_BURST_ON_TIME _IOW(PROXIMITY_IOC_MAGIC, 0x07, unsigned long)
#define PROXIMITY_GET_BURST_ON_TIME _IOR(PROXIMITY_IOC_MAGIC, 0x08, unsigned long)
#define PROXIMITY_DO_SENSING _IOW(PROXIMITY_IOC_MAGIC, 0x09, unsigned char)
#define PROXIMITY_SET_LOCK _IOW(PROXIMITY_IOC_MAGIC, 0x0A, unsigned char)
#define PROXIMITY_SET_UNLOCK _IOW(PROXIMITY_IOC_MAGIC, 0x0B, unsigned char)
#define PROXIMITY_IOC_MAXNR 11
#define PROXIMITY_GPIO_POWER_PIN 146
#define PROXIMITY_GPIO_ENBAR_PIN 109
#define PROXIMITY_GPIO_LEDON_PIN 22
#define PROXIMITY_GPIO_DOUT_PIN 108
#define PROXIMITY_GPIO_POWER_ON 1 /* high active */
#define PROXIMITY_GPIO_POWER_OFF 0
#define PROXIMITY_GPIO_ENBAR_ENABLE 0 /* low active */
#define PROXIMITY_GPIO_ENBAR_DISABLE 1
#define PROXIMITY_GPIO_LEDON_ENABLE 1 /* high active */
#define PROXIMITY_GPIO_LEDON_DISABLE 0
#define PROXIMITY_GPIO_DOUT_ON 0 /* low active */
#define PROXIMITY_GPIO_DOUT_OFF 1
#define PROXIMITY_BURST_ON_TIME_MAX 6000 /* 6.0ms */
#define PROXIMITY_BURST_ON_TIME_MIN 500 /* 0.5ms */
#define PROXIMITY_BURST_ON_TIME_DEFAULT 1500 /* 1.5ms */
#define PROXIMITY_BURST_OFF_TIME_DEFAULT 500000 /* 500ms */
#endif /* __ES209RA_PROXIMITY_H__ */
| skritchz/semc-kernel-qsd8k-ics | include/linux/es209ra_proximity.h | C | gpl-2.0 | 1,941 |
/*
* Copyright (C) 2005-2014 Junjiro R. Okajima
*
* This program, aufs is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* lookup and dentry operations
*/
#ifndef __AUFS_DENTRY_H__
#define __AUFS_DENTRY_H__
#ifdef __KERNEL__
#include <linux/dcache.h>
#include "rwsem.h"
struct au_hdentry {
struct dentry *hd_dentry;
aufs_bindex_t hd_id;
};
struct au_dinfo {
atomic_t di_generation;
struct au_rwsem di_rwsem;
aufs_bindex_t di_bstart, di_bend, di_bwh, di_bdiropq;
unsigned char di_tmpfile; /* to allow the different name */
struct au_hdentry *di_hdentry;
} ____cacheline_aligned_in_smp;
/* ---------------------------------------------------------------------- */
/* dentry.c */
extern const struct dentry_operations aufs_dop;
struct au_branch;
struct dentry *au_sio_lkup_one(struct qstr *name, struct dentry *parent);
int au_h_verify(struct dentry *h_dentry, unsigned int udba, struct inode *h_dir,
struct dentry *h_parent, struct au_branch *br);
int au_lkup_dentry(struct dentry *dentry, aufs_bindex_t bstart, mode_t type);
int au_lkup_neg(struct dentry *dentry, aufs_bindex_t bindex, int wh);
int au_refresh_dentry(struct dentry *dentry, struct dentry *parent);
int au_reval_dpath(struct dentry *dentry, unsigned int sigen);
/* dinfo.c */
void au_di_init_once(void *_di);
struct au_dinfo *au_di_alloc(struct super_block *sb, unsigned int lsc);
void au_di_free(struct au_dinfo *dinfo);
void au_di_swap(struct au_dinfo *a, struct au_dinfo *b);
void au_di_cp(struct au_dinfo *dst, struct au_dinfo *src);
int au_di_init(struct dentry *dentry);
void au_di_fin(struct dentry *dentry);
int au_di_realloc(struct au_dinfo *dinfo, int nbr);
void di_read_lock(struct dentry *d, int flags, unsigned int lsc);
void di_read_unlock(struct dentry *d, int flags);
void di_downgrade_lock(struct dentry *d, int flags);
void di_write_lock(struct dentry *d, unsigned int lsc);
void di_write_unlock(struct dentry *d);
void di_write_lock2_child(struct dentry *d1, struct dentry *d2, int isdir);
void di_write_lock2_parent(struct dentry *d1, struct dentry *d2, int isdir);
void di_write_unlock2(struct dentry *d1, struct dentry *d2);
struct dentry *au_h_dptr(struct dentry *dentry, aufs_bindex_t bindex);
struct dentry *au_h_d_alias(struct dentry *dentry, aufs_bindex_t bindex);
aufs_bindex_t au_dbtail(struct dentry *dentry);
aufs_bindex_t au_dbtaildir(struct dentry *dentry);
void au_set_h_dptr(struct dentry *dentry, aufs_bindex_t bindex,
struct dentry *h_dentry);
int au_digen_test(struct dentry *dentry, unsigned int sigen);
int au_dbrange_test(struct dentry *dentry);
void au_update_digen(struct dentry *dentry);
void au_update_dbrange(struct dentry *dentry, int do_put_zero);
void au_update_dbstart(struct dentry *dentry);
void au_update_dbend(struct dentry *dentry);
int au_find_dbindex(struct dentry *dentry, struct dentry *h_dentry);
/* ---------------------------------------------------------------------- */
static inline struct au_dinfo *au_di(struct dentry *dentry)
{
return dentry->d_fsdata;
}
/* ---------------------------------------------------------------------- */
/* lock subclass for dinfo */
enum {
AuLsc_DI_CHILD, /* child first */
AuLsc_DI_CHILD2, /* rename(2), link(2), and cpup at hnotify */
AuLsc_DI_CHILD3, /* copyup dirs */
AuLsc_DI_PARENT,
AuLsc_DI_PARENT2,
AuLsc_DI_PARENT3,
AuLsc_DI_TMP /* temp for replacing dinfo */
};
/*
* di_read_lock_child, di_write_lock_child,
* di_read_lock_child2, di_write_lock_child2,
* di_read_lock_child3, di_write_lock_child3,
* di_read_lock_parent, di_write_lock_parent,
* di_read_lock_parent2, di_write_lock_parent2,
* di_read_lock_parent3, di_write_lock_parent3,
*/
#define AuReadLockFunc(name, lsc) \
static inline void di_read_lock_##name(struct dentry *d, int flags) \
{ di_read_lock(d, flags, AuLsc_DI_##lsc); }
#define AuWriteLockFunc(name, lsc) \
static inline void di_write_lock_##name(struct dentry *d) \
{ di_write_lock(d, AuLsc_DI_##lsc); }
#define AuRWLockFuncs(name, lsc) \
AuReadLockFunc(name, lsc) \
AuWriteLockFunc(name, lsc)
AuRWLockFuncs(child, CHILD);
AuRWLockFuncs(child2, CHILD2);
AuRWLockFuncs(child3, CHILD3);
AuRWLockFuncs(parent, PARENT);
AuRWLockFuncs(parent2, PARENT2);
AuRWLockFuncs(parent3, PARENT3);
#undef AuReadLockFunc
#undef AuWriteLockFunc
#undef AuRWLockFuncs
#define DiMustNoWaiters(d) AuRwMustNoWaiters(&au_di(d)->di_rwsem)
#define DiMustAnyLock(d) AuRwMustAnyLock(&au_di(d)->di_rwsem)
#define DiMustWriteLock(d) AuRwMustWriteLock(&au_di(d)->di_rwsem)
/* ---------------------------------------------------------------------- */
/* todo: memory barrier? */
static inline unsigned int au_digen(struct dentry *d)
{
return atomic_read(&au_di(d)->di_generation);
}
static inline void au_h_dentry_init(struct au_hdentry *hdentry)
{
hdentry->hd_dentry = NULL;
}
static inline void au_hdput(struct au_hdentry *hd)
{
if (hd)
dput(hd->hd_dentry);
}
static inline aufs_bindex_t au_dbstart(struct dentry *dentry)
{
DiMustAnyLock(dentry);
return au_di(dentry)->di_bstart;
}
static inline aufs_bindex_t au_dbend(struct dentry *dentry)
{
DiMustAnyLock(dentry);
return au_di(dentry)->di_bend;
}
static inline aufs_bindex_t au_dbwh(struct dentry *dentry)
{
DiMustAnyLock(dentry);
return au_di(dentry)->di_bwh;
}
static inline aufs_bindex_t au_dbdiropq(struct dentry *dentry)
{
DiMustAnyLock(dentry);
return au_di(dentry)->di_bdiropq;
}
/* todo: hard/soft set? */
static inline void au_set_dbstart(struct dentry *dentry, aufs_bindex_t bindex)
{
DiMustWriteLock(dentry);
au_di(dentry)->di_bstart = bindex;
}
static inline void au_set_dbend(struct dentry *dentry, aufs_bindex_t bindex)
{
DiMustWriteLock(dentry);
au_di(dentry)->di_bend = bindex;
}
static inline void au_set_dbwh(struct dentry *dentry, aufs_bindex_t bindex)
{
DiMustWriteLock(dentry);
/* dbwh can be outside of bstart - bend range */
au_di(dentry)->di_bwh = bindex;
}
static inline void au_set_dbdiropq(struct dentry *dentry, aufs_bindex_t bindex)
{
DiMustWriteLock(dentry);
au_di(dentry)->di_bdiropq = bindex;
}
/* ---------------------------------------------------------------------- */
#ifdef CONFIG_AUFS_HNOTIFY
static inline void au_digen_dec(struct dentry *d)
{
atomic_dec(&au_di(d)->di_generation);
}
static inline void au_hn_di_reinit(struct dentry *dentry)
{
dentry->d_fsdata = NULL;
}
#else
AuStubVoid(au_hn_di_reinit, struct dentry *dentry __maybe_unused)
#endif /* CONFIG_AUFS_HNOTIFY */
#endif /* __KERNEL__ */
#endif /* __AUFS_DENTRY_H__ */
| yangmenghui/LinuxKernel3_19_V2X | ubuntu/aufs/dentry.h | C | gpl-2.0 | 7,080 |
<?php
class ControllerPaymentPayMate extends Controller {
private $error = array();
public function index() {
$this->load->language('payment/paymate');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('setting/setting');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$this->model_setting_setting->editSetting('paymate', $this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$this->response->redirect($this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL'));
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_edit'] = $this->language->get('text_edit');
$data['text_enabled'] = $this->language->get('text_enabled');
$data['text_disabled'] = $this->language->get('text_disabled');
$data['text_all_zones'] = $this->language->get('text_all_zones');
$data['text_yes'] = $this->language->get('text_yes');
$data['text_no'] = $this->language->get('text_no');
$data['entry_username'] = $this->language->get('entry_username');
$data['entry_password'] = $this->language->get('entry_password');
$data['entry_test'] = $this->language->get('entry_test');
$data['entry_total'] = $this->language->get('entry_total');
$data['entry_order_status'] = $this->language->get('entry_order_status');
$data['entry_geo_zone'] = $this->language->get('entry_geo_zone');
$data['entry_status'] = $this->language->get('entry_status');
$data['entry_sort_order'] = $this->language->get('entry_sort_order');
$data['help_password'] = $this->language->get('help_password');
$data['help_total'] = $this->language->get('help_total');
$data['button_save'] = $this->language->get('button_save');
$data['button_cancel'] = $this->language->get('button_cancel');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->error['username'])) {
$data['error_username'] = $this->error['username'];
} else {
$data['error_username'] = '';
}
if (isset($this->error['password'])) {
$data['error_password'] = $this->error['password'];
} else {
$data['error_password'] = '';
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_payment'),
'href' => $this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('payment/paymate', 'token=' . $this->session->data['token'], 'SSL')
);
$data['action'] = $this->url->link('payment/paymate', 'token=' . $this->session->data['token'], 'SSL');
$data['cancel'] = $this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL');
if (isset($this->request->post['paymate_username'])) {
$data['paymate_username'] = $this->request->post['paymate_username'];
} else {
$data['paymate_username'] = $this->config->get('paymate_username');
}
if (isset($this->request->post['paymate_password'])) {
$data['paymate_username'] = $this->request->post['paymate_username'];
} elseif ($this->config->get('paymate_password')) {
$data['paymate_password'] = $this->config->get('paymate_password');
} else {
$data['paymate_password'] = md5(mt_rand());
}
if (isset($this->request->post['paymate_test'])) {
$data['paymate_test'] = $this->request->post['paymate_test'];
} else {
$data['paymate_test'] = $this->config->get('paymate_test');
}
if (isset($this->request->post['paymate_total'])) {
$data['paymate_total'] = $this->request->post['paymate_total'];
} else {
$data['paymate_total'] = $this->config->get('paymate_total');
}
if (isset($this->request->post['paymate_order_status_id'])) {
$data['paymate_order_status_id'] = $this->request->post['paymate_order_status_id'];
} else {
$data['paymate_order_status_id'] = $this->config->get('paymate_order_status_id');
}
$this->load->model('localisation/order_status');
$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
if (isset($this->request->post['paymate_geo_zone_id'])) {
$data['paymate_geo_zone_id'] = $this->request->post['paymate_geo_zone_id'];
} else {
$data['paymate_geo_zone_id'] = $this->config->get('paymate_geo_zone_id');
}
$this->load->model('localisation/geo_zone');
$data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();
if (isset($this->request->post['paymate_status'])) {
$data['paymate_status'] = $this->request->post['paymate_status'];
} else {
$data['paymate_status'] = $this->config->get('paymate_status');
}
if (isset($this->request->post['paymate_sort_order'])) {
$data['paymate_sort_order'] = $this->request->post['paymate_sort_order'];
} else {
$data['paymate_sort_order'] = $this->config->get('paymate_sort_order');
}
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('payment/paymate.tpl', $data));
}
protected function validate() {
if (!$this->user->hasPermission('modify', 'payment/paymate')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if (!$this->request->post['paymate_username']) {
$this->error['username'] = $this->language->get('error_username');
}
if (!$this->request->post['paymate_password']) {
$this->error['password'] = $this->language->get('error_password');
}
return !$this->error;
}
}
| jneivil/marca | upload/admin/controller/payment/paymate.php | PHP | gpl-3.0 | 5,964 |
/*
* Simple serial driver for Cogent motherboard serial ports
* for use during boot
*/
#include <common.h>
#include "serial.h"
#include <serial.h>
#include <linux/compiler.h>
DECLARE_GLOBAL_DATA_PTR;
#if (CMA_MB_CAPS & CMA_MB_CAP_SERPAR)
#if (defined(CONFIG_8xx) && defined(CONFIG_8xx_CONS_NONE)) || \
(defined(CONFIG_MPC8260) && defined(CONFIG_CONS_NONE))
#if CONFIG_CONS_INDEX == 1
#define CMA_MB_SERIAL_BASE CMA_MB_SERIALA_BASE
#elif CONFIG_CONS_INDEX == 2
#define CMA_MB_SERIAL_BASE CMA_MB_SERIALB_BASE
#elif CONFIG_CONS_INDEX == 3 && (CMA_MB_CAPS & CMA_MB_CAP_SER2)
#define CMA_MB_SERIAL_BASE CMA_MB_SER2A_BASE
#elif CONFIG_CONS_INDEX == 4 && (CMA_MB_CAPS & CMA_MB_CAP_SER2)
#define CMA_MB_SERIAL_BASE CMA_MB_SER2B_BASE
#else
#error CONFIG_CONS_INDEX must be configured for Cogent motherboard serial
#endif
static int cogent_serial_init(void)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_SERIAL_BASE;
cma_mb_reg_write (&mbsp->ser_ier, 0x00); /* turn off interrupts */
serial_setbrg ();
cma_mb_reg_write (&mbsp->ser_lcr, 0x03); /* 8 data, 1 stop, no parity */
cma_mb_reg_write (&mbsp->ser_mcr, 0x03); /* RTS/DTR */
cma_mb_reg_write (&mbsp->ser_fcr, 0x07); /* Clear & enable FIFOs */
return (0);
}
static void cogent_serial_setbrg(void)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_SERIAL_BASE;
unsigned int divisor;
unsigned char lcr;
if ((divisor = br_to_div (gd->baudrate)) == 0)
divisor = DEFDIV;
lcr = cma_mb_reg_read (&mbsp->ser_lcr);
cma_mb_reg_write (&mbsp->ser_lcr, lcr | 0x80); /* Access baud rate(set DLAB) */
cma_mb_reg_write (&mbsp->ser_brl, divisor & 0xff);
cma_mb_reg_write (&mbsp->ser_brh, (divisor >> 8) & 0xff);
cma_mb_reg_write (&mbsp->ser_lcr, lcr); /* unset DLAB */
}
static void cogent_serial_putc(const char c)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_SERIAL_BASE;
if (c == '\n')
serial_putc ('\r');
while ((cma_mb_reg_read (&mbsp->ser_lsr) & LSR_THRE) == 0);
cma_mb_reg_write (&mbsp->ser_thr, c);
}
static int cogent_serial_getc(void)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_SERIAL_BASE;
while ((cma_mb_reg_read (&mbsp->ser_lsr) & LSR_DR) == 0);
return ((int) cma_mb_reg_read (&mbsp->ser_rhr) & 0x7f);
}
static int cogent_serial_tstc(void)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_SERIAL_BASE;
return ((cma_mb_reg_read (&mbsp->ser_lsr) & LSR_DR) != 0);
}
static struct serial_device cogent_serial_drv = {
.name = "cogent_serial",
.start = cogent_serial_init,
.stop = NULL,
.setbrg = cogent_serial_setbrg,
.putc = cogent_serial_putc,
.puts = default_serial_puts,
.getc = cogent_serial_getc,
.tstc = cogent_serial_tstc,
};
void cogent_serial_initialize(void)
{
serial_register(&cogent_serial_drv);
}
__weak struct serial_device *default_serial_console(void)
{
return &cogent_serial_drv;
}
#endif /* CONS_NONE */
#if defined(CONFIG_CMD_KGDB) && \
defined(CONFIG_KGDB_NONE)
#if CONFIG_KGDB_INDEX == CONFIG_CONS_INDEX
#error Console and kgdb are on the same serial port - this is not supported
#endif
#if CONFIG_KGDB_INDEX == 1
#define CMA_MB_KGDB_SER_BASE CMA_MB_SERIALA_BASE
#elif CONFIG_KGDB_INDEX == 2
#define CMA_MB_KGDB_SER_BASE CMA_MB_SERIALB_BASE
#elif CONFIG_KGDB_INDEX == 3 && (CMA_MB_CAPS & CMA_MB_CAP_SER2)
#define CMA_MB_KGDB_SER_BASE CMA_MB_SER2A_BASE
#elif CONFIG_KGDB_INDEX == 4 && (CMA_MB_CAPS & CMA_MB_CAP_SER2)
#define CMA_MB_KGDB_SER_BASE CMA_MB_SER2B_BASE
#else
#error CONFIG_KGDB_INDEX must be configured for Cogent motherboard serial
#endif
void kgdb_serial_init (void)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_KGDB_SER_BASE;
unsigned int divisor;
if ((divisor = br_to_div (CONFIG_KGDB_BAUDRATE)) == 0)
divisor = DEFDIV;
cma_mb_reg_write (&mbsp->ser_ier, 0x00); /* turn off interrupts */
cma_mb_reg_write (&mbsp->ser_lcr, 0x80); /* Access baud rate(set DLAB) */
cma_mb_reg_write (&mbsp->ser_brl, divisor & 0xff);
cma_mb_reg_write (&mbsp->ser_brh, (divisor >> 8) & 0xff);
cma_mb_reg_write (&mbsp->ser_lcr, 0x03); /* 8 data, 1 stop, no parity */
cma_mb_reg_write (&mbsp->ser_mcr, 0x03); /* RTS/DTR */
cma_mb_reg_write (&mbsp->ser_fcr, 0x07); /* Clear & enable FIFOs */
printf ("[on cma10x serial port B] ");
}
void putDebugChar (int c)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_KGDB_SER_BASE;
while ((cma_mb_reg_read (&mbsp->ser_lsr) & LSR_THRE) == 0);
cma_mb_reg_write (&mbsp->ser_thr, c & 0xff);
}
void putDebugStr (const char *str)
{
while (*str != '\0') {
if (*str == '\n')
putDebugChar ('\r');
putDebugChar (*str++);
}
}
int getDebugChar (void)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_KGDB_SER_BASE;
while ((cma_mb_reg_read (&mbsp->ser_lsr) & LSR_DR) == 0);
return ((int) cma_mb_reg_read (&mbsp->ser_rhr) & 0x7f);
}
void kgdb_interruptible (int yes)
{
cma_mb_serial *mbsp = (cma_mb_serial *) CMA_MB_KGDB_SER_BASE;
if (yes == 1) {
printf ("kgdb: turning serial ints on\n");
cma_mb_reg_write (&mbsp->ser_ier, 0xf);
} else {
printf ("kgdb: turning serial ints off\n");
cma_mb_reg_write (&mbsp->ser_ier, 0x0);
}
}
#endif /* KGDB && KGDB_NONE */
#endif /* CAPS & SERPAR */
| r2t2sdr/r2t2 | u-boot/board/cogent/serial.c | C | gpl-3.0 | 5,101 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2010 - 2013 by Martin Steigemann and Wolfgang Bangerth
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include <QtGui>
#include "mainwindow.h"
#include "parameter_delegate.h"
#include "xml_parameter_reader.h"
#include "xml_parameter_writer.h"
namespace dealii
{
namespace ParameterGui
{
MainWindow::MainWindow(const QString &filename)
{
QString settings_file = QDir::currentPath() + "/settings.ini"; // a file for user settings
gui_settings = new QSettings (settings_file, QSettings::IniFormat); // load settings
// Up to now, we do not read any settings,
// but this can be used in the future for customizing the GUI.
tree_widget = new QTreeWidget; // tree for showing XML tags
// Setup the tree and the window first:
tree_widget->header()->setResizeMode(QHeaderView::ResizeToContents); // behavior of the header sections:
// "Interactive: User can resize sections"
// "Fixed: User cannot resize sections"
// "Stretch: Qt will automatically resize sections to fill available space"
// "ResizeToContents: Qt will automatically resize sections to optimal size"
tree_widget->setHeaderLabels(QStringList() << tr("(Sub)Sections/Parameters")
<< tr("Value"));
tree_widget->setMouseTracking(true); // enables mouse events e.g. showing ToolTips
// and documentation in the StatusLine
tree_widget->setEditTriggers(QAbstractItemView::DoubleClicked|
QAbstractItemView::SelectedClicked|
QAbstractItemView::EditKeyPressed);
// set which actions will initiate item editing: Editing starts when:
// DoubleClicked: an item is double clicked
// SelectedClicked: clicking on an already selected item
// EditKeyPressed: the platform edit key has been pressed over an item
// AnyKeyPressed: any key is pressed over an item
tree_widget->setItemDelegate(new ParameterDelegate(1)); // set the delegate for editing items
setCentralWidget(tree_widget);
// connect: if the tree changes, the window will know
connect(tree_widget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(tree_was_modified()));
create_actions(); // create window actions as "Open",...
create_menus(); // and menus
statusBar()->showMessage(tr("Ready, start editing by double-clicking or hitting F2!"));
setWindowTitle(tr("[*]parameterGUI")); // set window title
resize(800, 600); // set window height and width
if (filename.size() > 3) // if there is a file_name, try to load the file.
load_file(filename); // a vliad file has the xml extension, so we require size() > 3
}
void MainWindow::open()
{
if (maybe_save()) // check, if the content was modified
{
QString file_name = // open a file dialog
QFileDialog::getOpenFileName(this, tr("Open XML Parameter File"),
QDir::currentPath(),
tr("XML Files (*.xml)"));
if (!file_name.isEmpty()) // if a file was selected,
load_file(file_name); // load the content
};
}
bool MainWindow::save()
{
if (current_file.isEmpty()) // if there is no file
return save_as(); // to save changes, open a dialog
else
return save_file(current_file); // otherwise save
}
bool MainWindow::save_as()
{
QString file_name = // open a file dialog
QFileDialog::getSaveFileName(this, tr("Save XML Parameter File"),
QDir::currentPath(),
tr("XML Files (*.xml)"));
if (file_name.isEmpty()) // if no file was selected
return false; // return false
else
return save_file(file_name); // otherwise save content to file
}
void MainWindow::about()
{
#ifdef Q_WS_MAC
static QPointer<QMessageBox> old_msg_box;
if (old_msg_box)
{
old_msg_box->show();
old_msg_box->raise();
old_msg_box->activateWindow();
return;
};
#endif
QString title = "About parameterGUI";
QString trAboutparameterGUIcaption;
trAboutparameterGUIcaption = QMessageBox::tr(
"<h3>parameterGUI: A GraphicalUserInterface for parameter handling in deal.II</h3>"
"<p>This program uses Qt version %1.</p>"
).arg(QLatin1String(QT_VERSION_STR));
QString trAboutparameterGUItext;
trAboutparameterGUItext = QMessageBox::tr(
"<p>The parameterGUI is a graphical user interface for editing XML parameter files "
"created by the ParameterHandler class of deal.II. Please see "
"<a href=\"http://www.dealii.org/7.0.0/doxygen/deal.II/classParameterHandler.html\">dealii.org/doc</a> for more information. "
"The parameterGUI parses XML files into a tree structure and provides "
" special editors for different types of parameters.</p>"
"<p><b>Editing parameter values:</b><br>"
"Parameters can be edited by (double-)clicking on the value or "
"by pressing the platform edit key (F2 on Linux) over an parameter item.</p>"
"<p><b>Editors for parameter values:</b>"
" <ul>"
" <li>Integer- and Double-type parameters: SpinBox</li>"
" <li>Booleans: ComboBox</li>"
" <li>Selection: ComboBox</li>"
" <li>File- and DirectoryName parameters: BrowseLineEditor</li>"
" <li>Anything|MultipleSelection|List: LineEditor</li>"
" </ul>"
"</p>"
"<p>Please see <a href=\"http://www.dealii.org\">dealii.org</a> for more information</p>"
"<p><b>Authors:</b><br> "
"Martin Steigemann, <a href=\"mailto:[email protected]\">[email protected]</a><br>"
"Wolfgang Bangerth, <a href=\"mailto:[email protected]\">[email protected]</a></p>"
);
QMessageBox *msg_box = new QMessageBox;
msg_box->setAttribute(Qt::WA_DeleteOnClose);
msg_box->setWindowTitle(title);
msg_box->setText(trAboutparameterGUIcaption);
msg_box->setInformativeText(trAboutparameterGUItext);
QPixmap pm(QLatin1String(":/images/logo_dealii_gui_128.png"));
if (!pm.isNull())
msg_box->setIconPixmap(pm);
#ifdef Q_WS_MAC
old_msg_box = msg_box;
msg_box->show();
#else
msg_box->exec();
#endif
}
void MainWindow::tree_was_modified()
{
setWindowModified(true); // store, that the window was modified
// this is a function from the QMainWindow class
// and we use the windowModified mechanism to show a "*"
// in the window title, if content was modified
}
void MainWindow::show_message ()
{
QString title = "parameterGUI";
info_message = new InfoMessage(this);
info_message->setWindowTitle(title);
info_message->setInfoMessage(tr("Start Editing by double-clicking on the parameter value or"
" by hitting the platform edit key. For example, on Linux this is the F2-key!"));
info_message->showMessage();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (maybe_save()) // reimplement the closeEvent from the QMainWindow class
event->accept(); // check, if we have to save modified content,
else // if content was saved, accept the event,
event->ignore(); // otherwise ignore it
}
void MainWindow::create_actions()
{
QStyle * style = tree_widget->style();
open_act = new QAction(tr("&Open..."), this); // create actions
open_act->setIcon(style->standardPixmap(QStyle::SP_DialogOpenButton)); // and set icons
open_act->setShortcut(Qt::CTRL + Qt::Key_O); // set a short cut
open_act->setStatusTip(tr("Open a XML file")); // set a status tip
connect(open_act, SIGNAL(triggered()), this, SLOT(open())); // and connect
save_act = new QAction(tr("&Save ..."), this);
save_act->setIcon(style->standardPixmap(QStyle::SP_DialogSaveButton));
save_act->setShortcut(Qt::CTRL + Qt::Key_S);
save_act->setStatusTip(tr("Save the current XML file"));
connect(save_act, SIGNAL(triggered()), this, SLOT(save()));
save_as_act = new QAction(tr("&Save As..."), this);
save_as_act->setIcon(style->standardPixmap(QStyle::SP_DialogSaveButton));
save_as_act->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_Q);
save_as_act->setStatusTip(tr("Save the current XML file as"));
connect(save_as_act, SIGNAL(triggered()), this, SLOT(save_as()));
exit_act = new QAction(tr("E&xit"), this);
exit_act->setIcon(style->standardPixmap(QStyle::SP_DialogCloseButton));
exit_act->setShortcut(Qt::CTRL + Qt::Key_Q);
exit_act->setStatusTip(tr("Exit the parameterGUI application"));
connect(exit_act, SIGNAL(triggered()), this, SLOT(close()));
about_act = new QAction(tr("&About"), this);
about_act->setIcon(style->standardPixmap(QStyle::SP_FileDialogInfoView));
about_act->setStatusTip(tr("Show the parameterGUI About box"));
connect(about_act, SIGNAL(triggered()), this, SLOT(about()));
about_qt_act = new QAction(tr("About &Qt"), this);
about_qt_act->setStatusTip(tr("Show the Qt library's About box"));
connect(about_qt_act, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}
void MainWindow::create_menus()
{
file_menu = menuBar()->addMenu(tr("&File")); // create a file menu
file_menu->addAction(open_act); // and add actions
file_menu->addAction(save_act);
file_menu->addAction(save_as_act);
file_menu->addAction(exit_act);
menuBar()->addSeparator();
help_menu = menuBar()->addMenu(tr("&Help")); // create a help menu
help_menu->addAction(about_act);
help_menu->addAction(about_qt_act);
}
bool MainWindow::maybe_save()
{
if (isWindowModified()) // if content was modified
{
QMessageBox::StandardButton ret; // ask, if content should be saved
ret = QMessageBox::warning(this, tr("parameterGUI"),
tr("The content has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Save | QMessageBox::Discard |QMessageBox::Cancel);
if (ret == QMessageBox::Save)
return save();
else if (ret == QMessageBox::Cancel)
return false;
};
return true;
}
bool MainWindow::save_file(const QString &filename)
{
QFile file(filename);
if (!file.open(QFile::WriteOnly | QFile::Text)) // open a file dialog
{
QMessageBox::warning(this, tr("parameterGUI"),
tr("Cannot write file %1:\n%2.")
.arg(filename)
.arg(file.errorString()));
return false;
};
XMLParameterWriter xml_writer(tree_widget); // create a xml_writer
if (!xml_writer.write_xml_file(&file)) // and read the xml file
return false;
statusBar()->showMessage(tr("File saved"), 2000); // if we succeed, show a message
set_current_file(filename); // and reset the window
return true;
}
void MainWindow::load_file(const QString &filename)
{
QFile file(filename);
if (!file.open(QFile::ReadOnly | QFile::Text)) // open the file
{
QMessageBox::warning(this, tr("parameterGUI"),
tr("Cannot read file %1:\n%2.")
.arg(filename)
.arg(file.errorString()));
return;
};
tree_widget->clear(); // clear the tree
XMLParameterReader xml_reader(tree_widget); // and read the xml file
if (!xml_reader.read_xml_file(&file))
{
QMessageBox::warning(this, tr("parameterGUI"),
tr("Parse error in file %1:\n\n%2")
.arg(filename)
.arg(xml_reader.error_string()));
}
else
{
statusBar()->showMessage(tr("File loaded - Start editing by double-clicking or hitting F2"), 25000);
set_current_file(filename); // show a message and set current file
show_message (); // show some informations how values can be edited
};
}
void MainWindow::set_current_file(const QString &filename)
{
// We use the windowModified mechanism from the
// QMainWindow class to indicate in the window title,
// if the content was modified.
// If there is "[*]" in the window title, a * will
// added automatically at this position, if the
// window was modified.
// We set the window title to
// file_name[*] - XMLParameterHandler
current_file = filename; // set the (global) current file to file_name
std::string win_title = (filename.toStdString()); // and create the window title,
if (current_file.isEmpty()) // if file_name is empty
win_title = "[*]parameterGUI"; // set the title to our application name,
else
win_title += "[*] - parameterGUI"; // if there is a file_name, add the
// the file_name and a minus to the title
setWindowTitle(tr(win_title.c_str())); // set the window title
setWindowModified(false); // and reset window modified
}
}
}
| msteigemann/dealii | contrib/parameter_gui/mainwindow.cpp | C++ | lgpl-2.1 | 14,738 |
/**
* 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.apex.malhar.lib.window.accumulation;
import org.junit.Assert;
import org.junit.Test;
import org.apache.apex.malhar.lib.window.Tuple;
import com.datatorrent.api.DefaultInputPort;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.InputOperator;
import com.datatorrent.common.util.BaseOperator;
/**
* Test for {@link ReduceFn}.
*/
public class FoldFnTest
{
public static class NumGen extends BaseOperator implements InputOperator
{
public transient DefaultOutputPort<Integer> output = new DefaultOutputPort<>();
public static int count = 0;
private int i = 0;
public NumGen()
{
count = 0;
i = 0;
}
@Override
public void emitTuples()
{
while (i <= 7) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore it.
}
count++;
if (i >= 0) {
output.emit(i++);
}
}
i = -1;
}
}
public static class Collector extends BaseOperator
{
private static int result;
public transient DefaultInputPort<Tuple.WindowedTuple<Integer>> input = new DefaultInputPort<Tuple.WindowedTuple<Integer>>()
{
@Override
public void process(Tuple.WindowedTuple<Integer> tuple)
{
result = tuple.getValue();
}
};
public int getResult()
{
return result;
}
}
public static class Plus extends FoldFn<Integer, Integer>
{
@Override
public Integer merge(Integer accumulatedValue1, Integer accumulatedValue2)
{
return fold(accumulatedValue1, accumulatedValue2);
}
@Override
public Integer fold(Integer input1, Integer input2)
{
if (input1 == null) {
return input2;
}
return input1 + input2;
}
}
@Test
public void FoldFnTest()
{
FoldFn<String, String> concat = new FoldFn<String, String>()
{
@Override
public String merge(String accumulatedValue1, String accumulatedValue2)
{
return fold(accumulatedValue1, accumulatedValue2);
}
@Override
public String fold(String input1, String input2)
{
return input1 + ", " + input2;
}
};
String[] ss = new String[]{"b", "c", "d", "e"};
String base = "a";
for (String s : ss) {
base = concat.accumulate(base, s);
}
Assert.assertEquals("a, b, c, d, e", base);
}
}
| yogidevendra/incubator-apex-malhar | library/src/test/java/org/apache/apex/malhar/lib/window/accumulation/FoldFnTest.java | Java | apache-2.0 | 3,241 |
/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_
#define TENSORFLOW_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_
// IWYU pragma: private, include "third_party/tensorflow/core/platform/types.h"
// IWYU pragma: friend third_party/tensorflow/core/platform/types.h
namespace tensorflow {
typedef signed char int8;
typedef short int16;
typedef int int32;
typedef long long int64;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
} // namespace tensorflow
#endif // TENSORFLOW_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_
| ivano666/tensorflow | tensorflow/core/platform/default/integral_types.h | C | apache-2.0 | 1,242 |
/**
******************************************************************************
* @file stm32f7xx_ll_tim.h
* @author MCD Application Team
* @brief Header file of TIM LL module.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F7xx_LL_TIM_H
#define __STM32F7xx_LL_TIM_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx.h"
/** @addtogroup STM32F7xx_LL_Driver
* @{
*/
#if defined (TIM1) || defined (TIM8) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM9) || defined (TIM10) || defined (TIM11) || defined (TIM12) || defined (TIM13) || defined (TIM14) || defined (TIM6) || defined (TIM7)
/** @defgroup TIM_LL TIM
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/** @defgroup TIM_LL_Private_Variables TIM Private Variables
* @{
*/
static const uint8_t OFFSET_TAB_CCMRx[] =
{
0x00U, /* 0: TIMx_CH1 */
0x00U, /* 1: TIMx_CH1N */
0x00U, /* 2: TIMx_CH2 */
0x00U, /* 3: TIMx_CH2N */
0x04U, /* 4: TIMx_CH3 */
0x04U, /* 5: TIMx_CH3N */
0x04U, /* 6: TIMx_CH4 */
0x3CU, /* 7: TIMx_CH5 */
0x3CU /* 8: TIMx_CH6 */
};
static const uint8_t SHIFT_TAB_OCxx[] =
{
0U, /* 0: OC1M, OC1FE, OC1PE */
0U, /* 1: - NA */
8U, /* 2: OC2M, OC2FE, OC2PE */
0U, /* 3: - NA */
0U, /* 4: OC3M, OC3FE, OC3PE */
0U, /* 5: - NA */
8U, /* 6: OC4M, OC4FE, OC4PE */
0U, /* 7: OC5M, OC5FE, OC5PE */
8U /* 8: OC6M, OC6FE, OC6PE */
};
static const uint8_t SHIFT_TAB_ICxx[] =
{
0U, /* 0: CC1S, IC1PSC, IC1F */
0U, /* 1: - NA */
8U, /* 2: CC2S, IC2PSC, IC2F */
0U, /* 3: - NA */
0U, /* 4: CC3S, IC3PSC, IC3F */
0U, /* 5: - NA */
8U, /* 6: CC4S, IC4PSC, IC4F */
0U, /* 7: - NA */
0U /* 8: - NA */
};
static const uint8_t SHIFT_TAB_CCxP[] =
{
0U, /* 0: CC1P */
2U, /* 1: CC1NP */
4U, /* 2: CC2P */
6U, /* 3: CC2NP */
8U, /* 4: CC3P */
10U, /* 5: CC3NP */
12U, /* 6: CC4P */
16U, /* 7: CC5P */
20U /* 8: CC6P */
};
static const uint8_t SHIFT_TAB_OISx[] =
{
0U, /* 0: OIS1 */
1U, /* 1: OIS1N */
2U, /* 2: OIS2 */
3U, /* 3: OIS2N */
4U, /* 4: OIS3 */
5U, /* 5: OIS3N */
6U, /* 6: OIS4 */
8U, /* 7: OIS5 */
10U /* 8: OIS6 */
};
/**
* @}
*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup TIM_LL_Private_Constants TIM Private Constants
* @{
*/
#if defined(TIM_BREAK_INPUT_SUPPORT)
/* Defines used for the bit position in the register and perform offsets */
#define TIM_POSITION_BRK_SOURCE POSITION_VAL(Source)
/* Generic bit definitions for TIMx_AF1 register */
#define TIMx_AF1_BKINE TIM1_AF1_BKINE /*!< BRK BKINE input enable */
#if defined(DFSDM1_Channel0)
#define TIMx_AF1_BKDFBKE TIM1_AF1_BKDFBKE /*!< BRK DFSDM1_BREAK[0] enable */
#endif /* DFSDM1_Channel0 */
#define TIMx_AF1_BKINP TIM1_AF1_BKINP /*!< BRK BKIN input polarity */
/* Generic bit definitions for TIMx_AF2 register */
#define TIMx_AF2_BK2INE TIM1_AF2_BK2INE /*!< BRK B2KINE input enable */
#if defined(DFSDM1_Channel0)
#define TIMx_AF2_BK2DFBKE TIM1_AF2_BK2DFBKE /*!< BRK DFSDM_BREAK[0] enable */
#endif /* DFSDM1_Channel0 */
#define TIMx_AF2_BK2INP TIM1_AF2_BK2INP /*!< BRK BK2IN input polarity */
#endif /* TIM_BREAK_INPUT_SUPPORT */
/* Remap mask definitions */
#define TIMx_OR_RMP_SHIFT 16U
#define TIMx_OR_RMP_MASK 0x0000FFFFU
#define TIM2_OR_RMP_MASK (TIM2_OR_ITR1_RMP << TIMx_OR_RMP_SHIFT)
#define TIM5_OR_RMP_MASK (TIM5_OR_TI4_RMP << TIMx_OR_RMP_SHIFT)
#define TIM11_OR_RMP_MASK (TIM11_OR_TI1_RMP << TIMx_OR_RMP_SHIFT)
/* Mask used to set the TDG[x:0] of the DTG bits of the TIMx_BDTR register */
#define DT_DELAY_1 ((uint8_t)0x7FU)
#define DT_DELAY_2 ((uint8_t)0x3FU)
#define DT_DELAY_3 ((uint8_t)0x1FU)
#define DT_DELAY_4 ((uint8_t)0x1FU)
/* Mask used to set the DTG[7:5] bits of the DTG bits of the TIMx_BDTR register */
#define DT_RANGE_1 ((uint8_t)0x00U)
#define DT_RANGE_2 ((uint8_t)0x80U)
#define DT_RANGE_3 ((uint8_t)0xC0U)
#define DT_RANGE_4 ((uint8_t)0xE0U)
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup TIM_LL_Private_Macros TIM Private Macros
* @{
*/
/** @brief Convert channel id into channel index.
* @param __CHANNEL__ This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval none
*/
#define TIM_GET_CHANNEL_INDEX( __CHANNEL__) \
(((__CHANNEL__) == LL_TIM_CHANNEL_CH1) ? 0U :\
((__CHANNEL__) == LL_TIM_CHANNEL_CH1N) ? 1U :\
((__CHANNEL__) == LL_TIM_CHANNEL_CH2) ? 2U :\
((__CHANNEL__) == LL_TIM_CHANNEL_CH2N) ? 3U :\
((__CHANNEL__) == LL_TIM_CHANNEL_CH3) ? 4U :\
((__CHANNEL__) == LL_TIM_CHANNEL_CH3N) ? 5U :\
((__CHANNEL__) == LL_TIM_CHANNEL_CH4) ? 6U :\
((__CHANNEL__) == LL_TIM_CHANNEL_CH5) ? 7U : 8U)
/** @brief Calculate the deadtime sampling period(in ps).
* @param __TIMCLK__ timer input clock frequency (in Hz).
* @param __CKD__ This parameter can be one of the following values:
* @arg @ref LL_TIM_CLOCKDIVISION_DIV1
* @arg @ref LL_TIM_CLOCKDIVISION_DIV2
* @arg @ref LL_TIM_CLOCKDIVISION_DIV4
* @retval none
*/
#define TIM_CALC_DTS(__TIMCLK__, __CKD__) \
(((__CKD__) == LL_TIM_CLOCKDIVISION_DIV1) ? ((uint64_t)1000000000000U/(__TIMCLK__)) : \
((__CKD__) == LL_TIM_CLOCKDIVISION_DIV2) ? ((uint64_t)1000000000000U/((__TIMCLK__) >> 1U)) : \
((uint64_t)1000000000000U/((__TIMCLK__) >> 2U)))
/**
* @}
*/
/* Exported types ------------------------------------------------------------*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup TIM_LL_ES_INIT TIM Exported Init structure
* @{
*/
/**
* @brief TIM Time Base configuration structure definition.
*/
typedef struct
{
uint16_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock.
This parameter can be a number between Min_Data=0x0000 and Max_Data=0xFFFF.
This feature can be modified afterwards using unitary function @ref LL_TIM_SetPrescaler().*/
uint32_t CounterMode; /*!< Specifies the counter mode.
This parameter can be a value of @ref TIM_LL_EC_COUNTERMODE.
This feature can be modified afterwards using unitary function @ref LL_TIM_SetCounterMode().*/
uint32_t Autoreload; /*!< Specifies the auto reload value to be loaded into the active
Auto-Reload Register at the next update event.
This parameter must be a number between Min_Data=0x0000 and Max_Data=0xFFFF.
Some timer instances may support 32 bits counters. In that case this parameter must be a number between 0x0000 and 0xFFFFFFFF.
This feature can be modified afterwards using unitary function @ref LL_TIM_SetAutoReload().*/
uint32_t ClockDivision; /*!< Specifies the clock division.
This parameter can be a value of @ref TIM_LL_EC_CLOCKDIVISION.
This feature can be modified afterwards using unitary function @ref LL_TIM_SetClockDivision().*/
uint8_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the RCR downcounter
reaches zero, an update event is generated and counting restarts
from the RCR value (N).
This means in PWM mode that (N+1) corresponds to:
- the number of PWM periods in edge-aligned mode
- the number of half PWM period in center-aligned mode
This parameter must be a number between 0x00 and 0xFF.
This feature can be modified afterwards using unitary function @ref LL_TIM_SetRepetitionCounter().*/
} LL_TIM_InitTypeDef;
/**
* @brief TIM Output Compare configuration structure definition.
*/
typedef struct
{
uint32_t OCMode; /*!< Specifies the output mode.
This parameter can be a value of @ref TIM_LL_EC_OCMODE.
This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetMode().*/
uint32_t OCState; /*!< Specifies the TIM Output Compare state.
This parameter can be a value of @ref TIM_LL_EC_OCSTATE.
This feature can be modified afterwards using unitary functions @ref LL_TIM_CC_EnableChannel() or @ref LL_TIM_CC_DisableChannel().*/
uint32_t OCNState; /*!< Specifies the TIM complementary Output Compare state.
This parameter can be a value of @ref TIM_LL_EC_OCSTATE.
This feature can be modified afterwards using unitary functions @ref LL_TIM_CC_EnableChannel() or @ref LL_TIM_CC_DisableChannel().*/
uint32_t CompareValue; /*!< Specifies the Compare value to be loaded into the Capture Compare Register.
This parameter can be a number between Min_Data=0x0000 and Max_Data=0xFFFF.
This feature can be modified afterwards using unitary function LL_TIM_OC_SetCompareCHx (x=1..6).*/
uint32_t OCPolarity; /*!< Specifies the output polarity.
This parameter can be a value of @ref TIM_LL_EC_OCPOLARITY.
This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetPolarity().*/
uint32_t OCNPolarity; /*!< Specifies the complementary output polarity.
This parameter can be a value of @ref TIM_LL_EC_OCPOLARITY.
This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetPolarity().*/
uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state.
This parameter can be a value of @ref TIM_LL_EC_OCIDLESTATE.
This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetIdleState().*/
uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state.
This parameter can be a value of @ref TIM_LL_EC_OCIDLESTATE.
This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetIdleState().*/
} LL_TIM_OC_InitTypeDef;
/**
* @brief TIM Input Capture configuration structure definition.
*/
typedef struct
{
uint32_t ICPolarity; /*!< Specifies the active edge of the input signal.
This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/
uint32_t ICActiveInput; /*!< Specifies the input.
This parameter can be a value of @ref TIM_LL_EC_ACTIVEINPUT.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetActiveInput().*/
uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler.
This parameter can be a value of @ref TIM_LL_EC_ICPSC.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/
uint32_t ICFilter; /*!< Specifies the input capture filter.
This parameter can be a value of @ref TIM_LL_EC_IC_FILTER.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/
} LL_TIM_IC_InitTypeDef;
/**
* @brief TIM Encoder interface configuration structure definition.
*/
typedef struct
{
uint32_t EncoderMode; /*!< Specifies the encoder resolution (x2 or x4).
This parameter can be a value of @ref TIM_LL_EC_ENCODERMODE.
This feature can be modified afterwards using unitary function @ref LL_TIM_SetEncoderMode().*/
uint32_t IC1Polarity; /*!< Specifies the active edge of TI1 input.
This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/
uint32_t IC1ActiveInput; /*!< Specifies the TI1 input source
This parameter can be a value of @ref TIM_LL_EC_ACTIVEINPUT.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetActiveInput().*/
uint32_t IC1Prescaler; /*!< Specifies the TI1 input prescaler value.
This parameter can be a value of @ref TIM_LL_EC_ICPSC.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/
uint32_t IC1Filter; /*!< Specifies the TI1 input filter.
This parameter can be a value of @ref TIM_LL_EC_IC_FILTER.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/
uint32_t IC2Polarity; /*!< Specifies the active edge of TI2 input.
This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/
uint32_t IC2ActiveInput; /*!< Specifies the TI2 input source
This parameter can be a value of @ref TIM_LL_EC_ACTIVEINPUT.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetActiveInput().*/
uint32_t IC2Prescaler; /*!< Specifies the TI2 input prescaler value.
This parameter can be a value of @ref TIM_LL_EC_ICPSC.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/
uint32_t IC2Filter; /*!< Specifies the TI2 input filter.
This parameter can be a value of @ref TIM_LL_EC_IC_FILTER.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/
} LL_TIM_ENCODER_InitTypeDef;
/**
* @brief TIM Hall sensor interface configuration structure definition.
*/
typedef struct
{
uint32_t IC1Polarity; /*!< Specifies the active edge of TI1 input.
This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/
uint32_t IC1Prescaler; /*!< Specifies the TI1 input prescaler value.
Prescaler must be set to get a maximum counter period longer than the
time interval between 2 consecutive changes on the Hall inputs.
This parameter can be a value of @ref TIM_LL_EC_ICPSC.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/
uint32_t IC1Filter; /*!< Specifies the TI1 input filter.
This parameter can be a value of @ref TIM_LL_EC_IC_FILTER.
This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/
uint32_t CommutationDelay; /*!< Specifies the compare value to be loaded into the Capture Compare Register.
A positive pulse (TRGO event) is generated with a programmable delay every time
a change occurs on the Hall inputs.
This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF.
This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetCompareCH2().*/
} LL_TIM_HALLSENSOR_InitTypeDef;
/**
* @brief BDTR (Break and Dead Time) structure definition
*/
typedef struct
{
uint32_t OSSRState; /*!< Specifies the Off-State selection used in Run mode.
This parameter can be a value of @ref TIM_LL_EC_OSSR
This feature can be modified afterwards using unitary function @ref LL_TIM_SetOffStates()
@note This bit-field cannot be modified as long as LOCK level 2 has been programmed. */
uint32_t OSSIState; /*!< Specifies the Off-State used in Idle state.
This parameter can be a value of @ref TIM_LL_EC_OSSI
This feature can be modified afterwards using unitary function @ref LL_TIM_SetOffStates()
@note This bit-field cannot be modified as long as LOCK level 2 has been programmed. */
uint32_t LockLevel; /*!< Specifies the LOCK level parameters.
This parameter can be a value of @ref TIM_LL_EC_LOCKLEVEL
@note The LOCK bits can be written only once after the reset. Once the TIMx_BDTR register
has been written, their content is frozen until the next reset.*/
uint8_t DeadTime; /*!< Specifies the delay time between the switching-off and the
switching-on of the outputs.
This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF.
This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetDeadTime()
@note This bit-field can not be modified as long as LOCK level 1, 2 or 3 has been programmed. */
uint16_t BreakState; /*!< Specifies whether the TIM Break input is enabled or not.
This parameter can be a value of @ref TIM_LL_EC_BREAK_ENABLE
This feature can be modified afterwards using unitary functions @ref LL_TIM_EnableBRK() or @ref LL_TIM_DisableBRK()
@note This bit-field can not be modified as long as LOCK level 1 has been programmed. */
uint32_t BreakPolarity; /*!< Specifies the TIM Break Input pin polarity.
This parameter can be a value of @ref TIM_LL_EC_BREAK_POLARITY
This feature can be modified afterwards using unitary function @ref LL_TIM_ConfigBRK()
@note This bit-field can not be modified as long as LOCK level 1 has been programmed. */
uint32_t BreakFilter; /*!< Specifies the TIM Break Filter.
This parameter can be a value of @ref TIM_LL_EC_BREAK_FILTER
This feature can be modified afterwards using unitary function @ref LL_TIM_ConfigBRK()
@note This bit-field can not be modified as long as LOCK level 1 has been programmed. */
uint32_t Break2State; /*!< Specifies whether the TIM Break2 input is enabled or not.
This parameter can be a value of @ref TIM_LL_EC_BREAK2_ENABLE
This feature can be modified afterwards using unitary functions @ref LL_TIM_EnableBRK2() or @ref LL_TIM_DisableBRK2()
@note This bit-field can not be modified as long as LOCK level 1 has been programmed. */
uint32_t Break2Polarity; /*!< Specifies the TIM Break2 Input pin polarity.
This parameter can be a value of @ref TIM_LL_EC_BREAK2_POLARITY
This feature can be modified afterwards using unitary function @ref LL_TIM_ConfigBRK2()
@note This bit-field can not be modified as long as LOCK level 1 has been programmed. */
uint32_t Break2Filter; /*!< Specifies the TIM Break2 Filter.
This parameter can be a value of @ref TIM_LL_EC_BREAK2_FILTER
This feature can be modified afterwards using unitary function @ref LL_TIM_ConfigBRK2()
@note This bit-field can not be modified as long as LOCK level 1 has been programmed. */
uint32_t AutomaticOutput; /*!< Specifies whether the TIM Automatic Output feature is enabled or not.
This parameter can be a value of @ref TIM_LL_EC_AUTOMATICOUTPUT_ENABLE
This feature can be modified afterwards using unitary functions @ref LL_TIM_EnableAutomaticOutput() or @ref LL_TIM_DisableAutomaticOutput()
@note This bit-field can not be modified as long as LOCK level 1 has been programmed. */
} LL_TIM_BDTR_InitTypeDef;
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/* Exported constants --------------------------------------------------------*/
/** @defgroup TIM_LL_Exported_Constants TIM Exported Constants
* @{
*/
/** @defgroup TIM_LL_EC_GET_FLAG Get Flags Defines
* @brief Flags defines which can be used with LL_TIM_ReadReg function.
* @{
*/
#define LL_TIM_SR_UIF TIM_SR_UIF /*!< Update interrupt flag */
#define LL_TIM_SR_CC1IF TIM_SR_CC1IF /*!< Capture/compare 1 interrupt flag */
#define LL_TIM_SR_CC2IF TIM_SR_CC2IF /*!< Capture/compare 2 interrupt flag */
#define LL_TIM_SR_CC3IF TIM_SR_CC3IF /*!< Capture/compare 3 interrupt flag */
#define LL_TIM_SR_CC4IF TIM_SR_CC4IF /*!< Capture/compare 4 interrupt flag */
#define LL_TIM_SR_CC5IF TIM_SR_CC5IF /*!< Capture/compare 5 interrupt flag */
#define LL_TIM_SR_CC6IF TIM_SR_CC6IF /*!< Capture/compare 6 interrupt flag */
#define LL_TIM_SR_COMIF TIM_SR_COMIF /*!< COM interrupt flag */
#define LL_TIM_SR_TIF TIM_SR_TIF /*!< Trigger interrupt flag */
#define LL_TIM_SR_BIF TIM_SR_BIF /*!< Break interrupt flag */
#define LL_TIM_SR_B2IF TIM_SR_B2IF /*!< Second break interrupt flag */
#define LL_TIM_SR_CC1OF TIM_SR_CC1OF /*!< Capture/Compare 1 overcapture flag */
#define LL_TIM_SR_CC2OF TIM_SR_CC2OF /*!< Capture/Compare 2 overcapture flag */
#define LL_TIM_SR_CC3OF TIM_SR_CC3OF /*!< Capture/Compare 3 overcapture flag */
#define LL_TIM_SR_CC4OF TIM_SR_CC4OF /*!< Capture/Compare 4 overcapture flag */
#define LL_TIM_SR_SBIF TIM_SR_SBIF /*!< System Break interrupt flag */
/**
* @}
*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup TIM_LL_EC_BREAK_ENABLE Break Enable
* @{
*/
#define LL_TIM_BREAK_DISABLE 0x00000000U /*!< Break function disabled */
#define LL_TIM_BREAK_ENABLE TIM_BDTR_BKE /*!< Break function enabled */
/**
* @}
*/
/** @defgroup TIM_LL_EC_BREAK2_ENABLE Break2 Enable
* @{
*/
#define LL_TIM_BREAK2_DISABLE 0x00000000U /*!< Break2 function disabled */
#define LL_TIM_BREAK2_ENABLE TIM_BDTR_BK2E /*!< Break2 function enabled */
/**
* @}
*/
/** @defgroup TIM_LL_EC_AUTOMATICOUTPUT_ENABLE Automatic output enable
* @{
*/
#define LL_TIM_AUTOMATICOUTPUT_DISABLE 0x00000000U /*!< MOE can be set only by software */
#define LL_TIM_AUTOMATICOUTPUT_ENABLE TIM_BDTR_AOE /*!< MOE can be set by software or automatically at the next update event */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/** @defgroup TIM_LL_EC_IT IT Defines
* @brief IT defines which can be used with LL_TIM_ReadReg and LL_TIM_WriteReg functions.
* @{
*/
#define LL_TIM_DIER_UIE TIM_DIER_UIE /*!< Update interrupt enable */
#define LL_TIM_DIER_CC1IE TIM_DIER_CC1IE /*!< Capture/compare 1 interrupt enable */
#define LL_TIM_DIER_CC2IE TIM_DIER_CC2IE /*!< Capture/compare 2 interrupt enable */
#define LL_TIM_DIER_CC3IE TIM_DIER_CC3IE /*!< Capture/compare 3 interrupt enable */
#define LL_TIM_DIER_CC4IE TIM_DIER_CC4IE /*!< Capture/compare 4 interrupt enable */
#define LL_TIM_DIER_COMIE TIM_DIER_COMIE /*!< COM interrupt enable */
#define LL_TIM_DIER_TIE TIM_DIER_TIE /*!< Trigger interrupt enable */
#define LL_TIM_DIER_BIE TIM_DIER_BIE /*!< Break interrupt enable */
/**
* @}
*/
/** @defgroup TIM_LL_EC_UPDATESOURCE Update Source
* @{
*/
#define LL_TIM_UPDATESOURCE_REGULAR 0x00000000U /*!< Counter overflow/underflow, Setting the UG bit or Update generation through the slave mode controller generates an update request */
#define LL_TIM_UPDATESOURCE_COUNTER TIM_CR1_URS /*!< Only counter overflow/underflow generates an update request */
/**
* @}
*/
/** @defgroup TIM_LL_EC_ONEPULSEMODE One Pulse Mode
* @{
*/
#define LL_TIM_ONEPULSEMODE_SINGLE TIM_CR1_OPM /*!< Counter is not stopped at update event */
#define LL_TIM_ONEPULSEMODE_REPETITIVE 0x00000000U /*!< Counter stops counting at the next update event */
/**
* @}
*/
/** @defgroup TIM_LL_EC_COUNTERMODE Counter Mode
* @{
*/
#define LL_TIM_COUNTERMODE_UP 0x00000000U /*!<Counter used as upcounter */
#define LL_TIM_COUNTERMODE_DOWN TIM_CR1_DIR /*!< Counter used as downcounter */
#define LL_TIM_COUNTERMODE_CENTER_UP TIM_CR1_CMS_0 /*!< The counter counts up and down alternatively. Output compare interrupt flags of output channels are set only when the counter is counting down. */
#define LL_TIM_COUNTERMODE_CENTER_DOWN TIM_CR1_CMS_1 /*!<The counter counts up and down alternatively. Output compare interrupt flags of output channels are set only when the counter is counting up */
#define LL_TIM_COUNTERMODE_CENTER_UP_DOWN TIM_CR1_CMS /*!< The counter counts up and down alternatively. Output compare interrupt flags of output channels are set only when the counter is counting up or down. */
/**
* @}
*/
/** @defgroup TIM_LL_EC_CLOCKDIVISION Clock Division
* @{
*/
#define LL_TIM_CLOCKDIVISION_DIV1 0x00000000U /*!< tDTS=tCK_INT */
#define LL_TIM_CLOCKDIVISION_DIV2 TIM_CR1_CKD_0 /*!< tDTS=2*tCK_INT */
#define LL_TIM_CLOCKDIVISION_DIV4 TIM_CR1_CKD_1 /*!< tDTS=4*tCK_INT */
/**
* @}
*/
/** @defgroup TIM_LL_EC_COUNTERDIRECTION Counter Direction
* @{
*/
#define LL_TIM_COUNTERDIRECTION_UP 0x00000000U /*!< Timer counter counts up */
#define LL_TIM_COUNTERDIRECTION_DOWN TIM_CR1_DIR /*!< Timer counter counts down */
/**
* @}
*/
/** @defgroup TIM_LL_EC_CCUPDATESOURCE Capture Compare Update Source
* @{
*/
#define LL_TIM_CCUPDATESOURCE_COMG_ONLY 0x00000000U /*!< Capture/compare control bits are updated by setting the COMG bit only */
#define LL_TIM_CCUPDATESOURCE_COMG_AND_TRGI TIM_CR2_CCUS /*!< Capture/compare control bits are updated by setting the COMG bit or when a rising edge occurs on trigger input (TRGI) */
/**
* @}
*/
/** @defgroup TIM_LL_EC_CCDMAREQUEST Capture Compare DMA Request
* @{
*/
#define LL_TIM_CCDMAREQUEST_CC 0x00000000U /*!< CCx DMA request sent when CCx event occurs */
#define LL_TIM_CCDMAREQUEST_UPDATE TIM_CR2_CCDS /*!< CCx DMA requests sent when update event occurs */
/**
* @}
*/
/** @defgroup TIM_LL_EC_LOCKLEVEL Lock Level
* @{
*/
#define LL_TIM_LOCKLEVEL_OFF 0x00000000U /*!< LOCK OFF - No bit is write protected */
#define LL_TIM_LOCKLEVEL_1 TIM_BDTR_LOCK_0 /*!< LOCK Level 1 */
#define LL_TIM_LOCKLEVEL_2 TIM_BDTR_LOCK_1 /*!< LOCK Level 2 */
#define LL_TIM_LOCKLEVEL_3 TIM_BDTR_LOCK /*!< LOCK Level 3 */
/**
* @}
*/
/** @defgroup TIM_LL_EC_CHANNEL Channel
* @{
*/
#define LL_TIM_CHANNEL_CH1 TIM_CCER_CC1E /*!< Timer input/output channel 1 */
#define LL_TIM_CHANNEL_CH1N TIM_CCER_CC1NE /*!< Timer complementary output channel 1 */
#define LL_TIM_CHANNEL_CH2 TIM_CCER_CC2E /*!< Timer input/output channel 2 */
#define LL_TIM_CHANNEL_CH2N TIM_CCER_CC2NE /*!< Timer complementary output channel 2 */
#define LL_TIM_CHANNEL_CH3 TIM_CCER_CC3E /*!< Timer input/output channel 3 */
#define LL_TIM_CHANNEL_CH3N TIM_CCER_CC3NE /*!< Timer complementary output channel 3 */
#define LL_TIM_CHANNEL_CH4 TIM_CCER_CC4E /*!< Timer input/output channel 4 */
#define LL_TIM_CHANNEL_CH5 TIM_CCER_CC5E /*!< Timer output channel 5 */
#define LL_TIM_CHANNEL_CH6 TIM_CCER_CC6E /*!< Timer output channel 6 */
/**
* @}
*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup TIM_LL_EC_OCSTATE Output Configuration State
* @{
*/
#define LL_TIM_OCSTATE_DISABLE 0x00000000U /*!< OCx is not active */
#define LL_TIM_OCSTATE_ENABLE TIM_CCER_CC1E /*!< OCx signal is output on the corresponding output pin */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/** @defgroup TIM_LL_EC_OCMODE Output Configuration Mode
* @{
*/
#define LL_TIM_OCMODE_FROZEN 0x00000000U /*!<The comparison between the output compare register TIMx_CCRy and the counter TIMx_CNT has no effect on the output channel level */
#define LL_TIM_OCMODE_ACTIVE TIM_CCMR1_OC1M_0 /*!<OCyREF is forced high on compare match*/
#define LL_TIM_OCMODE_INACTIVE TIM_CCMR1_OC1M_1 /*!<OCyREF is forced low on compare match*/
#define LL_TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_0) /*!<OCyREF toggles on compare match*/
#define LL_TIM_OCMODE_FORCED_INACTIVE TIM_CCMR1_OC1M_2 /*!<OCyREF is forced low*/
#define LL_TIM_OCMODE_FORCED_ACTIVE (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_0) /*!<OCyREF is forced high*/
#define LL_TIM_OCMODE_PWM1 (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1) /*!<In upcounting, channel y is active as long as TIMx_CNT<TIMx_CCRy else inactive. In downcounting, channel y is inactive as long as TIMx_CNT>TIMx_CCRy else active.*/
#define LL_TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_0) /*!<In upcounting, channel y is inactive as long as TIMx_CNT<TIMx_CCRy else active. In downcounting, channel y is active as long as TIMx_CNT>TIMx_CCRy else inactive*/
#define LL_TIM_OCMODE_RETRIG_OPM1 TIM_CCMR1_OC1M_3 /*!<Retrigerrable OPM mode 1*/
#define LL_TIM_OCMODE_RETRIG_OPM2 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_0) /*!<Retrigerrable OPM mode 2*/
#define LL_TIM_OCMODE_COMBINED_PWM1 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_2) /*!<Combined PWM mode 1*/
#define LL_TIM_OCMODE_COMBINED_PWM2 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) /*!<Combined PWM mode 2*/
#define LL_TIM_OCMODE_ASSYMETRIC_PWM1 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) /*!<Asymmetric PWM mode 1*/
#define LL_TIM_OCMODE_ASSYMETRIC_PWM2 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M) /*!<Asymmetric PWM mode 2*/
/**
* @}
*/
/** @defgroup TIM_LL_EC_OCPOLARITY Output Configuration Polarity
* @{
*/
#define LL_TIM_OCPOLARITY_HIGH 0x00000000U /*!< OCxactive high*/
#define LL_TIM_OCPOLARITY_LOW TIM_CCER_CC1P /*!< OCxactive low*/
/**
* @}
*/
/** @defgroup TIM_LL_EC_OCIDLESTATE Output Configuration Idle State
* @{
*/
#define LL_TIM_OCIDLESTATE_LOW 0x00000000U /*!<OCx=0 (after a dead-time if OC is implemented) when MOE=0*/
#define LL_TIM_OCIDLESTATE_HIGH TIM_CR2_OIS1 /*!<OCx=1 (after a dead-time if OC is implemented) when MOE=0*/
/**
* @}
*/
/** @defgroup TIM_LL_EC_GROUPCH5 GROUPCH5
* @{
*/
#define LL_TIM_GROUPCH5_NONE 0x00000000U /*!< No effect of OC5REF on OC1REFC, OC2REFC and OC3REFC */
#define LL_TIM_GROUPCH5_OC1REFC TIM_CCR5_GC5C1 /*!< OC1REFC is the logical AND of OC1REFC and OC5REF */
#define LL_TIM_GROUPCH5_OC2REFC TIM_CCR5_GC5C2 /*!< OC2REFC is the logical AND of OC2REFC and OC5REF */
#define LL_TIM_GROUPCH5_OC3REFC TIM_CCR5_GC5C3 /*!< OC3REFC is the logical AND of OC3REFC and OC5REF */
/**
* @}
*/
/** @defgroup TIM_LL_EC_ACTIVEINPUT Active Input Selection
* @{
*/
#define LL_TIM_ACTIVEINPUT_DIRECTTI (TIM_CCMR1_CC1S_0 << 16U) /*!< ICx is mapped on TIx */
#define LL_TIM_ACTIVEINPUT_INDIRECTTI (TIM_CCMR1_CC1S_1 << 16U) /*!< ICx is mapped on TIy */
#define LL_TIM_ACTIVEINPUT_TRC (TIM_CCMR1_CC1S << 16U) /*!< ICx is mapped on TRC */
/**
* @}
*/
/** @defgroup TIM_LL_EC_ICPSC Input Configuration Prescaler
* @{
*/
#define LL_TIM_ICPSC_DIV1 0x00000000U /*!< No prescaler, capture is done each time an edge is detected on the capture input */
#define LL_TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0 << 16U) /*!< Capture is done once every 2 events */
#define LL_TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1 << 16U) /*!< Capture is done once every 4 events */
#define LL_TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC << 16U) /*!< Capture is done once every 8 events */
/**
* @}
*/
/** @defgroup TIM_LL_EC_IC_FILTER Input Configuration Filter
* @{
*/
#define LL_TIM_IC_FILTER_FDIV1 0x00000000U /*!< No filter, sampling is done at fDTS */
#define LL_TIM_IC_FILTER_FDIV1_N2 (TIM_CCMR1_IC1F_0 << 16U) /*!< fSAMPLING=fCK_INT, N=2 */
#define LL_TIM_IC_FILTER_FDIV1_N4 (TIM_CCMR1_IC1F_1 << 16U) /*!< fSAMPLING=fCK_INT, N=4 */
#define LL_TIM_IC_FILTER_FDIV1_N8 ((TIM_CCMR1_IC1F_1 | TIM_CCMR1_IC1F_0) << 16U) /*!< fSAMPLING=fCK_INT, N=8 */
#define LL_TIM_IC_FILTER_FDIV2_N6 (TIM_CCMR1_IC1F_2 << 16U) /*!< fSAMPLING=fDTS/2, N=6 */
#define LL_TIM_IC_FILTER_FDIV2_N8 ((TIM_CCMR1_IC1F_2 | TIM_CCMR1_IC1F_0) << 16U) /*!< fSAMPLING=fDTS/2, N=8 */
#define LL_TIM_IC_FILTER_FDIV4_N6 ((TIM_CCMR1_IC1F_2 | TIM_CCMR1_IC1F_1) << 16U) /*!< fSAMPLING=fDTS/4, N=6 */
#define LL_TIM_IC_FILTER_FDIV4_N8 ((TIM_CCMR1_IC1F_2 | TIM_CCMR1_IC1F_1 | TIM_CCMR1_IC1F_0) << 16U) /*!< fSAMPLING=fDTS/4, N=8 */
#define LL_TIM_IC_FILTER_FDIV8_N6 (TIM_CCMR1_IC1F_3 << 16U) /*!< fSAMPLING=fDTS/8, N=6 */
#define LL_TIM_IC_FILTER_FDIV8_N8 ((TIM_CCMR1_IC1F_3 | TIM_CCMR1_IC1F_0) << 16U) /*!< fSAMPLING=fDTS/8, N=8 */
#define LL_TIM_IC_FILTER_FDIV16_N5 ((TIM_CCMR1_IC1F_3 | TIM_CCMR1_IC1F_1) << 16U) /*!< fSAMPLING=fDTS/16, N=5 */
#define LL_TIM_IC_FILTER_FDIV16_N6 ((TIM_CCMR1_IC1F_3 | TIM_CCMR1_IC1F_1 | TIM_CCMR1_IC1F_0) << 16U) /*!< fSAMPLING=fDTS/16, N=6 */
#define LL_TIM_IC_FILTER_FDIV16_N8 ((TIM_CCMR1_IC1F_3 | TIM_CCMR1_IC1F_2) << 16U) /*!< fSAMPLING=fDTS/16, N=8 */
#define LL_TIM_IC_FILTER_FDIV32_N5 ((TIM_CCMR1_IC1F_3 | TIM_CCMR1_IC1F_2 | TIM_CCMR1_IC1F_0) << 16U) /*!< fSAMPLING=fDTS/32, N=5 */
#define LL_TIM_IC_FILTER_FDIV32_N6 ((TIM_CCMR1_IC1F_3 | TIM_CCMR1_IC1F_2 | TIM_CCMR1_IC1F_1) << 16U) /*!< fSAMPLING=fDTS/32, N=6 */
#define LL_TIM_IC_FILTER_FDIV32_N8 (TIM_CCMR1_IC1F << 16U) /*!< fSAMPLING=fDTS/32, N=8 */
/**
* @}
*/
/** @defgroup TIM_LL_EC_IC_POLARITY Input Configuration Polarity
* @{
*/
#define LL_TIM_IC_POLARITY_RISING 0x00000000U /*!< The circuit is sensitive to TIxFP1 rising edge, TIxFP1 is not inverted */
#define LL_TIM_IC_POLARITY_FALLING TIM_CCER_CC1P /*!< The circuit is sensitive to TIxFP1 falling edge, TIxFP1 is inverted */
#define LL_TIM_IC_POLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< The circuit is sensitive to both TIxFP1 rising and falling edges, TIxFP1 is not inverted */
/**
* @}
*/
/** @defgroup TIM_LL_EC_CLOCKSOURCE Clock Source
* @{
*/
#define LL_TIM_CLOCKSOURCE_INTERNAL 0x00000000U /*!< The timer is clocked by the internal clock provided from the RCC */
#define LL_TIM_CLOCKSOURCE_EXT_MODE1 (TIM_SMCR_SMS_2 | TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) /*!< Counter counts at each rising or falling edge on a selected inpu t*/
#define LL_TIM_CLOCKSOURCE_EXT_MODE2 TIM_SMCR_ECE /*!< Counter counts at each rising or falling edge on the external trigger input ETR */
/**
* @}
*/
/** @defgroup TIM_LL_EC_ENCODERMODE Encoder Mode
* @{
*/
#define LL_TIM_ENCODERMODE_X2_TI1 TIM_SMCR_SMS_0 /*!< Encoder mode 1 - Counter counts up/down on TI2FP2 edge depending on TI1FP1 level */
#define LL_TIM_ENCODERMODE_X2_TI2 TIM_SMCR_SMS_1 /*!< Encoder mode 2 - Counter counts up/down on TI1FP1 edge depending on TI2FP2 level */
#define LL_TIM_ENCODERMODE_X4_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) /*!< Encoder mode 3 - Counter counts up/down on both TI1FP1 and TI2FP2 edges depending on the level of the other input l */
/**
* @}
*/
/** @defgroup TIM_LL_EC_TRGO Trigger Output
* @{
*/
#define LL_TIM_TRGO_RESET 0x00000000U /*!< UG bit from the TIMx_EGR register is used as trigger output */
#define LL_TIM_TRGO_ENABLE TIM_CR2_MMS_0 /*!< Counter Enable signal (CNT_EN) is used as trigger output */
#define LL_TIM_TRGO_UPDATE TIM_CR2_MMS_1 /*!< Update event is used as trigger output */
#define LL_TIM_TRGO_CC1IF (TIM_CR2_MMS_1 | TIM_CR2_MMS_0) /*!< CC1 capture or a compare match is used as trigger output */
#define LL_TIM_TRGO_OC1REF TIM_CR2_MMS_2 /*!< OC1REF signal is used as trigger output */
#define LL_TIM_TRGO_OC2REF (TIM_CR2_MMS_2 | TIM_CR2_MMS_0) /*!< OC2REF signal is used as trigger output */
#define LL_TIM_TRGO_OC3REF (TIM_CR2_MMS_2 | TIM_CR2_MMS_1) /*!< OC3REF signal is used as trigger output */
#define LL_TIM_TRGO_OC4REF (TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0) /*!< OC4REF signal is used as trigger output */
/**
* @}
*/
/** @defgroup TIM_LL_EC_TRGO2 Trigger Output 2
* @{
*/
#define LL_TIM_TRGO2_RESET 0x00000000U /*!< UG bit from the TIMx_EGR register is used as trigger output 2 */
#define LL_TIM_TRGO2_ENABLE TIM_CR2_MMS2_0 /*!< Counter Enable signal (CNT_EN) is used as trigger output 2 */
#define LL_TIM_TRGO2_UPDATE TIM_CR2_MMS2_1 /*!< Update event is used as trigger output 2 */
#define LL_TIM_TRGO2_CC1F (TIM_CR2_MMS2_1 | TIM_CR2_MMS2_0) /*!< CC1 capture or a compare match is used as trigger output 2 */
#define LL_TIM_TRGO2_OC1 TIM_CR2_MMS2_2 /*!< OC1REF signal is used as trigger output 2 */
#define LL_TIM_TRGO2_OC2 (TIM_CR2_MMS2_2 | TIM_CR2_MMS2_0) /*!< OC2REF signal is used as trigger output 2 */
#define LL_TIM_TRGO2_OC3 (TIM_CR2_MMS2_2 | TIM_CR2_MMS2_1) /*!< OC3REF signal is used as trigger output 2 */
#define LL_TIM_TRGO2_OC4 (TIM_CR2_MMS2_2 | TIM_CR2_MMS2_1 | TIM_CR2_MMS2_0) /*!< OC4REF signal is used as trigger output 2 */
#define LL_TIM_TRGO2_OC5 TIM_CR2_MMS2_3 /*!< OC5REF signal is used as trigger output 2 */
#define LL_TIM_TRGO2_OC6 (TIM_CR2_MMS2_3 | TIM_CR2_MMS2_0) /*!< OC6REF signal is used as trigger output 2 */
#define LL_TIM_TRGO2_OC4_RISINGFALLING (TIM_CR2_MMS2_3 | TIM_CR2_MMS2_1) /*!< OC4REF rising or falling edges are used as trigger output 2 */
#define LL_TIM_TRGO2_OC6_RISINGFALLING (TIM_CR2_MMS2_3 | TIM_CR2_MMS2_1 | TIM_CR2_MMS2_0) /*!< OC6REF rising or falling edges are used as trigger output 2 */
#define LL_TIM_TRGO2_OC4_RISING_OC6_RISING (TIM_CR2_MMS2_3 | TIM_CR2_MMS2_2) /*!< OC4REF or OC6REF rising edges are used as trigger output 2 */
#define LL_TIM_TRGO2_OC4_RISING_OC6_FALLING (TIM_CR2_MMS2_3 | TIM_CR2_MMS2_2 | TIM_CR2_MMS2_0) /*!< OC4REF rising or OC6REF falling edges are used as trigger output 2 */
#define LL_TIM_TRGO2_OC5_RISING_OC6_RISING (TIM_CR2_MMS2_3 | TIM_CR2_MMS2_2 |TIM_CR2_MMS2_1) /*!< OC5REF or OC6REF rising edges are used as trigger output 2 */
#define LL_TIM_TRGO2_OC5_RISING_OC6_FALLING (TIM_CR2_MMS2_3 | TIM_CR2_MMS2_2 | TIM_CR2_MMS2_1 | TIM_CR2_MMS2_0) /*!< OC5REF rising or OC6REF falling edges are used as trigger output 2 */
/**
* @}
*/
/** @defgroup TIM_LL_EC_SLAVEMODE Slave Mode
* @{
*/
#define LL_TIM_SLAVEMODE_DISABLED 0x00000000U /*!< Slave mode disabled */
#define LL_TIM_SLAVEMODE_RESET TIM_SMCR_SMS_2 /*!< Reset Mode - Rising edge of the selected trigger input (TRGI) reinitializes the counter */
#define LL_TIM_SLAVEMODE_GATED (TIM_SMCR_SMS_2 | TIM_SMCR_SMS_0) /*!< Gated Mode - The counter clock is enabled when the trigger input (TRGI) is high */
#define LL_TIM_SLAVEMODE_TRIGGER (TIM_SMCR_SMS_2 | TIM_SMCR_SMS_1) /*!< Trigger Mode - The counter starts at a rising edge of the trigger TRGI */
#define LL_TIM_SLAVEMODE_COMBINED_RESETTRIGGER TIM_SMCR_SMS_3 /*!< Combined reset + trigger mode - Rising edge of the selected trigger input (TRGI) reinitializes the counter, generates an update of the registers and starts the counter */
/**
* @}
*/
/** @defgroup TIM_LL_EC_TS Trigger Selection
* @{
*/
#define LL_TIM_TS_ITR0 0x00000000U /*!< Internal Trigger 0 (ITR0) is used as trigger input */
#define LL_TIM_TS_ITR1 TIM_SMCR_TS_0 /*!< Internal Trigger 1 (ITR1) is used as trigger input */
#define LL_TIM_TS_ITR2 TIM_SMCR_TS_1 /*!< Internal Trigger 2 (ITR2) is used as trigger input */
#define LL_TIM_TS_ITR3 (TIM_SMCR_TS_0 | TIM_SMCR_TS_1) /*!< Internal Trigger 3 (ITR3) is used as trigger input */
#define LL_TIM_TS_TI1F_ED TIM_SMCR_TS_2 /*!< TI1 Edge Detector (TI1F_ED) is used as trigger input */
#define LL_TIM_TS_TI1FP1 (TIM_SMCR_TS_2 | TIM_SMCR_TS_0) /*!< Filtered Timer Input 1 (TI1FP1) is used as trigger input */
#define LL_TIM_TS_TI2FP2 (TIM_SMCR_TS_2 | TIM_SMCR_TS_1) /*!< Filtered Timer Input 2 (TI12P2) is used as trigger input */
#define LL_TIM_TS_ETRF (TIM_SMCR_TS_2 | TIM_SMCR_TS_1 | TIM_SMCR_TS_0) /*!< Filtered external Trigger (ETRF) is used as trigger input */
/**
* @}
*/
/** @defgroup TIM_LL_EC_ETR_POLARITY External Trigger Polarity
* @{
*/
#define LL_TIM_ETR_POLARITY_NONINVERTED 0x00000000U /*!< ETR is non-inverted, active at high level or rising edge */
#define LL_TIM_ETR_POLARITY_INVERTED TIM_SMCR_ETP /*!< ETR is inverted, active at low level or falling edge */
/**
* @}
*/
/** @defgroup TIM_LL_EC_ETR_PRESCALER External Trigger Prescaler
* @{
*/
#define LL_TIM_ETR_PRESCALER_DIV1 0x00000000U /*!< ETR prescaler OFF */
#define LL_TIM_ETR_PRESCALER_DIV2 TIM_SMCR_ETPS_0 /*!< ETR frequency is divided by 2 */
#define LL_TIM_ETR_PRESCALER_DIV4 TIM_SMCR_ETPS_1 /*!< ETR frequency is divided by 4 */
#define LL_TIM_ETR_PRESCALER_DIV8 TIM_SMCR_ETPS /*!< ETR frequency is divided by 8 */
/**
* @}
*/
/** @defgroup TIM_LL_EC_ETR_FILTER External Trigger Filter
* @{
*/
#define LL_TIM_ETR_FILTER_FDIV1 0x00000000U /*!< No filter, sampling is done at fDTS */
#define LL_TIM_ETR_FILTER_FDIV1_N2 TIM_SMCR_ETF_0 /*!< fSAMPLING=fCK_INT, N=2 */
#define LL_TIM_ETR_FILTER_FDIV1_N4 TIM_SMCR_ETF_1 /*!< fSAMPLING=fCK_INT, N=4 */
#define LL_TIM_ETR_FILTER_FDIV1_N8 (TIM_SMCR_ETF_1 | TIM_SMCR_ETF_0) /*!< fSAMPLING=fCK_INT, N=8 */
#define LL_TIM_ETR_FILTER_FDIV2_N6 TIM_SMCR_ETF_2 /*!< fSAMPLING=fDTS/2, N=6 */
#define LL_TIM_ETR_FILTER_FDIV2_N8 (TIM_SMCR_ETF_2 | TIM_SMCR_ETF_0) /*!< fSAMPLING=fDTS/2, N=8 */
#define LL_TIM_ETR_FILTER_FDIV4_N6 (TIM_SMCR_ETF_2 | TIM_SMCR_ETF_1) /*!< fSAMPLING=fDTS/4, N=6 */
#define LL_TIM_ETR_FILTER_FDIV4_N8 (TIM_SMCR_ETF_2 | TIM_SMCR_ETF_1 | TIM_SMCR_ETF_0) /*!< fSAMPLING=fDTS/4, N=8 */
#define LL_TIM_ETR_FILTER_FDIV8_N6 TIM_SMCR_ETF_3 /*!< fSAMPLING=fDTS/8, N=8 */
#define LL_TIM_ETR_FILTER_FDIV8_N8 (TIM_SMCR_ETF_3 | TIM_SMCR_ETF_0) /*!< fSAMPLING=fDTS/16, N=5 */
#define LL_TIM_ETR_FILTER_FDIV16_N5 (TIM_SMCR_ETF_3 | TIM_SMCR_ETF_1) /*!< fSAMPLING=fDTS/16, N=6 */
#define LL_TIM_ETR_FILTER_FDIV16_N6 (TIM_SMCR_ETF_3 | TIM_SMCR_ETF_1 | TIM_SMCR_ETF_0) /*!< fSAMPLING=fDTS/16, N=8 */
#define LL_TIM_ETR_FILTER_FDIV16_N8 (TIM_SMCR_ETF_3 | TIM_SMCR_ETF_2) /*!< fSAMPLING=fDTS/16, N=5 */
#define LL_TIM_ETR_FILTER_FDIV32_N5 (TIM_SMCR_ETF_3 | TIM_SMCR_ETF_2 | TIM_SMCR_ETF_0) /*!< fSAMPLING=fDTS/32, N=5 */
#define LL_TIM_ETR_FILTER_FDIV32_N6 (TIM_SMCR_ETF_3 | TIM_SMCR_ETF_2 | TIM_SMCR_ETF_1) /*!< fSAMPLING=fDTS/32, N=6 */
#define LL_TIM_ETR_FILTER_FDIV32_N8 TIM_SMCR_ETF /*!< fSAMPLING=fDTS/32, N=8 */
/**
* @}
*/
/** @defgroup TIM_LL_EC_BREAK_POLARITY break polarity
* @{
*/
#define LL_TIM_BREAK_POLARITY_LOW 0x00000000U /*!< Break input BRK is active low */
#define LL_TIM_BREAK_POLARITY_HIGH TIM_BDTR_BKP /*!< Break input BRK is active high */
/**
* @}
*/
/** @defgroup TIM_LL_EC_BREAK_FILTER break filter
* @{
*/
#define LL_TIM_BREAK_FILTER_FDIV1 0x00000000U /*!< No filter, BRK acts asynchronously */
#define LL_TIM_BREAK_FILTER_FDIV1_N2 0x00010000U /*!< fSAMPLING=fCK_INT, N=2 */
#define LL_TIM_BREAK_FILTER_FDIV1_N4 0x00020000U /*!< fSAMPLING=fCK_INT, N=4 */
#define LL_TIM_BREAK_FILTER_FDIV1_N8 0x00030000U /*!< fSAMPLING=fCK_INT, N=8 */
#define LL_TIM_BREAK_FILTER_FDIV2_N6 0x00040000U /*!< fSAMPLING=fDTS/2, N=6 */
#define LL_TIM_BREAK_FILTER_FDIV2_N8 0x00050000U /*!< fSAMPLING=fDTS/2, N=8 */
#define LL_TIM_BREAK_FILTER_FDIV4_N6 0x00060000U /*!< fSAMPLING=fDTS/4, N=6 */
#define LL_TIM_BREAK_FILTER_FDIV4_N8 0x00070000U /*!< fSAMPLING=fDTS/4, N=8 */
#define LL_TIM_BREAK_FILTER_FDIV8_N6 0x00080000U /*!< fSAMPLING=fDTS/8, N=6 */
#define LL_TIM_BREAK_FILTER_FDIV8_N8 0x00090000U /*!< fSAMPLING=fDTS/8, N=8 */
#define LL_TIM_BREAK_FILTER_FDIV16_N5 0x000A0000U /*!< fSAMPLING=fDTS/16, N=5 */
#define LL_TIM_BREAK_FILTER_FDIV16_N6 0x000B0000U /*!< fSAMPLING=fDTS/16, N=6 */
#define LL_TIM_BREAK_FILTER_FDIV16_N8 0x000C0000U /*!< fSAMPLING=fDTS/16, N=8 */
#define LL_TIM_BREAK_FILTER_FDIV32_N5 0x000D0000U /*!< fSAMPLING=fDTS/32, N=5 */
#define LL_TIM_BREAK_FILTER_FDIV32_N6 0x000E0000U /*!< fSAMPLING=fDTS/32, N=6 */
#define LL_TIM_BREAK_FILTER_FDIV32_N8 0x000F0000U /*!< fSAMPLING=fDTS/32, N=8 */
/**
* @}
*/
/** @defgroup TIM_LL_EC_BREAK2_POLARITY BREAK2 POLARITY
* @{
*/
#define LL_TIM_BREAK2_POLARITY_LOW 0x00000000U /*!< Break input BRK2 is active low */
#define LL_TIM_BREAK2_POLARITY_HIGH TIM_BDTR_BK2P /*!< Break input BRK2 is active high */
/**
* @}
*/
/** @defgroup TIM_LL_EC_BREAK2_FILTER BREAK2 FILTER
* @{
*/
#define LL_TIM_BREAK2_FILTER_FDIV1 0x00000000U /*!< No filter, BRK acts asynchronously */
#define LL_TIM_BREAK2_FILTER_FDIV1_N2 0x00100000U /*!< fSAMPLING=fCK_INT, N=2 */
#define LL_TIM_BREAK2_FILTER_FDIV1_N4 0x00200000U /*!< fSAMPLING=fCK_INT, N=4 */
#define LL_TIM_BREAK2_FILTER_FDIV1_N8 0x00300000U /*!< fSAMPLING=fCK_INT, N=8 */
#define LL_TIM_BREAK2_FILTER_FDIV2_N6 0x00400000U /*!< fSAMPLING=fDTS/2, N=6 */
#define LL_TIM_BREAK2_FILTER_FDIV2_N8 0x00500000U /*!< fSAMPLING=fDTS/2, N=8 */
#define LL_TIM_BREAK2_FILTER_FDIV4_N6 0x00600000U /*!< fSAMPLING=fDTS/4, N=6 */
#define LL_TIM_BREAK2_FILTER_FDIV4_N8 0x00700000U /*!< fSAMPLING=fDTS/4, N=8 */
#define LL_TIM_BREAK2_FILTER_FDIV8_N6 0x00800000U /*!< fSAMPLING=fDTS/8, N=6 */
#define LL_TIM_BREAK2_FILTER_FDIV8_N8 0x00900000U /*!< fSAMPLING=fDTS/8, N=8 */
#define LL_TIM_BREAK2_FILTER_FDIV16_N5 0x00A00000U /*!< fSAMPLING=fDTS/16, N=5 */
#define LL_TIM_BREAK2_FILTER_FDIV16_N6 0x00B00000U /*!< fSAMPLING=fDTS/16, N=6 */
#define LL_TIM_BREAK2_FILTER_FDIV16_N8 0x00C00000U /*!< fSAMPLING=fDTS/16, N=8 */
#define LL_TIM_BREAK2_FILTER_FDIV32_N5 0x00D00000U /*!< fSAMPLING=fDTS/32, N=5 */
#define LL_TIM_BREAK2_FILTER_FDIV32_N6 0x00E00000U /*!< fSAMPLING=fDTS/32, N=6 */
#define LL_TIM_BREAK2_FILTER_FDIV32_N8 0x00F00000U /*!< fSAMPLING=fDTS/32, N=8 */
/**
* @}
*/
/** @defgroup TIM_LL_EC_OSSI OSSI
* @{
*/
#define LL_TIM_OSSI_DISABLE 0x00000000U /*!< When inactive, OCx/OCxN outputs are disabled */
#define LL_TIM_OSSI_ENABLE TIM_BDTR_OSSI /*!< When inactive, OxC/OCxN outputs are first forced with their inactive level then forced to their idle level after the deadtime */
/**
* @}
*/
/** @defgroup TIM_LL_EC_OSSR OSSR
* @{
*/
#define LL_TIM_OSSR_DISABLE 0x00000000U /*!< When inactive, OCx/OCxN outputs are disabled */
#define LL_TIM_OSSR_ENABLE TIM_BDTR_OSSR /*!< When inactive, OC/OCN outputs are enabled with their inactive level as soon as CCxE=1 or CCxNE=1 */
/**
* @}
*/
#if defined(TIM_BREAK_INPUT_SUPPORT)
/** @defgroup TIM_LL_EC_BREAK_INPUT BREAK INPUT
* @{
*/
#define LL_TIM_BREAK_INPUT_BKIN 0x00000000U /*!< TIMx_BKIN input */
#define LL_TIM_BREAK_INPUT_BKIN2 0x00000004U /*!< TIMx_BKIN2 input */
/**
* @}
*/
/** @defgroup TIM_LL_EC_BKIN_SOURCE BKIN SOURCE
* @{
*/
#define LL_TIM_BKIN_SOURCE_BKIN TIM1_AF1_BKINE /*!< BKIN input from AF controller */
#define LL_TIM_BKIN_SOURCE_DF1BK TIM1_AF1_BKDF1BKE /*!< internal signal: DFSDM1 break output */
/**
* @}
*/
/** @defgroup TIM_LL_EC_BKIN_POLARITY BKIN POLARITY
* @{
*/
#define LL_TIM_BKIN_POLARITY_LOW TIM1_AF1_BKINP /*!< BRK BKIN input is active low */
#define LL_TIM_BKIN_POLARITY_HIGH 0x00000000U /*!< BRK BKIN input is active high */
/**
* @}
*/
#endif /* TIM_BREAK_INPUT_SUPPORT */
/** @defgroup TIM_LL_EC_DMABURST_BASEADDR DMA Burst Base Address
* @{
*/
#define LL_TIM_DMABURST_BASEADDR_CR1 0x00000000U /*!< TIMx_CR1 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CR2 TIM_DCR_DBA_0 /*!< TIMx_CR2 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_SMCR TIM_DCR_DBA_1 /*!< TIMx_SMCR register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_DIER (TIM_DCR_DBA_1 | TIM_DCR_DBA_0) /*!< TIMx_DIER register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_SR TIM_DCR_DBA_2 /*!< TIMx_SR register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_EGR (TIM_DCR_DBA_2 | TIM_DCR_DBA_0) /*!< TIMx_EGR register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCMR1 (TIM_DCR_DBA_2 | TIM_DCR_DBA_1) /*!< TIMx_CCMR1 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCMR2 (TIM_DCR_DBA_2 | TIM_DCR_DBA_1 | TIM_DCR_DBA_0) /*!< TIMx_CCMR2 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCER TIM_DCR_DBA_3 /*!< TIMx_CCER register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CNT (TIM_DCR_DBA_3 | TIM_DCR_DBA_0) /*!< TIMx_CNT register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_PSC (TIM_DCR_DBA_3 | TIM_DCR_DBA_1) /*!< TIMx_PSC register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_ARR (TIM_DCR_DBA_3 | TIM_DCR_DBA_1 | TIM_DCR_DBA_0) /*!< TIMx_ARR register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_RCR (TIM_DCR_DBA_3 | TIM_DCR_DBA_2) /*!< TIMx_RCR register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCR1 (TIM_DCR_DBA_3 | TIM_DCR_DBA_2 | TIM_DCR_DBA_0) /*!< TIMx_CCR1 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCR2 (TIM_DCR_DBA_3 | TIM_DCR_DBA_2 | TIM_DCR_DBA_1) /*!< TIMx_CCR2 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCR3 (TIM_DCR_DBA_3 | TIM_DCR_DBA_2 | TIM_DCR_DBA_1 | TIM_DCR_DBA_0) /*!< TIMx_CCR3 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCR4 TIM_DCR_DBA_4 /*!< TIMx_CCR4 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_BDTR (TIM_DCR_DBA_4 | TIM_DCR_DBA_0) /*!< TIMx_BDTR register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCMR3 (TIM_DCR_DBA_4 | TIM_DCR_DBA_1) /*!< TIMx_CCMR3 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCR5 (TIM_DCR_DBA_4 | TIM_DCR_DBA_1 | TIM_DCR_DBA_0) /*!< TIMx_CCR5 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_CCR6 (TIM_DCR_DBA_4 | TIM_DCR_DBA_2) /*!< TIMx_CCR6 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_OR (TIM_DCR_DBA_4 | TIM_DCR_DBA_2 | TIM_DCR_DBA_0) /*!< TIMx_OR register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_AF1 (TIM_DCR_DBA_4 | TIM_DCR_DBA_2 | TIM_DCR_DBA_1) /*!< TIMx_AF1 register is the DMA base address for DMA burst */
#define LL_TIM_DMABURST_BASEADDR_AF2 (TIM_DCR_DBA_4 | TIM_DCR_DBA_2 | TIM_DCR_DBA_1 | TIM_DCR_DBA_0) /*!< TIMx_AF2 register is the DMA base address for DMA burst */
/**
* @}
*/
/** @defgroup TIM_LL_EC_DMABURST_LENGTH DMA Burst Length
* @{
*/
#define LL_TIM_DMABURST_LENGTH_1TRANSFER 0x00000000U /*!< Transfer is done to 1 register starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_2TRANSFERS TIM_DCR_DBL_0 /*!< Transfer is done to 2 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_3TRANSFERS TIM_DCR_DBL_1 /*!< Transfer is done to 3 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_4TRANSFERS (TIM_DCR_DBL_1 | TIM_DCR_DBL_0) /*!< Transfer is done to 4 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_5TRANSFERS TIM_DCR_DBL_2 /*!< Transfer is done to 5 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_6TRANSFERS (TIM_DCR_DBL_2 | TIM_DCR_DBL_0) /*!< Transfer is done to 6 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_7TRANSFERS (TIM_DCR_DBL_2 | TIM_DCR_DBL_1) /*!< Transfer is done to 7 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_8TRANSFERS (TIM_DCR_DBL_2 | TIM_DCR_DBL_1 | TIM_DCR_DBL_0) /*!< Transfer is done to 1 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_9TRANSFERS TIM_DCR_DBL_3 /*!< Transfer is done to 9 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_10TRANSFERS (TIM_DCR_DBL_3 | TIM_DCR_DBL_0) /*!< Transfer is done to 10 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_11TRANSFERS (TIM_DCR_DBL_3 | TIM_DCR_DBL_1) /*!< Transfer is done to 11 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_12TRANSFERS (TIM_DCR_DBL_3 | TIM_DCR_DBL_1 | TIM_DCR_DBL_0) /*!< Transfer is done to 12 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_13TRANSFERS (TIM_DCR_DBL_3 | TIM_DCR_DBL_2) /*!< Transfer is done to 13 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_14TRANSFERS (TIM_DCR_DBL_3 | TIM_DCR_DBL_2 | TIM_DCR_DBL_0) /*!< Transfer is done to 14 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_15TRANSFERS (TIM_DCR_DBL_3 | TIM_DCR_DBL_2 | TIM_DCR_DBL_1) /*!< Transfer is done to 15 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_16TRANSFERS (TIM_DCR_DBL_3 | TIM_DCR_DBL_2 | TIM_DCR_DBL_1 | TIM_DCR_DBL_0) /*!< Transfer is done to 16 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_17TRANSFERS TIM_DCR_DBL_4 /*!< Transfer is done to 17 registers starting from the DMA burst base address */
#define LL_TIM_DMABURST_LENGTH_18TRANSFERS (TIM_DCR_DBL_4 | TIM_DCR_DBL_0) /*!< Transfer is done to 18 registers starting from the DMA burst base address */
/**
* @}
*/
/** @defgroup TIM_LL_EC_TIM2_ITR1_RMP_TIM8 TIM2 Internal Trigger1 Remap TIM8
* @{
*/
#define LL_TIM_TIM2_ITR1_RMP_TIM8_TRGO TIM2_OR_RMP_MASK /*!< TIM2_ITR1 is connected to TIM8_TRGO */
#define LL_TIM_TIM2_ITR1_RMP_ETH_PTP (TIM2_OR_ITR1_RMP_0 | TIM2_OR_RMP_MASK) /*!< TIM2_ITR1 is connected to ETH_PTP */
#define LL_TIM_TIM2_ITR1_RMP_OTG_FS_SOF (TIM2_OR_ITR1_RMP_1 | TIM2_OR_RMP_MASK) /*!< TIM2_ITR1 is connected to OTG_FS SOF */
#define LL_TIM_TIM2_ITR1_RMP_OTG_HS_SOF (TIM2_OR_ITR1_RMP | TIM2_OR_RMP_MASK) /*!< TIM2_ITR1 is connected to OTG_HS SOF */
/**
* @}
*/
/** @defgroup TIM_LL_EC_TIM5_TI4_RMP TIM5 External Input Ch4 Remap
* @{
*/
#define LL_TIM_TIM5_TI4_RMP_GPIO TIM5_OR_RMP_MASK /*!< TIM5 channel 4 is connected to GPIO */
#define LL_TIM_TIM5_TI4_RMP_LSI (TIM5_OR_TI4_RMP_0 | TIM5_OR_RMP_MASK) /*!< TIM5 channel 4 is connected to LSI internal clock */
#define LL_TIM_TIM5_TI4_RMP_LSE (TIM5_OR_TI4_RMP_1 | TIM5_OR_RMP_MASK) /*!< TIM5 channel 4 is connected to LSE */
#define LL_TIM_TIM5_TI4_RMP_RTC (TIM5_OR_TI4_RMP | TIM5_OR_RMP_MASK) /*!< TIM5 channel 4 is connected to RTC wakeup interrupt */
/**
* @}
*/
/** @defgroup TIM_LL_EC_TIM11_TI1_RMP TIM11 External Input Capture 1 Remap
* @{
*/
#define LL_TIM_TIM11_TI1_RMP_GPIO TIM11_OR_RMP_MASK /*!< TIM11 channel 1 is connected to GPIO */
#define LL_TIM_TIM11_TI1_RMP_SPDIFRX (TIM11_OR_TI1_RMP_0 | TIM11_OR_RMP_MASK) /*!< TIM11 channel 1 is connected to SPDIFRX */
#define LL_TIM_TIM11_TI1_RMP_HSE (TIM11_OR_TI1_RMP_1 | TIM11_OR_RMP_MASK) /*!< TIM11 channel 1 is connected to HSE */
#define LL_TIM_TIM11_TI1_RMP_MCO1 (TIM11_OR_TI1_RMP | TIM11_OR_RMP_MASK) /*!< TIM11 channel 1 is connected to MCO1 */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/** @defgroup TIM_LL_Exported_Macros TIM Exported Macros
* @{
*/
/** @defgroup TIM_LL_EM_WRITE_READ Common Write and read registers Macros
* @{
*/
/**
* @brief Write a value in TIM register.
* @param __INSTANCE__ TIM Instance
* @param __REG__ Register to be written
* @param __VALUE__ Value to be written in the register
* @retval None
*/
#define LL_TIM_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__))
/**
* @brief Read a value in TIM register.
* @param __INSTANCE__ TIM Instance
* @param __REG__ Register to be read
* @retval Register value
*/
#define LL_TIM_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__)
/**
* @}
*/
/** @defgroup TIM_LL_EM_Exported_Macros Exported_Macros
* @{
*/
/**
* @brief HELPER macro retrieving the UIFCPY flag from the counter value.
* @note ex: @ref __LL_TIM_GETFLAG_UIFCPY (@ref LL_TIM_GetCounter ());
* @note Relevant only if UIF flag remapping has been enabled (UIF status bit is copied
* to TIMx_CNT register bit 31)
* @param __CNT__ Counter value
* @retval UIF status bit
*/
#define __LL_TIM_GETFLAG_UIFCPY(__CNT__) \
(READ_BIT((__CNT__), TIM_CNT_UIFCPY) >> TIM_CNT_UIFCPY_Pos)
/**
* @brief HELPER macro calculating DTG[0:7] in the TIMx_BDTR register to achieve the requested dead time duration.
* @note ex: @ref __LL_TIM_CALC_DEADTIME (80000000, @ref LL_TIM_GetClockDivision (), 120);
* @param __TIMCLK__ timer input clock frequency (in Hz)
* @param __CKD__ This parameter can be one of the following values:
* @arg @ref LL_TIM_CLOCKDIVISION_DIV1
* @arg @ref LL_TIM_CLOCKDIVISION_DIV2
* @arg @ref LL_TIM_CLOCKDIVISION_DIV4
* @param __DT__ deadtime duration (in ns)
* @retval DTG[0:7]
*/
#define __LL_TIM_CALC_DEADTIME(__TIMCLK__, __CKD__, __DT__) \
( (((uint64_t)((__DT__)*1000U)) < ((DT_DELAY_1+1U) * TIM_CALC_DTS((__TIMCLK__), (__CKD__)))) ? (uint8_t)(((uint64_t)((__DT__)*1000U) / TIM_CALC_DTS((__TIMCLK__), (__CKD__))) & DT_DELAY_1) : \
(((uint64_t)((__DT__)*1000U)) < (64U + (DT_DELAY_2+1U)) * 2U * TIM_CALC_DTS((__TIMCLK__), (__CKD__))) ? (uint8_t)(DT_RANGE_2 | ((uint8_t)((uint8_t)((((uint64_t)((__DT__)*1000U))/ TIM_CALC_DTS((__TIMCLK__), (__CKD__))) >> 1U) - (uint8_t) 64U) & DT_DELAY_2)) :\
(((uint64_t)((__DT__)*1000U)) < (32U + (DT_DELAY_3+1U)) * 8U * TIM_CALC_DTS((__TIMCLK__), (__CKD__))) ? (uint8_t)(DT_RANGE_3 | ((uint8_t)((uint8_t)(((((uint64_t)(__DT__)*1000U))/ TIM_CALC_DTS((__TIMCLK__), (__CKD__))) >> 3U) - (uint8_t) 32U) & DT_DELAY_3)) :\
(((uint64_t)((__DT__)*1000U)) < (32U + (DT_DELAY_4+1U)) * 16U * TIM_CALC_DTS((__TIMCLK__), (__CKD__))) ? (uint8_t)(DT_RANGE_4 | ((uint8_t)((uint8_t)(((((uint64_t)(__DT__)*1000U))/ TIM_CALC_DTS((__TIMCLK__), (__CKD__))) >> 4U) - (uint8_t) 32U) & DT_DELAY_4)) :\
0U)
/**
* @brief HELPER macro calculating the prescaler value to achieve the required counter clock frequency.
* @note ex: @ref __LL_TIM_CALC_PSC (80000000, 1000000);
* @param __TIMCLK__ timer input clock frequency (in Hz)
* @param __CNTCLK__ counter clock frequency (in Hz)
* @retval Prescaler value (between Min_Data=0 and Max_Data=65535)
*/
#define __LL_TIM_CALC_PSC(__TIMCLK__, __CNTCLK__) \
((__TIMCLK__) >= (__CNTCLK__)) ? (uint32_t)((__TIMCLK__)/(__CNTCLK__) - 1U) : 0U
/**
* @brief HELPER macro calculating the auto-reload value to achieve the required output signal frequency.
* @note ex: @ref __LL_TIM_CALC_ARR (1000000, @ref LL_TIM_GetPrescaler (), 10000);
* @param __TIMCLK__ timer input clock frequency (in Hz)
* @param __PSC__ prescaler
* @param __FREQ__ output signal frequency (in Hz)
* @retval Auto-reload value (between Min_Data=0 and Max_Data=65535)
*/
#define __LL_TIM_CALC_ARR(__TIMCLK__, __PSC__, __FREQ__) \
(((__TIMCLK__)/((__PSC__) + 1U)) >= (__FREQ__)) ? ((__TIMCLK__)/((__FREQ__) * ((__PSC__) + 1U)) - 1U) : 0U
/**
* @brief HELPER macro calculating the compare value required to achieve the required timer output compare active/inactive delay.
* @note ex: @ref __LL_TIM_CALC_DELAY (1000000, @ref LL_TIM_GetPrescaler (), 10);
* @param __TIMCLK__ timer input clock frequency (in Hz)
* @param __PSC__ prescaler
* @param __DELAY__ timer output compare active/inactive delay (in us)
* @retval Compare value (between Min_Data=0 and Max_Data=65535)
*/
#define __LL_TIM_CALC_DELAY(__TIMCLK__, __PSC__, __DELAY__) \
((uint32_t)(((uint64_t)(__TIMCLK__) * (uint64_t)(__DELAY__)) \
/ ((uint64_t)1000000U * (uint64_t)((__PSC__) + 1U))))
/**
* @brief HELPER macro calculating the auto-reload value to achieve the required pulse duration (when the timer operates in one pulse mode).
* @note ex: @ref __LL_TIM_CALC_PULSE (1000000, @ref LL_TIM_GetPrescaler (), 10, 20);
* @param __TIMCLK__ timer input clock frequency (in Hz)
* @param __PSC__ prescaler
* @param __DELAY__ timer output compare active/inactive delay (in us)
* @param __PULSE__ pulse duration (in us)
* @retval Auto-reload value (between Min_Data=0 and Max_Data=65535)
*/
#define __LL_TIM_CALC_PULSE(__TIMCLK__, __PSC__, __DELAY__, __PULSE__) \
((uint32_t)(__LL_TIM_CALC_DELAY((__TIMCLK__), (__PSC__), (__PULSE__)) \
+ __LL_TIM_CALC_DELAY((__TIMCLK__), (__PSC__), (__DELAY__))))
/**
* @brief HELPER macro retrieving the ratio of the input capture prescaler
* @note ex: @ref __LL_TIM_GET_ICPSC_RATIO (@ref LL_TIM_IC_GetPrescaler ());
* @param __ICPSC__ This parameter can be one of the following values:
* @arg @ref LL_TIM_ICPSC_DIV1
* @arg @ref LL_TIM_ICPSC_DIV2
* @arg @ref LL_TIM_ICPSC_DIV4
* @arg @ref LL_TIM_ICPSC_DIV8
* @retval Input capture prescaler ratio (1, 2, 4 or 8)
*/
#define __LL_TIM_GET_ICPSC_RATIO(__ICPSC__) \
((uint32_t)(0x01U << (((__ICPSC__) >> 16U) >> TIM_CCMR1_IC1PSC_Pos)))
/**
* @}
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup TIM_LL_Exported_Functions TIM Exported Functions
* @{
*/
/** @defgroup TIM_LL_EF_Time_Base Time Base configuration
* @{
*/
/**
* @brief Enable timer counter.
* @rmtoll CR1 CEN LL_TIM_EnableCounter
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableCounter(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->CR1, TIM_CR1_CEN);
}
/**
* @brief Disable timer counter.
* @rmtoll CR1 CEN LL_TIM_DisableCounter
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableCounter(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->CR1, TIM_CR1_CEN);
}
/**
* @brief Indicates whether the timer counter is enabled.
* @rmtoll CR1 CEN LL_TIM_IsEnabledCounter
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledCounter(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->CR1, TIM_CR1_CEN) == (TIM_CR1_CEN));
}
/**
* @brief Enable update event generation.
* @rmtoll CR1 UDIS LL_TIM_EnableUpdateEvent
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableUpdateEvent(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->CR1, TIM_CR1_UDIS);
}
/**
* @brief Disable update event generation.
* @rmtoll CR1 UDIS LL_TIM_DisableUpdateEvent
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableUpdateEvent(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->CR1, TIM_CR1_UDIS);
}
/**
* @brief Indicates whether update event generation is enabled.
* @rmtoll CR1 UDIS LL_TIM_IsEnabledUpdateEvent
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledUpdateEvent(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->CR1, TIM_CR1_UDIS) == (TIM_CR1_UDIS));
}
/**
* @brief Set update event source
* @note Update event source set to LL_TIM_UPDATESOURCE_REGULAR: any of the following events
* generate an update interrupt or DMA request if enabled:
* - Counter overflow/underflow
* - Setting the UG bit
* - Update generation through the slave mode controller
* @note Update event source set to LL_TIM_UPDATESOURCE_COUNTER: only counter
* overflow/underflow generates an update interrupt or DMA request if enabled.
* @rmtoll CR1 URS LL_TIM_SetUpdateSource
* @param TIMx Timer instance
* @param UpdateSource This parameter can be one of the following values:
* @arg @ref LL_TIM_UPDATESOURCE_REGULAR
* @arg @ref LL_TIM_UPDATESOURCE_COUNTER
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetUpdateSource(TIM_TypeDef *TIMx, uint32_t UpdateSource)
{
MODIFY_REG(TIMx->CR1, TIM_CR1_URS, UpdateSource);
}
/**
* @brief Get actual event update source
* @rmtoll CR1 URS LL_TIM_GetUpdateSource
* @param TIMx Timer instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_UPDATESOURCE_REGULAR
* @arg @ref LL_TIM_UPDATESOURCE_COUNTER
*/
__STATIC_INLINE uint32_t LL_TIM_GetUpdateSource(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_URS));
}
/**
* @brief Set one pulse mode (one shot v.s. repetitive).
* @rmtoll CR1 OPM LL_TIM_SetOnePulseMode
* @param TIMx Timer instance
* @param OnePulseMode This parameter can be one of the following values:
* @arg @ref LL_TIM_ONEPULSEMODE_SINGLE
* @arg @ref LL_TIM_ONEPULSEMODE_REPETITIVE
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetOnePulseMode(TIM_TypeDef *TIMx, uint32_t OnePulseMode)
{
MODIFY_REG(TIMx->CR1, TIM_CR1_OPM, OnePulseMode);
}
/**
* @brief Get actual one pulse mode.
* @rmtoll CR1 OPM LL_TIM_GetOnePulseMode
* @param TIMx Timer instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_ONEPULSEMODE_SINGLE
* @arg @ref LL_TIM_ONEPULSEMODE_REPETITIVE
*/
__STATIC_INLINE uint32_t LL_TIM_GetOnePulseMode(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_OPM));
}
/**
* @brief Set the timer counter counting mode.
* @note Macro @ref IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx) can be used to
* check whether or not the counter mode selection feature is supported
* by a timer instance.
* @rmtoll CR1 DIR LL_TIM_SetCounterMode\n
* CR1 CMS LL_TIM_SetCounterMode
* @param TIMx Timer instance
* @param CounterMode This parameter can be one of the following values:
* @arg @ref LL_TIM_COUNTERMODE_UP
* @arg @ref LL_TIM_COUNTERMODE_DOWN
* @arg @ref LL_TIM_COUNTERMODE_CENTER_UP
* @arg @ref LL_TIM_COUNTERMODE_CENTER_DOWN
* @arg @ref LL_TIM_COUNTERMODE_CENTER_UP_DOWN
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetCounterMode(TIM_TypeDef *TIMx, uint32_t CounterMode)
{
MODIFY_REG(TIMx->CR1, TIM_CR1_DIR | TIM_CR1_CMS, CounterMode);
}
/**
* @brief Get actual counter mode.
* @note Macro @ref IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx) can be used to
* check whether or not the counter mode selection feature is supported
* by a timer instance.
* @rmtoll CR1 DIR LL_TIM_GetCounterMode\n
* CR1 CMS LL_TIM_GetCounterMode
* @param TIMx Timer instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_COUNTERMODE_UP
* @arg @ref LL_TIM_COUNTERMODE_DOWN
* @arg @ref LL_TIM_COUNTERMODE_CENTER_UP
* @arg @ref LL_TIM_COUNTERMODE_CENTER_DOWN
* @arg @ref LL_TIM_COUNTERMODE_CENTER_UP_DOWN
*/
__STATIC_INLINE uint32_t LL_TIM_GetCounterMode(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_DIR | TIM_CR1_CMS));
}
/**
* @brief Enable auto-reload (ARR) preload.
* @rmtoll CR1 ARPE LL_TIM_EnableARRPreload
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableARRPreload(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->CR1, TIM_CR1_ARPE);
}
/**
* @brief Disable auto-reload (ARR) preload.
* @rmtoll CR1 ARPE LL_TIM_DisableARRPreload
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableARRPreload(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->CR1, TIM_CR1_ARPE);
}
/**
* @brief Indicates whether auto-reload (ARR) preload is enabled.
* @rmtoll CR1 ARPE LL_TIM_IsEnabledARRPreload
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledARRPreload(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->CR1, TIM_CR1_ARPE) == (TIM_CR1_ARPE));
}
/**
* @brief Set the division ratio between the timer clock and the sampling clock used by the dead-time generators (when supported) and the digital filters.
* @note Macro @ref IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx) can be used to check
* whether or not the clock division feature is supported by the timer
* instance.
* @rmtoll CR1 CKD LL_TIM_SetClockDivision
* @param TIMx Timer instance
* @param ClockDivision This parameter can be one of the following values:
* @arg @ref LL_TIM_CLOCKDIVISION_DIV1
* @arg @ref LL_TIM_CLOCKDIVISION_DIV2
* @arg @ref LL_TIM_CLOCKDIVISION_DIV4
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetClockDivision(TIM_TypeDef *TIMx, uint32_t ClockDivision)
{
MODIFY_REG(TIMx->CR1, TIM_CR1_CKD, ClockDivision);
}
/**
* @brief Get the actual division ratio between the timer clock and the sampling clock used by the dead-time generators (when supported) and the digital filters.
* @note Macro @ref IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx) can be used to check
* whether or not the clock division feature is supported by the timer
* instance.
* @rmtoll CR1 CKD LL_TIM_GetClockDivision
* @param TIMx Timer instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_CLOCKDIVISION_DIV1
* @arg @ref LL_TIM_CLOCKDIVISION_DIV2
* @arg @ref LL_TIM_CLOCKDIVISION_DIV4
*/
__STATIC_INLINE uint32_t LL_TIM_GetClockDivision(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_CKD));
}
/**
* @brief Set the counter value.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @rmtoll CNT CNT LL_TIM_SetCounter
* @param TIMx Timer instance
* @param Counter Counter value (between Min_Data=0 and Max_Data=0xFFFF or 0xFFFFFFFF)
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetCounter(TIM_TypeDef *TIMx, uint32_t Counter)
{
WRITE_REG(TIMx->CNT, Counter);
}
/**
* @brief Get the counter value.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @rmtoll CNT CNT LL_TIM_GetCounter
* @param TIMx Timer instance
* @retval Counter value (between Min_Data=0 and Max_Data=0xFFFF or 0xFFFFFFFF)
*/
__STATIC_INLINE uint32_t LL_TIM_GetCounter(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CNT));
}
/**
* @brief Get the current direction of the counter
* @rmtoll CR1 DIR LL_TIM_GetDirection
* @param TIMx Timer instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_COUNTERDIRECTION_UP
* @arg @ref LL_TIM_COUNTERDIRECTION_DOWN
*/
__STATIC_INLINE uint32_t LL_TIM_GetDirection(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_DIR));
}
/**
* @brief Set the prescaler value.
* @note The counter clock frequency CK_CNT is equal to fCK_PSC / (PSC[15:0] + 1).
* @note The prescaler can be changed on the fly as this control register is buffered. The new
* prescaler ratio is taken into account at the next update event.
* @note Helper macro @ref __LL_TIM_CALC_PSC can be used to calculate the Prescaler parameter
* @rmtoll PSC PSC LL_TIM_SetPrescaler
* @param TIMx Timer instance
* @param Prescaler between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetPrescaler(TIM_TypeDef *TIMx, uint32_t Prescaler)
{
WRITE_REG(TIMx->PSC, Prescaler);
}
/**
* @brief Get the prescaler value.
* @rmtoll PSC PSC LL_TIM_GetPrescaler
* @param TIMx Timer instance
* @retval Prescaler value between Min_Data=0 and Max_Data=65535
*/
__STATIC_INLINE uint32_t LL_TIM_GetPrescaler(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->PSC));
}
/**
* @brief Set the auto-reload value.
* @note The counter is blocked while the auto-reload value is null.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Helper macro @ref __LL_TIM_CALC_ARR can be used to calculate the AutoReload parameter
* @rmtoll ARR ARR LL_TIM_SetAutoReload
* @param TIMx Timer instance
* @param AutoReload between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetAutoReload(TIM_TypeDef *TIMx, uint32_t AutoReload)
{
WRITE_REG(TIMx->ARR, AutoReload);
}
/**
* @brief Get the auto-reload value.
* @rmtoll ARR ARR LL_TIM_GetAutoReload
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @param TIMx Timer instance
* @retval Auto-reload value
*/
__STATIC_INLINE uint32_t LL_TIM_GetAutoReload(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->ARR));
}
/**
* @brief Set the repetition counter value.
* @note For advanced timer instances RepetitionCounter can be up to 65535.
* @note Macro @ref IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a repetition counter.
* @rmtoll RCR REP LL_TIM_SetRepetitionCounter
* @param TIMx Timer instance
* @param RepetitionCounter between Min_Data=0 and Max_Data=255
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetRepetitionCounter(TIM_TypeDef *TIMx, uint32_t RepetitionCounter)
{
WRITE_REG(TIMx->RCR, RepetitionCounter);
}
/**
* @brief Get the repetition counter value.
* @note Macro @ref IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a repetition counter.
* @rmtoll RCR REP LL_TIM_GetRepetitionCounter
* @param TIMx Timer instance
* @retval Repetition counter value
*/
__STATIC_INLINE uint32_t LL_TIM_GetRepetitionCounter(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->RCR));
}
/**
* @brief Force a continuous copy of the update interrupt flag (UIF) into the timer counter register (bit 31).
* @note This allows both the counter value and a potential roll-over condition signalled by the UIFCPY flag to be read in an atomic way.
* @rmtoll CR1 UIFREMAP LL_TIM_EnableUIFRemap
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableUIFRemap(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->CR1, TIM_CR1_UIFREMAP);
}
/**
* @brief Disable update interrupt flag (UIF) remapping.
* @rmtoll CR1 UIFREMAP LL_TIM_DisableUIFRemap
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableUIFRemap(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->CR1, TIM_CR1_UIFREMAP);
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_Capture_Compare Capture Compare configuration
* @{
*/
/**
* @brief Enable the capture/compare control bits (CCxE, CCxNE and OCxM) preload.
* @note CCxE, CCxNE and OCxM bits are preloaded, after having been written,
* they are updated only when a commutation event (COM) occurs.
* @note Only on channels that have a complementary output.
* @note Macro @ref IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check
* whether or not a timer instance is able to generate a commutation event.
* @rmtoll CR2 CCPC LL_TIM_CC_EnablePreload
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_CC_EnablePreload(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->CR2, TIM_CR2_CCPC);
}
/**
* @brief Disable the capture/compare control bits (CCxE, CCxNE and OCxM) preload.
* @note Macro @ref IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check
* whether or not a timer instance is able to generate a commutation event.
* @rmtoll CR2 CCPC LL_TIM_CC_DisablePreload
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_CC_DisablePreload(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->CR2, TIM_CR2_CCPC);
}
/**
* @brief Set the updated source of the capture/compare control bits (CCxE, CCxNE and OCxM).
* @note Macro @ref IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check
* whether or not a timer instance is able to generate a commutation event.
* @rmtoll CR2 CCUS LL_TIM_CC_SetUpdate
* @param TIMx Timer instance
* @param CCUpdateSource This parameter can be one of the following values:
* @arg @ref LL_TIM_CCUPDATESOURCE_COMG_ONLY
* @arg @ref LL_TIM_CCUPDATESOURCE_COMG_AND_TRGI
* @retval None
*/
__STATIC_INLINE void LL_TIM_CC_SetUpdate(TIM_TypeDef *TIMx, uint32_t CCUpdateSource)
{
MODIFY_REG(TIMx->CR2, TIM_CR2_CCUS, CCUpdateSource);
}
/**
* @brief Set the trigger of the capture/compare DMA request.
* @rmtoll CR2 CCDS LL_TIM_CC_SetDMAReqTrigger
* @param TIMx Timer instance
* @param DMAReqTrigger This parameter can be one of the following values:
* @arg @ref LL_TIM_CCDMAREQUEST_CC
* @arg @ref LL_TIM_CCDMAREQUEST_UPDATE
* @retval None
*/
__STATIC_INLINE void LL_TIM_CC_SetDMAReqTrigger(TIM_TypeDef *TIMx, uint32_t DMAReqTrigger)
{
MODIFY_REG(TIMx->CR2, TIM_CR2_CCDS, DMAReqTrigger);
}
/**
* @brief Get actual trigger of the capture/compare DMA request.
* @rmtoll CR2 CCDS LL_TIM_CC_GetDMAReqTrigger
* @param TIMx Timer instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_CCDMAREQUEST_CC
* @arg @ref LL_TIM_CCDMAREQUEST_UPDATE
*/
__STATIC_INLINE uint32_t LL_TIM_CC_GetDMAReqTrigger(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_BIT(TIMx->CR2, TIM_CR2_CCDS));
}
/**
* @brief Set the lock level to freeze the
* configuration of several capture/compare parameters.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* the lock mechanism is supported by a timer instance.
* @rmtoll BDTR LOCK LL_TIM_CC_SetLockLevel
* @param TIMx Timer instance
* @param LockLevel This parameter can be one of the following values:
* @arg @ref LL_TIM_LOCKLEVEL_OFF
* @arg @ref LL_TIM_LOCKLEVEL_1
* @arg @ref LL_TIM_LOCKLEVEL_2
* @arg @ref LL_TIM_LOCKLEVEL_3
* @retval None
*/
__STATIC_INLINE void LL_TIM_CC_SetLockLevel(TIM_TypeDef *TIMx, uint32_t LockLevel)
{
MODIFY_REG(TIMx->BDTR, TIM_BDTR_LOCK, LockLevel);
}
/**
* @brief Enable capture/compare channels.
* @rmtoll CCER CC1E LL_TIM_CC_EnableChannel\n
* CCER CC1NE LL_TIM_CC_EnableChannel\n
* CCER CC2E LL_TIM_CC_EnableChannel\n
* CCER CC2NE LL_TIM_CC_EnableChannel\n
* CCER CC3E LL_TIM_CC_EnableChannel\n
* CCER CC3NE LL_TIM_CC_EnableChannel\n
* CCER CC4E LL_TIM_CC_EnableChannel\n
* CCER CC5E LL_TIM_CC_EnableChannel\n
* CCER CC6E LL_TIM_CC_EnableChannel
* @param TIMx Timer instance
* @param Channels This parameter can be a combination of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_CC_EnableChannel(TIM_TypeDef *TIMx, uint32_t Channels)
{
SET_BIT(TIMx->CCER, Channels);
}
/**
* @brief Disable capture/compare channels.
* @rmtoll CCER CC1E LL_TIM_CC_DisableChannel\n
* CCER CC1NE LL_TIM_CC_DisableChannel\n
* CCER CC2E LL_TIM_CC_DisableChannel\n
* CCER CC2NE LL_TIM_CC_DisableChannel\n
* CCER CC3E LL_TIM_CC_DisableChannel\n
* CCER CC3NE LL_TIM_CC_DisableChannel\n
* CCER CC4E LL_TIM_CC_DisableChannel\n
* CCER CC5E LL_TIM_CC_DisableChannel\n
* CCER CC6E LL_TIM_CC_DisableChannel
* @param TIMx Timer instance
* @param Channels This parameter can be a combination of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_CC_DisableChannel(TIM_TypeDef *TIMx, uint32_t Channels)
{
CLEAR_BIT(TIMx->CCER, Channels);
}
/**
* @brief Indicate whether channel(s) is(are) enabled.
* @rmtoll CCER CC1E LL_TIM_CC_IsEnabledChannel\n
* CCER CC1NE LL_TIM_CC_IsEnabledChannel\n
* CCER CC2E LL_TIM_CC_IsEnabledChannel\n
* CCER CC2NE LL_TIM_CC_IsEnabledChannel\n
* CCER CC3E LL_TIM_CC_IsEnabledChannel\n
* CCER CC3NE LL_TIM_CC_IsEnabledChannel\n
* CCER CC4E LL_TIM_CC_IsEnabledChannel\n
* CCER CC5E LL_TIM_CC_IsEnabledChannel\n
* CCER CC6E LL_TIM_CC_IsEnabledChannel
* @param TIMx Timer instance
* @param Channels This parameter can be a combination of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_CC_IsEnabledChannel(TIM_TypeDef *TIMx, uint32_t Channels)
{
return (READ_BIT(TIMx->CCER, Channels) == (Channels));
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_Output_Channel Output channel configuration
* @{
*/
/**
* @brief Configure an output channel.
* @rmtoll CCMR1 CC1S LL_TIM_OC_ConfigOutput\n
* CCMR1 CC2S LL_TIM_OC_ConfigOutput\n
* CCMR2 CC3S LL_TIM_OC_ConfigOutput\n
* CCMR2 CC4S LL_TIM_OC_ConfigOutput\n
* CCMR3 CC5S LL_TIM_OC_ConfigOutput\n
* CCMR3 CC6S LL_TIM_OC_ConfigOutput\n
* CCER CC1P LL_TIM_OC_ConfigOutput\n
* CCER CC2P LL_TIM_OC_ConfigOutput\n
* CCER CC3P LL_TIM_OC_ConfigOutput\n
* CCER CC4P LL_TIM_OC_ConfigOutput\n
* CCER CC5P LL_TIM_OC_ConfigOutput\n
* CCER CC6P LL_TIM_OC_ConfigOutput\n
* CR2 OIS1 LL_TIM_OC_ConfigOutput\n
* CR2 OIS2 LL_TIM_OC_ConfigOutput\n
* CR2 OIS3 LL_TIM_OC_ConfigOutput\n
* CR2 OIS4 LL_TIM_OC_ConfigOutput\n
* CR2 OIS5 LL_TIM_OC_ConfigOutput\n
* CR2 OIS6 LL_TIM_OC_ConfigOutput
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @param Configuration This parameter must be a combination of all the following values:
* @arg @ref LL_TIM_OCPOLARITY_HIGH or @ref LL_TIM_OCPOLARITY_LOW
* @arg @ref LL_TIM_OCIDLESTATE_LOW or @ref LL_TIM_OCIDLESTATE_HIGH
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_ConfigOutput(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Configuration)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
CLEAR_BIT(*pReg, (TIM_CCMR1_CC1S << SHIFT_TAB_OCxx[iChannel]));
MODIFY_REG(TIMx->CCER, (TIM_CCER_CC1P << SHIFT_TAB_CCxP[iChannel]),
(Configuration & TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel]);
MODIFY_REG(TIMx->CR2, (TIM_CR2_OIS1 << SHIFT_TAB_OISx[iChannel]),
(Configuration & TIM_CR2_OIS1) << SHIFT_TAB_OISx[iChannel]);
}
/**
* @brief Define the behavior of the output reference signal OCxREF from which
* OCx and OCxN (when relevant) are derived.
* @rmtoll CCMR1 OC1M LL_TIM_OC_SetMode\n
* CCMR1 OC2M LL_TIM_OC_SetMode\n
* CCMR2 OC3M LL_TIM_OC_SetMode\n
* CCMR2 OC4M LL_TIM_OC_SetMode\n
* CCMR3 OC5M LL_TIM_OC_SetMode\n
* CCMR3 OC6M LL_TIM_OC_SetMode
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @param Mode This parameter can be one of the following values:
* @arg @ref LL_TIM_OCMODE_FROZEN
* @arg @ref LL_TIM_OCMODE_ACTIVE
* @arg @ref LL_TIM_OCMODE_INACTIVE
* @arg @ref LL_TIM_OCMODE_TOGGLE
* @arg @ref LL_TIM_OCMODE_FORCED_INACTIVE
* @arg @ref LL_TIM_OCMODE_FORCED_ACTIVE
* @arg @ref LL_TIM_OCMODE_PWM1
* @arg @ref LL_TIM_OCMODE_PWM2
* @arg @ref LL_TIM_OCMODE_RETRIG_OPM1
* @arg @ref LL_TIM_OCMODE_RETRIG_OPM2
* @arg @ref LL_TIM_OCMODE_COMBINED_PWM1
* @arg @ref LL_TIM_OCMODE_COMBINED_PWM2
* @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM1
* @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM2
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetMode(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Mode)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
MODIFY_REG(*pReg, ((TIM_CCMR1_OC1M | TIM_CCMR1_CC1S) << SHIFT_TAB_OCxx[iChannel]), Mode << SHIFT_TAB_OCxx[iChannel]);
}
/**
* @brief Get the output compare mode of an output channel.
* @rmtoll CCMR1 OC1M LL_TIM_OC_GetMode\n
* CCMR1 OC2M LL_TIM_OC_GetMode\n
* CCMR2 OC3M LL_TIM_OC_GetMode\n
* CCMR2 OC4M LL_TIM_OC_GetMode\n
* CCMR3 OC5M LL_TIM_OC_GetMode\n
* CCMR3 OC6M LL_TIM_OC_GetMode
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_OCMODE_FROZEN
* @arg @ref LL_TIM_OCMODE_ACTIVE
* @arg @ref LL_TIM_OCMODE_INACTIVE
* @arg @ref LL_TIM_OCMODE_TOGGLE
* @arg @ref LL_TIM_OCMODE_FORCED_INACTIVE
* @arg @ref LL_TIM_OCMODE_FORCED_ACTIVE
* @arg @ref LL_TIM_OCMODE_PWM1
* @arg @ref LL_TIM_OCMODE_PWM2
* @arg @ref LL_TIM_OCMODE_RETRIG_OPM1
* @arg @ref LL_TIM_OCMODE_RETRIG_OPM2
* @arg @ref LL_TIM_OCMODE_COMBINED_PWM1
* @arg @ref LL_TIM_OCMODE_COMBINED_PWM2
* @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM1
* @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM2
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetMode(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
return (READ_BIT(*pReg, ((TIM_CCMR1_OC1M | TIM_CCMR1_CC1S) << SHIFT_TAB_OCxx[iChannel])) >> SHIFT_TAB_OCxx[iChannel]);
}
/**
* @brief Set the polarity of an output channel.
* @rmtoll CCER CC1P LL_TIM_OC_SetPolarity\n
* CCER CC1NP LL_TIM_OC_SetPolarity\n
* CCER CC2P LL_TIM_OC_SetPolarity\n
* CCER CC2NP LL_TIM_OC_SetPolarity\n
* CCER CC3P LL_TIM_OC_SetPolarity\n
* CCER CC3NP LL_TIM_OC_SetPolarity\n
* CCER CC4P LL_TIM_OC_SetPolarity\n
* CCER CC5P LL_TIM_OC_SetPolarity\n
* CCER CC6P LL_TIM_OC_SetPolarity
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @param Polarity This parameter can be one of the following values:
* @arg @ref LL_TIM_OCPOLARITY_HIGH
* @arg @ref LL_TIM_OCPOLARITY_LOW
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetPolarity(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Polarity)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
MODIFY_REG(TIMx->CCER, (TIM_CCER_CC1P << SHIFT_TAB_CCxP[iChannel]), Polarity << SHIFT_TAB_CCxP[iChannel]);
}
/**
* @brief Get the polarity of an output channel.
* @rmtoll CCER CC1P LL_TIM_OC_GetPolarity\n
* CCER CC1NP LL_TIM_OC_GetPolarity\n
* CCER CC2P LL_TIM_OC_GetPolarity\n
* CCER CC2NP LL_TIM_OC_GetPolarity\n
* CCER CC3P LL_TIM_OC_GetPolarity\n
* CCER CC3NP LL_TIM_OC_GetPolarity\n
* CCER CC4P LL_TIM_OC_GetPolarity\n
* CCER CC5P LL_TIM_OC_GetPolarity\n
* CCER CC6P LL_TIM_OC_GetPolarity
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_OCPOLARITY_HIGH
* @arg @ref LL_TIM_OCPOLARITY_LOW
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetPolarity(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
return (READ_BIT(TIMx->CCER, (TIM_CCER_CC1P << SHIFT_TAB_CCxP[iChannel])) >> SHIFT_TAB_CCxP[iChannel]);
}
/**
* @brief Set the IDLE state of an output channel
* @note This function is significant only for the timer instances
* supporting the break feature. Macro @ref IS_TIM_BREAK_INSTANCE(TIMx)
* can be used to check whether or not a timer instance provides
* a break input.
* @rmtoll CR2 OIS1 LL_TIM_OC_SetIdleState\n
* CR2 OIS2N LL_TIM_OC_SetIdleState\n
* CR2 OIS2 LL_TIM_OC_SetIdleState\n
* CR2 OIS2N LL_TIM_OC_SetIdleState\n
* CR2 OIS3 LL_TIM_OC_SetIdleState\n
* CR2 OIS3N LL_TIM_OC_SetIdleState\n
* CR2 OIS4 LL_TIM_OC_SetIdleState\n
* CR2 OIS5 LL_TIM_OC_SetIdleState\n
* CR2 OIS6 LL_TIM_OC_SetIdleState
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @param IdleState This parameter can be one of the following values:
* @arg @ref LL_TIM_OCIDLESTATE_LOW
* @arg @ref LL_TIM_OCIDLESTATE_HIGH
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetIdleState(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t IdleState)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
MODIFY_REG(TIMx->CR2, (TIM_CR2_OIS1 << SHIFT_TAB_OISx[iChannel]), IdleState << SHIFT_TAB_OISx[iChannel]);
}
/**
* @brief Get the IDLE state of an output channel
* @rmtoll CR2 OIS1 LL_TIM_OC_GetIdleState\n
* CR2 OIS2N LL_TIM_OC_GetIdleState\n
* CR2 OIS2 LL_TIM_OC_GetIdleState\n
* CR2 OIS2N LL_TIM_OC_GetIdleState\n
* CR2 OIS3 LL_TIM_OC_GetIdleState\n
* CR2 OIS3N LL_TIM_OC_GetIdleState\n
* CR2 OIS4 LL_TIM_OC_GetIdleState\n
* CR2 OIS5 LL_TIM_OC_GetIdleState\n
* CR2 OIS6 LL_TIM_OC_GetIdleState
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH1N
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH2N
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH3N
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_OCIDLESTATE_LOW
* @arg @ref LL_TIM_OCIDLESTATE_HIGH
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetIdleState(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
return (READ_BIT(TIMx->CR2, (TIM_CR2_OIS1 << SHIFT_TAB_OISx[iChannel])) >> SHIFT_TAB_OISx[iChannel]);
}
/**
* @brief Enable fast mode for the output channel.
* @note Acts only if the channel is configured in PWM1 or PWM2 mode.
* @rmtoll CCMR1 OC1FE LL_TIM_OC_EnableFast\n
* CCMR1 OC2FE LL_TIM_OC_EnableFast\n
* CCMR2 OC3FE LL_TIM_OC_EnableFast\n
* CCMR2 OC4FE LL_TIM_OC_EnableFast\n
* CCMR3 OC5FE LL_TIM_OC_EnableFast\n
* CCMR3 OC6FE LL_TIM_OC_EnableFast
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_EnableFast(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
SET_BIT(*pReg, (TIM_CCMR1_OC1FE << SHIFT_TAB_OCxx[iChannel]));
}
/**
* @brief Disable fast mode for the output channel.
* @rmtoll CCMR1 OC1FE LL_TIM_OC_DisableFast\n
* CCMR1 OC2FE LL_TIM_OC_DisableFast\n
* CCMR2 OC3FE LL_TIM_OC_DisableFast\n
* CCMR2 OC4FE LL_TIM_OC_DisableFast\n
* CCMR3 OC5FE LL_TIM_OC_DisableFast\n
* CCMR3 OC6FE LL_TIM_OC_DisableFast
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_DisableFast(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
CLEAR_BIT(*pReg, (TIM_CCMR1_OC1FE << SHIFT_TAB_OCxx[iChannel]));
}
/**
* @brief Indicates whether fast mode is enabled for the output channel.
* @rmtoll CCMR1 OC1FE LL_TIM_OC_IsEnabledFast\n
* CCMR1 OC2FE LL_TIM_OC_IsEnabledFast\n
* CCMR2 OC3FE LL_TIM_OC_IsEnabledFast\n
* CCMR2 OC4FE LL_TIM_OC_IsEnabledFast\n
* CCMR3 OC5FE LL_TIM_OC_IsEnabledFast\n
* CCMR3 OC6FE LL_TIM_OC_IsEnabledFast
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_OC_IsEnabledFast(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
register uint32_t bitfield = TIM_CCMR1_OC1FE << SHIFT_TAB_OCxx[iChannel];
return (READ_BIT(*pReg, bitfield) == bitfield);
}
/**
* @brief Enable compare register (TIMx_CCRx) preload for the output channel.
* @rmtoll CCMR1 OC1PE LL_TIM_OC_EnablePreload\n
* CCMR1 OC2PE LL_TIM_OC_EnablePreload\n
* CCMR2 OC3PE LL_TIM_OC_EnablePreload\n
* CCMR2 OC4PE LL_TIM_OC_EnablePreload\n
* CCMR3 OC5PE LL_TIM_OC_EnablePreload\n
* CCMR3 OC6PE LL_TIM_OC_EnablePreload
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel]));
}
/**
* @brief Disable compare register (TIMx_CCRx) preload for the output channel.
* @rmtoll CCMR1 OC1PE LL_TIM_OC_DisablePreload\n
* CCMR1 OC2PE LL_TIM_OC_DisablePreload\n
* CCMR2 OC3PE LL_TIM_OC_DisablePreload\n
* CCMR2 OC4PE LL_TIM_OC_DisablePreload\n
* CCMR3 OC5PE LL_TIM_OC_DisablePreload\n
* CCMR3 OC6PE LL_TIM_OC_DisablePreload
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel]));
}
/**
* @brief Indicates whether compare register (TIMx_CCRx) preload is enabled for the output channel.
* @rmtoll CCMR1 OC1PE LL_TIM_OC_IsEnabledPreload\n
* CCMR1 OC2PE LL_TIM_OC_IsEnabledPreload\n
* CCMR2 OC3PE LL_TIM_OC_IsEnabledPreload\n
* CCMR2 OC4PE LL_TIM_OC_IsEnabledPreload\n
* CCMR3 OC5PE LL_TIM_OC_IsEnabledPreload\n
* CCMR3 OC6PE LL_TIM_OC_IsEnabledPreload
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_OC_IsEnabledPreload(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
register uint32_t bitfield = TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel];
return (READ_BIT(*pReg, bitfield) == bitfield);
}
/**
* @brief Enable clearing the output channel on an external event.
* @note This function can only be used in Output compare and PWM modes. It does not work in Forced mode.
* @note Macro @ref IS_TIM_OCXREF_CLEAR_INSTANCE(TIMx) can be used to check whether
* or not a timer instance can clear the OCxREF signal on an external event.
* @rmtoll CCMR1 OC1CE LL_TIM_OC_EnableClear\n
* CCMR1 OC2CE LL_TIM_OC_EnableClear\n
* CCMR2 OC3CE LL_TIM_OC_EnableClear\n
* CCMR2 OC4CE LL_TIM_OC_EnableClear\n
* CCMR3 OC5CE LL_TIM_OC_EnableClear\n
* CCMR3 OC6CE LL_TIM_OC_EnableClear
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_EnableClear(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
SET_BIT(*pReg, (TIM_CCMR1_OC1CE << SHIFT_TAB_OCxx[iChannel]));
}
/**
* @brief Disable clearing the output channel on an external event.
* @note Macro @ref IS_TIM_OCXREF_CLEAR_INSTANCE(TIMx) can be used to check whether
* or not a timer instance can clear the OCxREF signal on an external event.
* @rmtoll CCMR1 OC1CE LL_TIM_OC_DisableClear\n
* CCMR1 OC2CE LL_TIM_OC_DisableClear\n
* CCMR2 OC3CE LL_TIM_OC_DisableClear\n
* CCMR2 OC4CE LL_TIM_OC_DisableClear\n
* CCMR3 OC5CE LL_TIM_OC_DisableClear\n
* CCMR3 OC6CE LL_TIM_OC_DisableClear
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_DisableClear(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
CLEAR_BIT(*pReg, (TIM_CCMR1_OC1CE << SHIFT_TAB_OCxx[iChannel]));
}
/**
* @brief Indicates clearing the output channel on an external event is enabled for the output channel.
* @note This function enables clearing the output channel on an external event.
* @note This function can only be used in Output compare and PWM modes. It does not work in Forced mode.
* @note Macro @ref IS_TIM_OCXREF_CLEAR_INSTANCE(TIMx) can be used to check whether
* or not a timer instance can clear the OCxREF signal on an external event.
* @rmtoll CCMR1 OC1CE LL_TIM_OC_IsEnabledClear\n
* CCMR1 OC2CE LL_TIM_OC_IsEnabledClear\n
* CCMR2 OC3CE LL_TIM_OC_IsEnabledClear\n
* CCMR2 OC4CE LL_TIM_OC_IsEnabledClear\n
* CCMR3 OC5CE LL_TIM_OC_IsEnabledClear\n
* CCMR3 OC6CE LL_TIM_OC_IsEnabledClear
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_OC_IsEnabledClear(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
register uint32_t bitfield = TIM_CCMR1_OC1CE << SHIFT_TAB_OCxx[iChannel];
return (READ_BIT(*pReg, bitfield) == bitfield);
}
/**
* @brief Set the dead-time delay (delay inserted between the rising edge of the OCxREF signal and the rising edge if the Ocx and OCxN signals).
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* dead-time insertion feature is supported by a timer instance.
* @note Helper macro @ref __LL_TIM_CALC_DEADTIME can be used to calculate the DeadTime parameter
* @rmtoll BDTR DTG LL_TIM_OC_SetDeadTime
* @param TIMx Timer instance
* @param DeadTime between Min_Data=0 and Max_Data=255
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetDeadTime(TIM_TypeDef *TIMx, uint32_t DeadTime)
{
MODIFY_REG(TIMx->BDTR, TIM_BDTR_DTG, DeadTime);
}
/**
* @brief Set compare value for output channel 1 (TIMx_CCR1).
* @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC1_INSTANCE(TIMx) can be used to check whether or not
* output channel 1 is supported by a timer instance.
* @rmtoll CCR1 CCR1 LL_TIM_OC_SetCompareCH1
* @param TIMx Timer instance
* @param CompareValue between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetCompareCH1(TIM_TypeDef *TIMx, uint32_t CompareValue)
{
WRITE_REG(TIMx->CCR1, CompareValue);
}
/**
* @brief Set compare value for output channel 2 (TIMx_CCR2).
* @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC2_INSTANCE(TIMx) can be used to check whether or not
* output channel 2 is supported by a timer instance.
* @rmtoll CCR2 CCR2 LL_TIM_OC_SetCompareCH2
* @param TIMx Timer instance
* @param CompareValue between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetCompareCH2(TIM_TypeDef *TIMx, uint32_t CompareValue)
{
WRITE_REG(TIMx->CCR2, CompareValue);
}
/**
* @brief Set compare value for output channel 3 (TIMx_CCR3).
* @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC3_INSTANCE(TIMx) can be used to check whether or not
* output channel is supported by a timer instance.
* @rmtoll CCR3 CCR3 LL_TIM_OC_SetCompareCH3
* @param TIMx Timer instance
* @param CompareValue between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetCompareCH3(TIM_TypeDef *TIMx, uint32_t CompareValue)
{
WRITE_REG(TIMx->CCR3, CompareValue);
}
/**
* @brief Set compare value for output channel 4 (TIMx_CCR4).
* @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC4_INSTANCE(TIMx) can be used to check whether or not
* output channel 4 is supported by a timer instance.
* @rmtoll CCR4 CCR4 LL_TIM_OC_SetCompareCH4
* @param TIMx Timer instance
* @param CompareValue between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetCompareCH4(TIM_TypeDef *TIMx, uint32_t CompareValue)
{
WRITE_REG(TIMx->CCR4, CompareValue);
}
/**
* @brief Set compare value for output channel 5 (TIMx_CCR5).
* @note Macro @ref IS_TIM_CC5_INSTANCE(TIMx) can be used to check whether or not
* output channel 5 is supported by a timer instance.
* @rmtoll CCR5 CCR5 LL_TIM_OC_SetCompareCH5
* @param TIMx Timer instance
* @param CompareValue between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetCompareCH5(TIM_TypeDef *TIMx, uint32_t CompareValue)
{
WRITE_REG(TIMx->CCR5, CompareValue);
}
/**
* @brief Set compare value for output channel 6 (TIMx_CCR6).
* @note Macro @ref IS_TIM_CC6_INSTANCE(TIMx) can be used to check whether or not
* output channel 6 is supported by a timer instance.
* @rmtoll CCR6 CCR6 LL_TIM_OC_SetCompareCH6
* @param TIMx Timer instance
* @param CompareValue between Min_Data=0 and Max_Data=65535
* @retval None
*/
__STATIC_INLINE void LL_TIM_OC_SetCompareCH6(TIM_TypeDef *TIMx, uint32_t CompareValue)
{
WRITE_REG(TIMx->CCR6, CompareValue);
}
/**
* @brief Get compare value (TIMx_CCR1) set for output channel 1.
* @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC1_INSTANCE(TIMx) can be used to check whether or not
* output channel 1 is supported by a timer instance.
* @rmtoll CCR1 CCR1 LL_TIM_OC_GetCompareCH1
* @param TIMx Timer instance
* @retval CompareValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH1(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR1));
}
/**
* @brief Get compare value (TIMx_CCR2) set for output channel 2.
* @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC2_INSTANCE(TIMx) can be used to check whether or not
* output channel 2 is supported by a timer instance.
* @rmtoll CCR2 CCR2 LL_TIM_OC_GetCompareCH2
* @param TIMx Timer instance
* @retval CompareValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH2(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR2));
}
/**
* @brief Get compare value (TIMx_CCR3) set for output channel 3.
* @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC3_INSTANCE(TIMx) can be used to check whether or not
* output channel 3 is supported by a timer instance.
* @rmtoll CCR3 CCR3 LL_TIM_OC_GetCompareCH3
* @param TIMx Timer instance
* @retval CompareValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH3(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR3));
}
/**
* @brief Get compare value (TIMx_CCR4) set for output channel 4.
* @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC4_INSTANCE(TIMx) can be used to check whether or not
* output channel 4 is supported by a timer instance.
* @rmtoll CCR4 CCR4 LL_TIM_OC_GetCompareCH4
* @param TIMx Timer instance
* @retval CompareValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH4(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR4));
}
/**
* @brief Get compare value (TIMx_CCR5) set for output channel 5.
* @note Macro @ref IS_TIM_CC5_INSTANCE(TIMx) can be used to check whether or not
* output channel 5 is supported by a timer instance.
* @rmtoll CCR5 CCR5 LL_TIM_OC_GetCompareCH5
* @param TIMx Timer instance
* @retval CompareValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH5(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR5));
}
/**
* @brief Get compare value (TIMx_CCR6) set for output channel 6.
* @note Macro @ref IS_TIM_CC6_INSTANCE(TIMx) can be used to check whether or not
* output channel 6 is supported by a timer instance.
* @rmtoll CCR6 CCR6 LL_TIM_OC_GetCompareCH6
* @param TIMx Timer instance
* @retval CompareValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH6(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR6));
}
/**
* @brief Select on which reference signal the OC5REF is combined to.
* @note Macro @ref IS_TIM_COMBINED3PHASEPWM_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports the combined 3-phase PWM mode.
* @rmtoll CCR5 GC5C3 LL_TIM_SetCH5CombinedChannels\n
* CCR5 GC5C2 LL_TIM_SetCH5CombinedChannels\n
* CCR5 GC5C1 LL_TIM_SetCH5CombinedChannels
* @param TIMx Timer instance
* @param GroupCH5 This parameter can be one of the following values:
* @arg @ref LL_TIM_GROUPCH5_NONE
* @arg @ref LL_TIM_GROUPCH5_OC1REFC
* @arg @ref LL_TIM_GROUPCH5_OC2REFC
* @arg @ref LL_TIM_GROUPCH5_OC3REFC
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetCH5CombinedChannels(TIM_TypeDef *TIMx, uint32_t GroupCH5)
{
MODIFY_REG(TIMx->CCR5, TIM_CCR5_CCR5, GroupCH5);
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_Input_Channel Input channel configuration
* @{
*/
/**
* @brief Configure input channel.
* @rmtoll CCMR1 CC1S LL_TIM_IC_Config\n
* CCMR1 IC1PSC LL_TIM_IC_Config\n
* CCMR1 IC1F LL_TIM_IC_Config\n
* CCMR1 CC2S LL_TIM_IC_Config\n
* CCMR1 IC2PSC LL_TIM_IC_Config\n
* CCMR1 IC2F LL_TIM_IC_Config\n
* CCMR2 CC3S LL_TIM_IC_Config\n
* CCMR2 IC3PSC LL_TIM_IC_Config\n
* CCMR2 IC3F LL_TIM_IC_Config\n
* CCMR2 CC4S LL_TIM_IC_Config\n
* CCMR2 IC4PSC LL_TIM_IC_Config\n
* CCMR2 IC4F LL_TIM_IC_Config\n
* CCER CC1P LL_TIM_IC_Config\n
* CCER CC1NP LL_TIM_IC_Config\n
* CCER CC2P LL_TIM_IC_Config\n
* CCER CC2NP LL_TIM_IC_Config\n
* CCER CC3P LL_TIM_IC_Config\n
* CCER CC3NP LL_TIM_IC_Config\n
* CCER CC4P LL_TIM_IC_Config\n
* CCER CC4NP LL_TIM_IC_Config
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @param Configuration This parameter must be a combination of all the following values:
* @arg @ref LL_TIM_ACTIVEINPUT_DIRECTTI or @ref LL_TIM_ACTIVEINPUT_INDIRECTTI or @ref LL_TIM_ACTIVEINPUT_TRC
* @arg @ref LL_TIM_ICPSC_DIV1 or ... or @ref LL_TIM_ICPSC_DIV8
* @arg @ref LL_TIM_IC_FILTER_FDIV1 or ... or @ref LL_TIM_IC_FILTER_FDIV32_N8
* @arg @ref LL_TIM_IC_POLARITY_RISING or @ref LL_TIM_IC_POLARITY_FALLING or @ref LL_TIM_IC_POLARITY_BOTHEDGE
* @retval None
*/
__STATIC_INLINE void LL_TIM_IC_Config(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Configuration)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
MODIFY_REG(*pReg, ((TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC | TIM_CCMR1_CC1S) << SHIFT_TAB_ICxx[iChannel]),
((Configuration >> 16U) & (TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC | TIM_CCMR1_CC1S)) << SHIFT_TAB_ICxx[iChannel]);
MODIFY_REG(TIMx->CCER, ((TIM_CCER_CC1NP | TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel]),
(Configuration & (TIM_CCER_CC1NP | TIM_CCER_CC1P)) << SHIFT_TAB_CCxP[iChannel]);
}
/**
* @brief Set the active input.
* @rmtoll CCMR1 CC1S LL_TIM_IC_SetActiveInput\n
* CCMR1 CC2S LL_TIM_IC_SetActiveInput\n
* CCMR2 CC3S LL_TIM_IC_SetActiveInput\n
* CCMR2 CC4S LL_TIM_IC_SetActiveInput
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @param ICActiveInput This parameter can be one of the following values:
* @arg @ref LL_TIM_ACTIVEINPUT_DIRECTTI
* @arg @ref LL_TIM_ACTIVEINPUT_INDIRECTTI
* @arg @ref LL_TIM_ACTIVEINPUT_TRC
* @retval None
*/
__STATIC_INLINE void LL_TIM_IC_SetActiveInput(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICActiveInput)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
MODIFY_REG(*pReg, ((TIM_CCMR1_CC1S) << SHIFT_TAB_ICxx[iChannel]), (ICActiveInput >> 16U) << SHIFT_TAB_ICxx[iChannel]);
}
/**
* @brief Get the current active input.
* @rmtoll CCMR1 CC1S LL_TIM_IC_GetActiveInput\n
* CCMR1 CC2S LL_TIM_IC_GetActiveInput\n
* CCMR2 CC3S LL_TIM_IC_GetActiveInput\n
* CCMR2 CC4S LL_TIM_IC_GetActiveInput
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_ACTIVEINPUT_DIRECTTI
* @arg @ref LL_TIM_ACTIVEINPUT_INDIRECTTI
* @arg @ref LL_TIM_ACTIVEINPUT_TRC
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetActiveInput(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
return ((READ_BIT(*pReg, ((TIM_CCMR1_CC1S) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U);
}
/**
* @brief Set the prescaler of input channel.
* @rmtoll CCMR1 IC1PSC LL_TIM_IC_SetPrescaler\n
* CCMR1 IC2PSC LL_TIM_IC_SetPrescaler\n
* CCMR2 IC3PSC LL_TIM_IC_SetPrescaler\n
* CCMR2 IC4PSC LL_TIM_IC_SetPrescaler
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @param ICPrescaler This parameter can be one of the following values:
* @arg @ref LL_TIM_ICPSC_DIV1
* @arg @ref LL_TIM_ICPSC_DIV2
* @arg @ref LL_TIM_ICPSC_DIV4
* @arg @ref LL_TIM_ICPSC_DIV8
* @retval None
*/
__STATIC_INLINE void LL_TIM_IC_SetPrescaler(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICPrescaler)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
MODIFY_REG(*pReg, ((TIM_CCMR1_IC1PSC) << SHIFT_TAB_ICxx[iChannel]), (ICPrescaler >> 16U) << SHIFT_TAB_ICxx[iChannel]);
}
/**
* @brief Get the current prescaler value acting on an input channel.
* @rmtoll CCMR1 IC1PSC LL_TIM_IC_GetPrescaler\n
* CCMR1 IC2PSC LL_TIM_IC_GetPrescaler\n
* CCMR2 IC3PSC LL_TIM_IC_GetPrescaler\n
* CCMR2 IC4PSC LL_TIM_IC_GetPrescaler
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_ICPSC_DIV1
* @arg @ref LL_TIM_ICPSC_DIV2
* @arg @ref LL_TIM_ICPSC_DIV4
* @arg @ref LL_TIM_ICPSC_DIV8
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetPrescaler(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
return ((READ_BIT(*pReg, ((TIM_CCMR1_IC1PSC) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U);
}
/**
* @brief Set the input filter duration.
* @rmtoll CCMR1 IC1F LL_TIM_IC_SetFilter\n
* CCMR1 IC2F LL_TIM_IC_SetFilter\n
* CCMR2 IC3F LL_TIM_IC_SetFilter\n
* CCMR2 IC4F LL_TIM_IC_SetFilter
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @param ICFilter This parameter can be one of the following values:
* @arg @ref LL_TIM_IC_FILTER_FDIV1
* @arg @ref LL_TIM_IC_FILTER_FDIV1_N2
* @arg @ref LL_TIM_IC_FILTER_FDIV1_N4
* @arg @ref LL_TIM_IC_FILTER_FDIV1_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV2_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV2_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV4_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV4_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV8_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV8_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV16_N5
* @arg @ref LL_TIM_IC_FILTER_FDIV16_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV16_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV32_N5
* @arg @ref LL_TIM_IC_FILTER_FDIV32_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV32_N8
* @retval None
*/
__STATIC_INLINE void LL_TIM_IC_SetFilter(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICFilter)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
MODIFY_REG(*pReg, ((TIM_CCMR1_IC1F) << SHIFT_TAB_ICxx[iChannel]), (ICFilter >> 16U) << SHIFT_TAB_ICxx[iChannel]);
}
/**
* @brief Get the input filter duration.
* @rmtoll CCMR1 IC1F LL_TIM_IC_GetFilter\n
* CCMR1 IC2F LL_TIM_IC_GetFilter\n
* CCMR2 IC3F LL_TIM_IC_GetFilter\n
* CCMR2 IC4F LL_TIM_IC_GetFilter
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_IC_FILTER_FDIV1
* @arg @ref LL_TIM_IC_FILTER_FDIV1_N2
* @arg @ref LL_TIM_IC_FILTER_FDIV1_N4
* @arg @ref LL_TIM_IC_FILTER_FDIV1_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV2_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV2_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV4_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV4_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV8_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV8_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV16_N5
* @arg @ref LL_TIM_IC_FILTER_FDIV16_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV16_N8
* @arg @ref LL_TIM_IC_FILTER_FDIV32_N5
* @arg @ref LL_TIM_IC_FILTER_FDIV32_N6
* @arg @ref LL_TIM_IC_FILTER_FDIV32_N8
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetFilter(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel]));
return ((READ_BIT(*pReg, ((TIM_CCMR1_IC1F) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U);
}
/**
* @brief Set the input channel polarity.
* @rmtoll CCER CC1P LL_TIM_IC_SetPolarity\n
* CCER CC1NP LL_TIM_IC_SetPolarity\n
* CCER CC2P LL_TIM_IC_SetPolarity\n
* CCER CC2NP LL_TIM_IC_SetPolarity\n
* CCER CC3P LL_TIM_IC_SetPolarity\n
* CCER CC3NP LL_TIM_IC_SetPolarity\n
* CCER CC4P LL_TIM_IC_SetPolarity\n
* CCER CC4NP LL_TIM_IC_SetPolarity
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @param ICPolarity This parameter can be one of the following values:
* @arg @ref LL_TIM_IC_POLARITY_RISING
* @arg @ref LL_TIM_IC_POLARITY_FALLING
* @arg @ref LL_TIM_IC_POLARITY_BOTHEDGE
* @retval None
*/
__STATIC_INLINE void LL_TIM_IC_SetPolarity(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICPolarity)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
MODIFY_REG(TIMx->CCER, ((TIM_CCER_CC1NP | TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel]),
ICPolarity << SHIFT_TAB_CCxP[iChannel]);
}
/**
* @brief Get the current input channel polarity.
* @rmtoll CCER CC1P LL_TIM_IC_GetPolarity\n
* CCER CC1NP LL_TIM_IC_GetPolarity\n
* CCER CC2P LL_TIM_IC_GetPolarity\n
* CCER CC2NP LL_TIM_IC_GetPolarity\n
* CCER CC3P LL_TIM_IC_GetPolarity\n
* CCER CC3NP LL_TIM_IC_GetPolarity\n
* CCER CC4P LL_TIM_IC_GetPolarity\n
* CCER CC4NP LL_TIM_IC_GetPolarity
* @param TIMx Timer instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @retval Returned value can be one of the following values:
* @arg @ref LL_TIM_IC_POLARITY_RISING
* @arg @ref LL_TIM_IC_POLARITY_FALLING
* @arg @ref LL_TIM_IC_POLARITY_BOTHEDGE
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetPolarity(TIM_TypeDef *TIMx, uint32_t Channel)
{
register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel);
return (READ_BIT(TIMx->CCER, ((TIM_CCER_CC1NP | TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel])) >>
SHIFT_TAB_CCxP[iChannel]);
}
/**
* @brief Connect the TIMx_CH1, CH2 and CH3 pins to the TI1 input (XOR combination).
* @note Macro @ref IS_TIM_XOR_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides an XOR input.
* @rmtoll CR2 TI1S LL_TIM_IC_EnableXORCombination
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_IC_EnableXORCombination(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->CR2, TIM_CR2_TI1S);
}
/**
* @brief Disconnect the TIMx_CH1, CH2 and CH3 pins from the TI1 input.
* @note Macro @ref IS_TIM_XOR_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides an XOR input.
* @rmtoll CR2 TI1S LL_TIM_IC_DisableXORCombination
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_IC_DisableXORCombination(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->CR2, TIM_CR2_TI1S);
}
/**
* @brief Indicates whether the TIMx_CH1, CH2 and CH3 pins are connectected to the TI1 input.
* @note Macro @ref IS_TIM_XOR_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides an XOR input.
* @rmtoll CR2 TI1S LL_TIM_IC_IsEnabledXORCombination
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IC_IsEnabledXORCombination(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->CR2, TIM_CR2_TI1S) == (TIM_CR2_TI1S));
}
/**
* @brief Get captured value for input channel 1.
* @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC1_INSTANCE(TIMx) can be used to check whether or not
* input channel 1 is supported by a timer instance.
* @rmtoll CCR1 CCR1 LL_TIM_IC_GetCaptureCH1
* @param TIMx Timer instance
* @retval CapturedValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH1(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR1));
}
/**
* @brief Get captured value for input channel 2.
* @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC2_INSTANCE(TIMx) can be used to check whether or not
* input channel 2 is supported by a timer instance.
* @rmtoll CCR2 CCR2 LL_TIM_IC_GetCaptureCH2
* @param TIMx Timer instance
* @retval CapturedValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH2(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR2));
}
/**
* @brief Get captured value for input channel 3.
* @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC3_INSTANCE(TIMx) can be used to check whether or not
* input channel 3 is supported by a timer instance.
* @rmtoll CCR3 CCR3 LL_TIM_IC_GetCaptureCH3
* @param TIMx Timer instance
* @retval CapturedValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH3(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR3));
}
/**
* @brief Get captured value for input channel 4.
* @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF.
* @note Macro @ref IS_TIM_32B_COUNTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports a 32 bits counter.
* @note Macro @ref IS_TIM_CC4_INSTANCE(TIMx) can be used to check whether or not
* input channel 4 is supported by a timer instance.
* @rmtoll CCR4 CCR4 LL_TIM_IC_GetCaptureCH4
* @param TIMx Timer instance
* @retval CapturedValue (between Min_Data=0 and Max_Data=65535)
*/
__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH4(TIM_TypeDef *TIMx)
{
return (uint32_t)(READ_REG(TIMx->CCR4));
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_Clock_Selection Counter clock selection
* @{
*/
/**
* @brief Enable external clock mode 2.
* @note When external clock mode 2 is enabled the counter is clocked by any active edge on the ETRF signal.
* @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports external clock mode2.
* @rmtoll SMCR ECE LL_TIM_EnableExternalClock
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableExternalClock(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->SMCR, TIM_SMCR_ECE);
}
/**
* @brief Disable external clock mode 2.
* @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports external clock mode2.
* @rmtoll SMCR ECE LL_TIM_DisableExternalClock
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableExternalClock(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->SMCR, TIM_SMCR_ECE);
}
/**
* @brief Indicate whether external clock mode 2 is enabled.
* @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports external clock mode2.
* @rmtoll SMCR ECE LL_TIM_IsEnabledExternalClock
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledExternalClock(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SMCR, TIM_SMCR_ECE) == (TIM_SMCR_ECE));
}
/**
* @brief Set the clock source of the counter clock.
* @note when selected clock source is external clock mode 1, the timer input
* the external clock is applied is selected by calling the @ref LL_TIM_SetTriggerInput()
* function. This timer input must be configured by calling
* the @ref LL_TIM_IC_Config() function.
* @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports external clock mode1.
* @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports external clock mode2.
* @rmtoll SMCR SMS LL_TIM_SetClockSource\n
* SMCR ECE LL_TIM_SetClockSource
* @param TIMx Timer instance
* @param ClockSource This parameter can be one of the following values:
* @arg @ref LL_TIM_CLOCKSOURCE_INTERNAL
* @arg @ref LL_TIM_CLOCKSOURCE_EXT_MODE1
* @arg @ref LL_TIM_CLOCKSOURCE_EXT_MODE2
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetClockSource(TIM_TypeDef *TIMx, uint32_t ClockSource)
{
MODIFY_REG(TIMx->SMCR, TIM_SMCR_SMS | TIM_SMCR_ECE, ClockSource);
}
/**
* @brief Set the encoder interface mode.
* @note Macro @ref IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx) can be used to check
* whether or not a timer instance supports the encoder mode.
* @rmtoll SMCR SMS LL_TIM_SetEncoderMode
* @param TIMx Timer instance
* @param EncoderMode This parameter can be one of the following values:
* @arg @ref LL_TIM_ENCODERMODE_X2_TI1
* @arg @ref LL_TIM_ENCODERMODE_X2_TI2
* @arg @ref LL_TIM_ENCODERMODE_X4_TI12
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetEncoderMode(TIM_TypeDef *TIMx, uint32_t EncoderMode)
{
MODIFY_REG(TIMx->SMCR, TIM_SMCR_SMS, EncoderMode);
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_Timer_Synchronization Timer synchronisation configuration
* @{
*/
/**
* @brief Set the trigger output (TRGO) used for timer synchronization .
* @note Macro @ref IS_TIM_MASTER_INSTANCE(TIMx) can be used to check
* whether or not a timer instance can operate as a master timer.
* @rmtoll CR2 MMS LL_TIM_SetTriggerOutput
* @param TIMx Timer instance
* @param TimerSynchronization This parameter can be one of the following values:
* @arg @ref LL_TIM_TRGO_RESET
* @arg @ref LL_TIM_TRGO_ENABLE
* @arg @ref LL_TIM_TRGO_UPDATE
* @arg @ref LL_TIM_TRGO_CC1IF
* @arg @ref LL_TIM_TRGO_OC1REF
* @arg @ref LL_TIM_TRGO_OC2REF
* @arg @ref LL_TIM_TRGO_OC3REF
* @arg @ref LL_TIM_TRGO_OC4REF
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetTriggerOutput(TIM_TypeDef *TIMx, uint32_t TimerSynchronization)
{
MODIFY_REG(TIMx->CR2, TIM_CR2_MMS, TimerSynchronization);
}
/**
* @brief Set the trigger output 2 (TRGO2) used for ADC synchronization .
* @note Macro @ref IS_TIM_TRGO2_INSTANCE(TIMx) can be used to check
* whether or not a timer instance can be used for ADC synchronization.
* @rmtoll CR2 MMS2 LL_TIM_SetTriggerOutput2
* @param TIMx Timer Instance
* @param ADCSynchronization This parameter can be one of the following values:
* @arg @ref LL_TIM_TRGO2_RESET
* @arg @ref LL_TIM_TRGO2_ENABLE
* @arg @ref LL_TIM_TRGO2_UPDATE
* @arg @ref LL_TIM_TRGO2_CC1F
* @arg @ref LL_TIM_TRGO2_OC1
* @arg @ref LL_TIM_TRGO2_OC2
* @arg @ref LL_TIM_TRGO2_OC3
* @arg @ref LL_TIM_TRGO2_OC4
* @arg @ref LL_TIM_TRGO2_OC5
* @arg @ref LL_TIM_TRGO2_OC6
* @arg @ref LL_TIM_TRGO2_OC4_RISINGFALLING
* @arg @ref LL_TIM_TRGO2_OC6_RISINGFALLING
* @arg @ref LL_TIM_TRGO2_OC4_RISING_OC6_RISING
* @arg @ref LL_TIM_TRGO2_OC4_RISING_OC6_FALLING
* @arg @ref LL_TIM_TRGO2_OC5_RISING_OC6_RISING
* @arg @ref LL_TIM_TRGO2_OC5_RISING_OC6_FALLING
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetTriggerOutput2(TIM_TypeDef *TIMx, uint32_t ADCSynchronization)
{
MODIFY_REG(TIMx->CR2, TIM_CR2_MMS2, ADCSynchronization);
}
/**
* @brief Set the synchronization mode of a slave timer.
* @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not
* a timer instance can operate as a slave timer.
* @rmtoll SMCR SMS LL_TIM_SetSlaveMode
* @param TIMx Timer instance
* @param SlaveMode This parameter can be one of the following values:
* @arg @ref LL_TIM_SLAVEMODE_DISABLED
* @arg @ref LL_TIM_SLAVEMODE_RESET
* @arg @ref LL_TIM_SLAVEMODE_GATED
* @arg @ref LL_TIM_SLAVEMODE_TRIGGER
* @arg @ref LL_TIM_SLAVEMODE_COMBINED_RESETTRIGGER
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetSlaveMode(TIM_TypeDef *TIMx, uint32_t SlaveMode)
{
MODIFY_REG(TIMx->SMCR, TIM_SMCR_SMS, SlaveMode);
}
/**
* @brief Set the selects the trigger input to be used to synchronize the counter.
* @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not
* a timer instance can operate as a slave timer.
* @rmtoll SMCR TS LL_TIM_SetTriggerInput
* @param TIMx Timer instance
* @param TriggerInput This parameter can be one of the following values:
* @arg @ref LL_TIM_TS_ITR0
* @arg @ref LL_TIM_TS_ITR1
* @arg @ref LL_TIM_TS_ITR2
* @arg @ref LL_TIM_TS_ITR3
* @arg @ref LL_TIM_TS_TI1F_ED
* @arg @ref LL_TIM_TS_TI1FP1
* @arg @ref LL_TIM_TS_TI2FP2
* @arg @ref LL_TIM_TS_ETRF
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetTriggerInput(TIM_TypeDef *TIMx, uint32_t TriggerInput)
{
MODIFY_REG(TIMx->SMCR, TIM_SMCR_TS, TriggerInput);
}
/**
* @brief Enable the Master/Slave mode.
* @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not
* a timer instance can operate as a slave timer.
* @rmtoll SMCR MSM LL_TIM_EnableMasterSlaveMode
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableMasterSlaveMode(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->SMCR, TIM_SMCR_MSM);
}
/**
* @brief Disable the Master/Slave mode.
* @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not
* a timer instance can operate as a slave timer.
* @rmtoll SMCR MSM LL_TIM_DisableMasterSlaveMode
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableMasterSlaveMode(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->SMCR, TIM_SMCR_MSM);
}
/**
* @brief Indicates whether the Master/Slave mode is enabled.
* @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not
* a timer instance can operate as a slave timer.
* @rmtoll SMCR MSM LL_TIM_IsEnabledMasterSlaveMode
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledMasterSlaveMode(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SMCR, TIM_SMCR_MSM) == (TIM_SMCR_MSM));
}
/**
* @brief Configure the external trigger (ETR) input.
* @note Macro @ref IS_TIM_ETR_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides an external trigger input.
* @rmtoll SMCR ETP LL_TIM_ConfigETR\n
* SMCR ETPS LL_TIM_ConfigETR\n
* SMCR ETF LL_TIM_ConfigETR
* @param TIMx Timer instance
* @param ETRPolarity This parameter can be one of the following values:
* @arg @ref LL_TIM_ETR_POLARITY_NONINVERTED
* @arg @ref LL_TIM_ETR_POLARITY_INVERTED
* @param ETRPrescaler This parameter can be one of the following values:
* @arg @ref LL_TIM_ETR_PRESCALER_DIV1
* @arg @ref LL_TIM_ETR_PRESCALER_DIV2
* @arg @ref LL_TIM_ETR_PRESCALER_DIV4
* @arg @ref LL_TIM_ETR_PRESCALER_DIV8
* @param ETRFilter This parameter can be one of the following values:
* @arg @ref LL_TIM_ETR_FILTER_FDIV1
* @arg @ref LL_TIM_ETR_FILTER_FDIV1_N2
* @arg @ref LL_TIM_ETR_FILTER_FDIV1_N4
* @arg @ref LL_TIM_ETR_FILTER_FDIV1_N8
* @arg @ref LL_TIM_ETR_FILTER_FDIV2_N6
* @arg @ref LL_TIM_ETR_FILTER_FDIV2_N8
* @arg @ref LL_TIM_ETR_FILTER_FDIV4_N6
* @arg @ref LL_TIM_ETR_FILTER_FDIV4_N8
* @arg @ref LL_TIM_ETR_FILTER_FDIV8_N6
* @arg @ref LL_TIM_ETR_FILTER_FDIV8_N8
* @arg @ref LL_TIM_ETR_FILTER_FDIV16_N5
* @arg @ref LL_TIM_ETR_FILTER_FDIV16_N6
* @arg @ref LL_TIM_ETR_FILTER_FDIV16_N8
* @arg @ref LL_TIM_ETR_FILTER_FDIV32_N5
* @arg @ref LL_TIM_ETR_FILTER_FDIV32_N6
* @arg @ref LL_TIM_ETR_FILTER_FDIV32_N8
* @retval None
*/
__STATIC_INLINE void LL_TIM_ConfigETR(TIM_TypeDef *TIMx, uint32_t ETRPolarity, uint32_t ETRPrescaler,
uint32_t ETRFilter)
{
MODIFY_REG(TIMx->SMCR, TIM_SMCR_ETP | TIM_SMCR_ETPS | TIM_SMCR_ETF, ETRPolarity | ETRPrescaler | ETRFilter);
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_Break_Function Break function configuration
* @{
*/
/**
* @brief Enable the break function.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR BKE LL_TIM_EnableBRK
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableBRK(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->BDTR, TIM_BDTR_BKE);
}
/**
* @brief Disable the break function.
* @rmtoll BDTR BKE LL_TIM_DisableBRK
* @param TIMx Timer instance
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableBRK(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->BDTR, TIM_BDTR_BKE);
}
/**
* @brief Configure the break input.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR BKP LL_TIM_ConfigBRK\n
* BDTR BKF LL_TIM_ConfigBRK
* @param TIMx Timer instance
* @param BreakPolarity This parameter can be one of the following values:
* @arg @ref LL_TIM_BREAK_POLARITY_LOW
* @arg @ref LL_TIM_BREAK_POLARITY_HIGH
* @param BreakFilter This parameter can be one of the following values:
* @arg @ref LL_TIM_BREAK_FILTER_FDIV1
* @arg @ref LL_TIM_BREAK_FILTER_FDIV1_N2
* @arg @ref LL_TIM_BREAK_FILTER_FDIV1_N4
* @arg @ref LL_TIM_BREAK_FILTER_FDIV1_N8
* @arg @ref LL_TIM_BREAK_FILTER_FDIV2_N6
* @arg @ref LL_TIM_BREAK_FILTER_FDIV2_N8
* @arg @ref LL_TIM_BREAK_FILTER_FDIV4_N6
* @arg @ref LL_TIM_BREAK_FILTER_FDIV4_N8
* @arg @ref LL_TIM_BREAK_FILTER_FDIV8_N6
* @arg @ref LL_TIM_BREAK_FILTER_FDIV8_N8
* @arg @ref LL_TIM_BREAK_FILTER_FDIV16_N5
* @arg @ref LL_TIM_BREAK_FILTER_FDIV16_N6
* @arg @ref LL_TIM_BREAK_FILTER_FDIV16_N8
* @arg @ref LL_TIM_BREAK_FILTER_FDIV32_N5
* @arg @ref LL_TIM_BREAK_FILTER_FDIV32_N6
* @arg @ref LL_TIM_BREAK_FILTER_FDIV32_N8
* @retval None
*/
__STATIC_INLINE void LL_TIM_ConfigBRK(TIM_TypeDef *TIMx, uint32_t BreakPolarity, uint32_t BreakFilter)
{
MODIFY_REG(TIMx->BDTR, TIM_BDTR_BKP | TIM_BDTR_BKF, BreakPolarity | BreakFilter);
}
/**
* @brief Enable the break 2 function.
* @note Macro @ref IS_TIM_BKIN2_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a second break input.
* @rmtoll BDTR BK2E LL_TIM_EnableBRK2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableBRK2(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->BDTR, TIM_BDTR_BK2E);
}
/**
* @brief Disable the break 2 function.
* @note Macro @ref IS_TIM_BKIN2_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a second break input.
* @rmtoll BDTR BK2E LL_TIM_DisableBRK2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableBRK2(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->BDTR, TIM_BDTR_BK2E);
}
/**
* @brief Configure the break 2 input.
* @note Macro @ref IS_TIM_BKIN2_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a second break input.
* @rmtoll BDTR BK2P LL_TIM_ConfigBRK2\n
* BDTR BK2F LL_TIM_ConfigBRK2
* @param TIMx Timer instance
* @param Break2Polarity This parameter can be one of the following values:
* @arg @ref LL_TIM_BREAK2_POLARITY_LOW
* @arg @ref LL_TIM_BREAK2_POLARITY_HIGH
* @param Break2Filter This parameter can be one of the following values:
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV1
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV1_N2
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV1_N4
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV1_N8
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV2_N6
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV2_N8
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV4_N6
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV4_N8
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV8_N6
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV8_N8
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV16_N5
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV16_N6
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV16_N8
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV32_N5
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV32_N6
* @arg @ref LL_TIM_BREAK2_FILTER_FDIV32_N8
* @retval None
*/
__STATIC_INLINE void LL_TIM_ConfigBRK2(TIM_TypeDef *TIMx, uint32_t Break2Polarity, uint32_t Break2Filter)
{
MODIFY_REG(TIMx->BDTR, TIM_BDTR_BK2P | TIM_BDTR_BK2F, Break2Polarity | Break2Filter);
}
/**
* @brief Select the outputs off state (enabled v.s. disabled) in Idle and Run modes.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR OSSI LL_TIM_SetOffStates\n
* BDTR OSSR LL_TIM_SetOffStates
* @param TIMx Timer instance
* @param OffStateIdle This parameter can be one of the following values:
* @arg @ref LL_TIM_OSSI_DISABLE
* @arg @ref LL_TIM_OSSI_ENABLE
* @param OffStateRun This parameter can be one of the following values:
* @arg @ref LL_TIM_OSSR_DISABLE
* @arg @ref LL_TIM_OSSR_ENABLE
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetOffStates(TIM_TypeDef *TIMx, uint32_t OffStateIdle, uint32_t OffStateRun)
{
MODIFY_REG(TIMx->BDTR, TIM_BDTR_OSSI | TIM_BDTR_OSSR, OffStateIdle | OffStateRun);
}
/**
* @brief Enable automatic output (MOE can be set by software or automatically when a break input is active).
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR AOE LL_TIM_EnableAutomaticOutput
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableAutomaticOutput(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->BDTR, TIM_BDTR_AOE);
}
/**
* @brief Disable automatic output (MOE can be set only by software).
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR AOE LL_TIM_DisableAutomaticOutput
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableAutomaticOutput(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->BDTR, TIM_BDTR_AOE);
}
/**
* @brief Indicate whether automatic output is enabled.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR AOE LL_TIM_IsEnabledAutomaticOutput
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledAutomaticOutput(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->BDTR, TIM_BDTR_AOE) == (TIM_BDTR_AOE));
}
/**
* @brief Enable the outputs (set the MOE bit in TIMx_BDTR register).
* @note The MOE bit in TIMx_BDTR register allows to enable /disable the outputs by
* software and is reset in case of break or break2 event
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR MOE LL_TIM_EnableAllOutputs
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableAllOutputs(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->BDTR, TIM_BDTR_MOE);
}
/**
* @brief Disable the outputs (reset the MOE bit in TIMx_BDTR register).
* @note The MOE bit in TIMx_BDTR register allows to enable /disable the outputs by
* software and is reset in case of break or break2 event.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR MOE LL_TIM_DisableAllOutputs
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableAllOutputs(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->BDTR, TIM_BDTR_MOE);
}
/**
* @brief Indicates whether outputs are enabled.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @rmtoll BDTR MOE LL_TIM_IsEnabledAllOutputs
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledAllOutputs(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->BDTR, TIM_BDTR_MOE) == (TIM_BDTR_MOE));
}
#if defined(TIM_BREAK_INPUT_SUPPORT)
/**
* @brief Enable the signals connected to the designated timer break input.
* @note Macro @ref IS_TIM_BREAKSOURCE_INSTANCE(TIMx) can be used to check whether
* or not a timer instance allows for break input selection.
* @rmtoll AF1 BKINE LL_TIM_EnableBreakInputSource\n
* AF1 BKDFBKE LL_TIM_EnableBreakInputSource\n
* AF2 BK2INE LL_TIM_EnableBreakInputSource\n
* AF2 BK2DFBKE LL_TIM_EnableBreakInputSource
* @param TIMx Timer instance
* @param BreakInput This parameter can be one of the following values:
* @arg @ref LL_TIM_BREAK_INPUT_BKIN
* @arg @ref LL_TIM_BREAK_INPUT_BKIN2
* @param Source This parameter can be one of the following values:
* @arg @ref LL_TIM_BKIN_SOURCE_BKIN
* @arg @ref LL_TIM_BKIN_SOURCE_DF1BK
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableBreakInputSource(TIM_TypeDef *TIMx, uint32_t BreakInput, uint32_t Source)
{
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->AF1) + BreakInput));
SET_BIT(*pReg , Source);
}
/**
* @brief Disable the signals connected to the designated timer break input.
* @note Macro @ref IS_TIM_BREAKSOURCE_INSTANCE(TIMx) can be used to check whether
* or not a timer instance allows for break input selection.
* @rmtoll AF1 BKINE LL_TIM_DisableBreakInputSource\n
* AF1 BKDFBKE LL_TIM_DisableBreakInputSource\n
* AF2 BK2INE LL_TIM_DisableBreakInputSource\n
* AF2 BK2DFBKE LL_TIM_DisableBreakInputSource
* @param TIMx Timer instance
* @param BreakInput This parameter can be one of the following values:
* @arg @ref LL_TIM_BREAK_INPUT_BKIN
* @arg @ref LL_TIM_BREAK_INPUT_BKIN2
* @param Source This parameter can be one of the following values:
* @arg @ref LL_TIM_BKIN_SOURCE_BKIN
* @arg @ref LL_TIM_BKIN_SOURCE_DF1BK
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableBreakInputSource(TIM_TypeDef *TIMx, uint32_t BreakInput, uint32_t Source)
{
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->AF1) + BreakInput));
CLEAR_BIT(*pReg, Source);
}
/**
* @brief Set the polarity of the break signal for the timer break input.
* @note Macro @ref IS_TIM_BREAKSOURCE_INSTANCE(TIMx) can be used to check whether
* or not a timer instance allows for break input selection.
* @rmtoll AF1 BKINE LL_TIM_SetBreakInputSourcePolarity\n
* AF1 BKDFBKE LL_TIM_SetBreakInputSourcePolarity\n
* AF2 BK2INE LL_TIM_SetBreakInputSourcePolarity\n
* AF2 BK2DFBKE LL_TIM_SetBreakInputSourcePolarity
* @param TIMx Timer instance
* @param BreakInput This parameter can be one of the following values:
* @arg @ref LL_TIM_BREAK_INPUT_BKIN
* @arg @ref LL_TIM_BREAK_INPUT_BKIN2
* @param Source This parameter can be one of the following values:
* @arg @ref LL_TIM_BKIN_SOURCE_BKIN
* @arg @ref LL_TIM_BKIN_SOURCE_DF1BK
* @param Polarity This parameter can be one of the following values:
* @arg @ref LL_TIM_BKIN_POLARITY_LOW
* @arg @ref LL_TIM_BKIN_POLARITY_HIGH
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetBreakInputSourcePolarity(TIM_TypeDef *TIMx, uint32_t BreakInput, uint32_t Source,
uint32_t Polarity)
{
register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->AF1) + BreakInput));
MODIFY_REG(*pReg, (TIMx_AF1_BKINP << (TIM_POSITION_BRK_SOURCE)) , (Polarity << (TIM_POSITION_BRK_SOURCE)));
}
#endif /* TIM_BREAK_INPUT_SUPPORT */
/**
* @}
*/
/** @defgroup TIM_LL_EF_DMA_Burst_Mode DMA burst mode configuration
* @{
*/
/**
* @brief Configures the timer DMA burst feature.
* @note Macro @ref IS_TIM_DMABURST_INSTANCE(TIMx) can be used to check whether or
* not a timer instance supports the DMA burst mode.
* @rmtoll DCR DBL LL_TIM_ConfigDMABurst\n
* DCR DBA LL_TIM_ConfigDMABurst
* @param TIMx Timer instance
* @param DMABurstBaseAddress This parameter can be one of the following values:
* @arg @ref LL_TIM_DMABURST_BASEADDR_CR1
* @arg @ref LL_TIM_DMABURST_BASEADDR_CR2
* @arg @ref LL_TIM_DMABURST_BASEADDR_SMCR
* @arg @ref LL_TIM_DMABURST_BASEADDR_DIER
* @arg @ref LL_TIM_DMABURST_BASEADDR_SR
* @arg @ref LL_TIM_DMABURST_BASEADDR_EGR
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCMR1
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCMR2
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCER
* @arg @ref LL_TIM_DMABURST_BASEADDR_CNT
* @arg @ref LL_TIM_DMABURST_BASEADDR_PSC
* @arg @ref LL_TIM_DMABURST_BASEADDR_ARR
* @arg @ref LL_TIM_DMABURST_BASEADDR_RCR
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCR1
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCR2
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCR3
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCR4
* @arg @ref LL_TIM_DMABURST_BASEADDR_BDTR
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCMR3
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCR5
* @arg @ref LL_TIM_DMABURST_BASEADDR_CCR6
* @arg @ref LL_TIM_DMABURST_BASEADDR_OR
* @arg @ref LL_TIM_DMABURST_BASEADDR_AF1
* @arg @ref LL_TIM_DMABURST_BASEADDR_AF2
* @param DMABurstLength This parameter can be one of the following values:
* @arg @ref LL_TIM_DMABURST_LENGTH_1TRANSFER
* @arg @ref LL_TIM_DMABURST_LENGTH_2TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_3TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_4TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_5TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_6TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_7TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_8TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_9TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_10TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_11TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_12TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_13TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_14TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_15TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_16TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_17TRANSFERS
* @arg @ref LL_TIM_DMABURST_LENGTH_18TRANSFERS
* @retval None
*/
__STATIC_INLINE void LL_TIM_ConfigDMABurst(TIM_TypeDef *TIMx, uint32_t DMABurstBaseAddress, uint32_t DMABurstLength)
{
MODIFY_REG(TIMx->DCR, TIM_DCR_DBL | TIM_DCR_DBA, DMABurstBaseAddress | DMABurstLength);
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_Timer_Inputs_Remapping Timer input remapping
* @{
*/
/**
* @brief Remap TIM inputs (input channel, internal/external triggers).
* @note Macro @ref IS_TIM_REMAP_INSTANCE(TIMx) can be used to check whether or not
* a some timer inputs can be remapped.
* @rmtoll TIM2_OR ITR1_RMP LL_TIM_SetRemap\n
* TIM5_OR TI4_RMP LL_TIM_SetRemap\n
* TIM11_OR TI1_RMP LL_TIM_SetRemap
* @param TIMx Timer instance
* @param Remap Remap param depends on the TIMx. Description available only
* in CHM version of the User Manual (not in .pdf).
* Otherwise see Reference Manual description of OR registers.
*
* Below description summarizes "Timer Instance" and "Remap" param combinations:
*
* TIM2: one of the following values
*
* ITR1_RMP can be one of the following values
* @arg @ref LL_TIM_TIM2_ITR1_RMP_TIM8_TRGO
* @arg @ref LL_TIM_TIM2_ITR1_RMP_ETH_PTP
* @arg @ref LL_TIM_TIM2_ITR1_RMP_OTG_FS_SOF
* @arg @ref LL_TIM_TIM2_ITR1_RMP_OTG_HS_SOF
*
* TIM5: one of the following values
*
* @arg @ref LL_TIM_TIM5_TI4_RMP_GPIO
* @arg @ref LL_TIM_TIM5_TI4_RMP_LSI
* @arg @ref LL_TIM_TIM5_TI4_RMP_LSE
* @arg @ref LL_TIM_TIM5_TI4_RMP_RTC
*
* TIM11: one of the following values
*
* @arg @ref LL_TIM_TIM11_TI1_RMP_GPIO
* @arg @ref LL_TIM_TIM11_TI1_RMP_SPDIFRX
* @arg @ref LL_TIM_TIM11_TI1_RMP_HSE
* @arg @ref LL_TIM_TIM11_TI1_RMP_MCO1
*
* @retval None
*/
__STATIC_INLINE void LL_TIM_SetRemap(TIM_TypeDef *TIMx, uint32_t Remap)
{
MODIFY_REG(TIMx->OR, (Remap >> TIMx_OR_RMP_SHIFT), (Remap & TIMx_OR_RMP_MASK));
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_FLAG_Management FLAG-Management
* @{
*/
/**
* @brief Clear the update interrupt flag (UIF).
* @rmtoll SR UIF LL_TIM_ClearFlag_UPDATE
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_UPDATE(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_UIF));
}
/**
* @brief Indicate whether update interrupt flag (UIF) is set (update interrupt is pending).
* @rmtoll SR UIF LL_TIM_IsActiveFlag_UPDATE
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_UPDATE(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_UIF) == (TIM_SR_UIF));
}
/**
* @brief Clear the Capture/Compare 1 interrupt flag (CC1F).
* @rmtoll SR CC1IF LL_TIM_ClearFlag_CC1
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC1(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC1IF));
}
/**
* @brief Indicate whether Capture/Compare 1 interrupt flag (CC1F) is set (Capture/Compare 1 interrupt is pending).
* @rmtoll SR CC1IF LL_TIM_IsActiveFlag_CC1
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC1(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC1IF) == (TIM_SR_CC1IF));
}
/**
* @brief Clear the Capture/Compare 2 interrupt flag (CC2F).
* @rmtoll SR CC2IF LL_TIM_ClearFlag_CC2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC2(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC2IF));
}
/**
* @brief Indicate whether Capture/Compare 2 interrupt flag (CC2F) is set (Capture/Compare 2 interrupt is pending).
* @rmtoll SR CC2IF LL_TIM_IsActiveFlag_CC2
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC2(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC2IF) == (TIM_SR_CC2IF));
}
/**
* @brief Clear the Capture/Compare 3 interrupt flag (CC3F).
* @rmtoll SR CC3IF LL_TIM_ClearFlag_CC3
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC3(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC3IF));
}
/**
* @brief Indicate whether Capture/Compare 3 interrupt flag (CC3F) is set (Capture/Compare 3 interrupt is pending).
* @rmtoll SR CC3IF LL_TIM_IsActiveFlag_CC3
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC3(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC3IF) == (TIM_SR_CC3IF));
}
/**
* @brief Clear the Capture/Compare 4 interrupt flag (CC4F).
* @rmtoll SR CC4IF LL_TIM_ClearFlag_CC4
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC4(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC4IF));
}
/**
* @brief Indicate whether Capture/Compare 4 interrupt flag (CC4F) is set (Capture/Compare 4 interrupt is pending).
* @rmtoll SR CC4IF LL_TIM_IsActiveFlag_CC4
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC4(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC4IF) == (TIM_SR_CC4IF));
}
/**
* @brief Clear the Capture/Compare 5 interrupt flag (CC5F).
* @rmtoll SR CC5IF LL_TIM_ClearFlag_CC5
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC5(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC5IF));
}
/**
* @brief Indicate whether Capture/Compare 5 interrupt flag (CC5F) is set (Capture/Compare 5 interrupt is pending).
* @rmtoll SR CC5IF LL_TIM_IsActiveFlag_CC5
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC5(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC5IF) == (TIM_SR_CC5IF));
}
/**
* @brief Clear the Capture/Compare 6 interrupt flag (CC6F).
* @rmtoll SR CC6IF LL_TIM_ClearFlag_CC6
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC6(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC6IF));
}
/**
* @brief Indicate whether Capture/Compare 6 interrupt flag (CC6F) is set (Capture/Compare 6 interrupt is pending).
* @rmtoll SR CC6IF LL_TIM_IsActiveFlag_CC6
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC6(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC6IF) == (TIM_SR_CC6IF));
}
/**
* @brief Clear the commutation interrupt flag (COMIF).
* @rmtoll SR COMIF LL_TIM_ClearFlag_COM
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_COM(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_COMIF));
}
/**
* @brief Indicate whether commutation interrupt flag (COMIF) is set (commutation interrupt is pending).
* @rmtoll SR COMIF LL_TIM_IsActiveFlag_COM
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_COM(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_COMIF) == (TIM_SR_COMIF));
}
/**
* @brief Clear the trigger interrupt flag (TIF).
* @rmtoll SR TIF LL_TIM_ClearFlag_TRIG
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_TRIG(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_TIF));
}
/**
* @brief Indicate whether trigger interrupt flag (TIF) is set (trigger interrupt is pending).
* @rmtoll SR TIF LL_TIM_IsActiveFlag_TRIG
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_TRIG(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_TIF) == (TIM_SR_TIF));
}
/**
* @brief Clear the break interrupt flag (BIF).
* @rmtoll SR BIF LL_TIM_ClearFlag_BRK
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_BRK(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_BIF));
}
/**
* @brief Indicate whether break interrupt flag (BIF) is set (break interrupt is pending).
* @rmtoll SR BIF LL_TIM_IsActiveFlag_BRK
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_BRK(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_BIF) == (TIM_SR_BIF));
}
/**
* @brief Clear the break 2 interrupt flag (B2IF).
* @rmtoll SR B2IF LL_TIM_ClearFlag_BRK2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_BRK2(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_B2IF));
}
/**
* @brief Indicate whether break 2 interrupt flag (B2IF) is set (break 2 interrupt is pending).
* @rmtoll SR B2IF LL_TIM_IsActiveFlag_BRK2
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_BRK2(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_B2IF) == (TIM_SR_B2IF));
}
/**
* @brief Clear the Capture/Compare 1 over-capture interrupt flag (CC1OF).
* @rmtoll SR CC1OF LL_TIM_ClearFlag_CC1OVR
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC1OVR(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC1OF));
}
/**
* @brief Indicate whether Capture/Compare 1 over-capture interrupt flag (CC1OF) is set (Capture/Compare 1 interrupt is pending).
* @rmtoll SR CC1OF LL_TIM_IsActiveFlag_CC1OVR
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC1OVR(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC1OF) == (TIM_SR_CC1OF));
}
/**
* @brief Clear the Capture/Compare 2 over-capture interrupt flag (CC2OF).
* @rmtoll SR CC2OF LL_TIM_ClearFlag_CC2OVR
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC2OVR(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC2OF));
}
/**
* @brief Indicate whether Capture/Compare 2 over-capture interrupt flag (CC2OF) is set (Capture/Compare 2 over-capture interrupt is pending).
* @rmtoll SR CC2OF LL_TIM_IsActiveFlag_CC2OVR
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC2OVR(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC2OF) == (TIM_SR_CC2OF));
}
/**
* @brief Clear the Capture/Compare 3 over-capture interrupt flag (CC3OF).
* @rmtoll SR CC3OF LL_TIM_ClearFlag_CC3OVR
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC3OVR(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC3OF));
}
/**
* @brief Indicate whether Capture/Compare 3 over-capture interrupt flag (CC3OF) is set (Capture/Compare 3 over-capture interrupt is pending).
* @rmtoll SR CC3OF LL_TIM_IsActiveFlag_CC3OVR
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC3OVR(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC3OF) == (TIM_SR_CC3OF));
}
/**
* @brief Clear the Capture/Compare 4 over-capture interrupt flag (CC4OF).
* @rmtoll SR CC4OF LL_TIM_ClearFlag_CC4OVR
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_CC4OVR(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_CC4OF));
}
/**
* @brief Indicate whether Capture/Compare 4 over-capture interrupt flag (CC4OF) is set (Capture/Compare 4 over-capture interrupt is pending).
* @rmtoll SR CC4OF LL_TIM_IsActiveFlag_CC4OVR
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC4OVR(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_CC4OF) == (TIM_SR_CC4OF));
}
/**
* @brief Clear the system break interrupt flag (SBIF).
* @rmtoll SR SBIF LL_TIM_ClearFlag_SYSBRK
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_ClearFlag_SYSBRK(TIM_TypeDef *TIMx)
{
WRITE_REG(TIMx->SR, ~(TIM_SR_SBIF));
}
/**
* @brief Indicate whether system break interrupt flag (SBIF) is set (system break interrupt is pending).
* @rmtoll SR SBIF LL_TIM_IsActiveFlag_SYSBRK
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_SYSBRK(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->SR, TIM_SR_SBIF) == (TIM_SR_SBIF));
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_IT_Management IT-Management
* @{
*/
/**
* @brief Enable update interrupt (UIE).
* @rmtoll DIER UIE LL_TIM_EnableIT_UPDATE
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_UPDATE(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_UIE);
}
/**
* @brief Disable update interrupt (UIE).
* @rmtoll DIER UIE LL_TIM_DisableIT_UPDATE
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_UPDATE(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_UIE);
}
/**
* @brief Indicates whether the update interrupt (UIE) is enabled.
* @rmtoll DIER UIE LL_TIM_IsEnabledIT_UPDATE
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_UPDATE(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_UIE) == (TIM_DIER_UIE));
}
/**
* @brief Enable capture/compare 1 interrupt (CC1IE).
* @rmtoll DIER CC1IE LL_TIM_EnableIT_CC1
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_CC1(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC1IE);
}
/**
* @brief Disable capture/compare 1 interrupt (CC1IE).
* @rmtoll DIER CC1IE LL_TIM_DisableIT_CC1
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_CC1(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC1IE);
}
/**
* @brief Indicates whether the capture/compare 1 interrupt (CC1IE) is enabled.
* @rmtoll DIER CC1IE LL_TIM_IsEnabledIT_CC1
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC1(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC1IE) == (TIM_DIER_CC1IE));
}
/**
* @brief Enable capture/compare 2 interrupt (CC2IE).
* @rmtoll DIER CC2IE LL_TIM_EnableIT_CC2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_CC2(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC2IE);
}
/**
* @brief Disable capture/compare 2 interrupt (CC2IE).
* @rmtoll DIER CC2IE LL_TIM_DisableIT_CC2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_CC2(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC2IE);
}
/**
* @brief Indicates whether the capture/compare 2 interrupt (CC2IE) is enabled.
* @rmtoll DIER CC2IE LL_TIM_IsEnabledIT_CC2
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC2(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC2IE) == (TIM_DIER_CC2IE));
}
/**
* @brief Enable capture/compare 3 interrupt (CC3IE).
* @rmtoll DIER CC3IE LL_TIM_EnableIT_CC3
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_CC3(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC3IE);
}
/**
* @brief Disable capture/compare 3 interrupt (CC3IE).
* @rmtoll DIER CC3IE LL_TIM_DisableIT_CC3
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_CC3(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC3IE);
}
/**
* @brief Indicates whether the capture/compare 3 interrupt (CC3IE) is enabled.
* @rmtoll DIER CC3IE LL_TIM_IsEnabledIT_CC3
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC3(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC3IE) == (TIM_DIER_CC3IE));
}
/**
* @brief Enable capture/compare 4 interrupt (CC4IE).
* @rmtoll DIER CC4IE LL_TIM_EnableIT_CC4
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_CC4(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC4IE);
}
/**
* @brief Disable capture/compare 4 interrupt (CC4IE).
* @rmtoll DIER CC4IE LL_TIM_DisableIT_CC4
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_CC4(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC4IE);
}
/**
* @brief Indicates whether the capture/compare 4 interrupt (CC4IE) is enabled.
* @rmtoll DIER CC4IE LL_TIM_IsEnabledIT_CC4
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC4(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC4IE) == (TIM_DIER_CC4IE));
}
/**
* @brief Enable commutation interrupt (COMIE).
* @rmtoll DIER COMIE LL_TIM_EnableIT_COM
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_COM(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_COMIE);
}
/**
* @brief Disable commutation interrupt (COMIE).
* @rmtoll DIER COMIE LL_TIM_DisableIT_COM
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_COM(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_COMIE);
}
/**
* @brief Indicates whether the commutation interrupt (COMIE) is enabled.
* @rmtoll DIER COMIE LL_TIM_IsEnabledIT_COM
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_COM(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_COMIE) == (TIM_DIER_COMIE));
}
/**
* @brief Enable trigger interrupt (TIE).
* @rmtoll DIER TIE LL_TIM_EnableIT_TRIG
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_TRIG(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_TIE);
}
/**
* @brief Disable trigger interrupt (TIE).
* @rmtoll DIER TIE LL_TIM_DisableIT_TRIG
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_TRIG(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_TIE);
}
/**
* @brief Indicates whether the trigger interrupt (TIE) is enabled.
* @rmtoll DIER TIE LL_TIM_IsEnabledIT_TRIG
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_TRIG(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_TIE) == (TIM_DIER_TIE));
}
/**
* @brief Enable break interrupt (BIE).
* @rmtoll DIER BIE LL_TIM_EnableIT_BRK
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableIT_BRK(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_BIE);
}
/**
* @brief Disable break interrupt (BIE).
* @rmtoll DIER BIE LL_TIM_DisableIT_BRK
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableIT_BRK(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_BIE);
}
/**
* @brief Indicates whether the break interrupt (BIE) is enabled.
* @rmtoll DIER BIE LL_TIM_IsEnabledIT_BRK
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_BRK(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_BIE) == (TIM_DIER_BIE));
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_DMA_Management DMA-Management
* @{
*/
/**
* @brief Enable update DMA request (UDE).
* @rmtoll DIER UDE LL_TIM_EnableDMAReq_UPDATE
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableDMAReq_UPDATE(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_UDE);
}
/**
* @brief Disable update DMA request (UDE).
* @rmtoll DIER UDE LL_TIM_DisableDMAReq_UPDATE
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableDMAReq_UPDATE(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_UDE);
}
/**
* @brief Indicates whether the update DMA request (UDE) is enabled.
* @rmtoll DIER UDE LL_TIM_IsEnabledDMAReq_UPDATE
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_UPDATE(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_UDE) == (TIM_DIER_UDE));
}
/**
* @brief Enable capture/compare 1 DMA request (CC1DE).
* @rmtoll DIER CC1DE LL_TIM_EnableDMAReq_CC1
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableDMAReq_CC1(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC1DE);
}
/**
* @brief Disable capture/compare 1 DMA request (CC1DE).
* @rmtoll DIER CC1DE LL_TIM_DisableDMAReq_CC1
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableDMAReq_CC1(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC1DE);
}
/**
* @brief Indicates whether the capture/compare 1 DMA request (CC1DE) is enabled.
* @rmtoll DIER CC1DE LL_TIM_IsEnabledDMAReq_CC1
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC1(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC1DE) == (TIM_DIER_CC1DE));
}
/**
* @brief Enable capture/compare 2 DMA request (CC2DE).
* @rmtoll DIER CC2DE LL_TIM_EnableDMAReq_CC2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableDMAReq_CC2(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC2DE);
}
/**
* @brief Disable capture/compare 2 DMA request (CC2DE).
* @rmtoll DIER CC2DE LL_TIM_DisableDMAReq_CC2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableDMAReq_CC2(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC2DE);
}
/**
* @brief Indicates whether the capture/compare 2 DMA request (CC2DE) is enabled.
* @rmtoll DIER CC2DE LL_TIM_IsEnabledDMAReq_CC2
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC2(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC2DE) == (TIM_DIER_CC2DE));
}
/**
* @brief Enable capture/compare 3 DMA request (CC3DE).
* @rmtoll DIER CC3DE LL_TIM_EnableDMAReq_CC3
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableDMAReq_CC3(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC3DE);
}
/**
* @brief Disable capture/compare 3 DMA request (CC3DE).
* @rmtoll DIER CC3DE LL_TIM_DisableDMAReq_CC3
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableDMAReq_CC3(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC3DE);
}
/**
* @brief Indicates whether the capture/compare 3 DMA request (CC3DE) is enabled.
* @rmtoll DIER CC3DE LL_TIM_IsEnabledDMAReq_CC3
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC3(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC3DE) == (TIM_DIER_CC3DE));
}
/**
* @brief Enable capture/compare 4 DMA request (CC4DE).
* @rmtoll DIER CC4DE LL_TIM_EnableDMAReq_CC4
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableDMAReq_CC4(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_CC4DE);
}
/**
* @brief Disable capture/compare 4 DMA request (CC4DE).
* @rmtoll DIER CC4DE LL_TIM_DisableDMAReq_CC4
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableDMAReq_CC4(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_CC4DE);
}
/**
* @brief Indicates whether the capture/compare 4 DMA request (CC4DE) is enabled.
* @rmtoll DIER CC4DE LL_TIM_IsEnabledDMAReq_CC4
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC4(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_CC4DE) == (TIM_DIER_CC4DE));
}
/**
* @brief Enable commutation DMA request (COMDE).
* @rmtoll DIER COMDE LL_TIM_EnableDMAReq_COM
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableDMAReq_COM(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_COMDE);
}
/**
* @brief Disable commutation DMA request (COMDE).
* @rmtoll DIER COMDE LL_TIM_DisableDMAReq_COM
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableDMAReq_COM(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_COMDE);
}
/**
* @brief Indicates whether the commutation DMA request (COMDE) is enabled.
* @rmtoll DIER COMDE LL_TIM_IsEnabledDMAReq_COM
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_COM(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_COMDE) == (TIM_DIER_COMDE));
}
/**
* @brief Enable trigger interrupt (TDE).
* @rmtoll DIER TDE LL_TIM_EnableDMAReq_TRIG
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_EnableDMAReq_TRIG(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->DIER, TIM_DIER_TDE);
}
/**
* @brief Disable trigger interrupt (TDE).
* @rmtoll DIER TDE LL_TIM_DisableDMAReq_TRIG
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_DisableDMAReq_TRIG(TIM_TypeDef *TIMx)
{
CLEAR_BIT(TIMx->DIER, TIM_DIER_TDE);
}
/**
* @brief Indicates whether the trigger interrupt (TDE) is enabled.
* @rmtoll DIER TDE LL_TIM_IsEnabledDMAReq_TRIG
* @param TIMx Timer instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_TRIG(TIM_TypeDef *TIMx)
{
return (READ_BIT(TIMx->DIER, TIM_DIER_TDE) == (TIM_DIER_TDE));
}
/**
* @}
*/
/** @defgroup TIM_LL_EF_EVENT_Management EVENT-Management
* @{
*/
/**
* @brief Generate an update event.
* @rmtoll EGR UG LL_TIM_GenerateEvent_UPDATE
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_UPDATE(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_UG);
}
/**
* @brief Generate Capture/Compare 1 event.
* @rmtoll EGR CC1G LL_TIM_GenerateEvent_CC1
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_CC1(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_CC1G);
}
/**
* @brief Generate Capture/Compare 2 event.
* @rmtoll EGR CC2G LL_TIM_GenerateEvent_CC2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_CC2(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_CC2G);
}
/**
* @brief Generate Capture/Compare 3 event.
* @rmtoll EGR CC3G LL_TIM_GenerateEvent_CC3
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_CC3(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_CC3G);
}
/**
* @brief Generate Capture/Compare 4 event.
* @rmtoll EGR CC4G LL_TIM_GenerateEvent_CC4
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_CC4(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_CC4G);
}
/**
* @brief Generate commutation event.
* @rmtoll EGR COMG LL_TIM_GenerateEvent_COM
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_COM(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_COMG);
}
/**
* @brief Generate trigger event.
* @rmtoll EGR TG LL_TIM_GenerateEvent_TRIG
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_TRIG(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_TG);
}
/**
* @brief Generate break event.
* @rmtoll EGR BG LL_TIM_GenerateEvent_BRK
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_BRK(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_BG);
}
/**
* @brief Generate break 2 event.
* @rmtoll EGR B2G LL_TIM_GenerateEvent_BRK2
* @param TIMx Timer instance
* @retval None
*/
__STATIC_INLINE void LL_TIM_GenerateEvent_BRK2(TIM_TypeDef *TIMx)
{
SET_BIT(TIMx->EGR, TIM_EGR_B2G);
}
/**
* @}
*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup TIM_LL_EF_Init Initialisation and deinitialisation functions
* @{
*/
ErrorStatus LL_TIM_DeInit(TIM_TypeDef *TIMx);
void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct);
ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, LL_TIM_InitTypeDef *TIM_InitStruct);
void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct);
ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct);
void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct);
void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct);
ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct);
void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct);
ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct);
void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct);
ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct);
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/**
* @}
*/
/**
* @}
*/
#endif /* TIM1 || TIM8 || TIM2 || TIM3 || TIM4 || TIM5 ||TIM9 || TIM10 || TIM11 || TIM12 || TIM13 || TIM14 || TIM6 || TIM7 */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F7xx_LL_TIM_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| c1728p9/mbed-os | targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_ll_tim.h | C | apache-2.0 | 204,721 |
<!DOCTYPE html >
<html>
<head>
<title>GroupByPartitioner - io.gearpump.streaming.dsl.partitioner.GroupByPartitioner</title>
<meta name="description" content="GroupByPartitioner - io.gearpump.streaming.dsl.partitioner.GroupByPartitioner" />
<meta name="keywords" content="GroupByPartitioner io.gearpump.streaming.dsl.partitioner.GroupByPartitioner" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../../../lib/template.js"></script>
<script type="text/javascript" src="../../../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../../../../index.html';
var hash = 'io.gearpump.streaming.dsl.partitioner.GroupByPartitioner';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="type">
<div id="definition">
<img src="../../../../../lib/class_big.png" />
<p id="owner"><a href="../../../../package.html" class="extype" name="io">io</a>.<a href="../../../package.html" class="extype" name="io.gearpump">gearpump</a>.<a href="../../package.html" class="extype" name="io.gearpump.streaming">streaming</a>.<a href="../package.html" class="extype" name="io.gearpump.streaming.dsl">dsl</a>.<a href="package.html" class="extype" name="io.gearpump.streaming.dsl.partitioner">partitioner</a></p>
<h1>GroupByPartitioner</h1><h3><span class="morelinks"><div>Related Doc:
<a href="package.html" class="extype" name="io.gearpump.streaming.dsl.partitioner">package partitioner</a>
</div></span></h3><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">GroupByPartitioner</span><span class="tparams">[<span name="T">T</span>, <span name="GROUP">GROUP</span>]</span><span class="result"> extends <a href="../../../partitioner/UnicastPartitioner.html" class="extype" name="io.gearpump.partitioner.UnicastPartitioner">UnicastPartitioner</a></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Partition messages by applying group by function first.
</p></div><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><a href="../../../partitioner/UnicastPartitioner.html" class="extype" name="io.gearpump.partitioner.UnicastPartitioner">UnicastPartitioner</a>, <a href="../../../partitioner/Partitioner.html" class="extype" name="io.gearpump.partitioner.Partitioner">Partitioner</a>, <span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="io.gearpump.streaming.dsl.partitioner.GroupByPartitioner"><span>GroupByPartitioner</span></li><li class="in" name="io.gearpump.partitioner.UnicastPartitioner"><span>UnicastPartitioner</span></li><li class="in" name="io.gearpump.partitioner.Partitioner"><span>Partitioner</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="io.gearpump.streaming.dsl.partitioner.GroupByPartitioner#<init>" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="<init>(groupBy:T=>GROUP):io.gearpump.streaming.dsl.partitioner.GroupByPartitioner[T,GROUP]"></a>
<a id="<init>:GroupByPartitioner[T,GROUP]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">GroupByPartitioner</span><span class="params">(<span name="groupBy">groupBy: (<span class="extype" name="io.gearpump.streaming.dsl.partitioner.GroupByPartitioner.T">T</span>) ⇒ <span class="extype" name="io.gearpump.streaming.dsl.partitioner.GroupByPartitioner.GROUP">GROUP</span> = <span class="symbol">null</span></span>)</span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@<init>(groupBy:T=>GROUP):io.gearpump.streaming.dsl.partitioner.GroupByPartitioner[T,GROUP]" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<p class="shortcomment cmt"></p><div class="fullcomment"><div class="comment cmt"></div><dl class="paramcmts block"><dt class="param">groupBy</dt><dd class="cmt"><p>
First apply message with groupBy function, then pick the hashCode of the output to do the partitioning.
You must define hashCode() for output type of groupBy function.</p><p>For example:
case class People(name: String, gender: String)</p><p>object Test{</p><p> val groupBy: (People => String) = people => people.gender
val partitioner = GroupByPartitioner(groupBy)
}
</p></dd></dl></div>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@!=(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@##():Int" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@==(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@asInstanceOf[T0]:T0" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@clone():Object" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@equals(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@finalize():Unit" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@getClass():Class[_]" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="io.gearpump.streaming.dsl.partitioner.GroupByPartitioner#getPartition" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getPartition(msg:io.gearpump.Message,partitionNum:Int,currentPartitionId:Int):Int"></a>
<a id="getPartition(Message,Int,Int):Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getPartition</span><span class="params">(<span name="msg">msg: <a href="../../../Message.html" class="extype" name="io.gearpump.Message">Message</a></span>, <span name="partitionNum">partitionNum: <span class="extype" name="scala.Int">Int</span></span>, <span name="currentPartitionId">currentPartitionId: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@getPartition(msg:io.gearpump.Message,partitionNum:Int,currentPartitionId:Int):Int" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<p class="shortcomment cmt"></p><div class="fullcomment"><div class="comment cmt"></div><dl class="paramcmts block"><dt class="param">msg</dt><dd class="cmt"></dd><dt class="param">partitionNum</dt><dd class="cmt"></dd><dt>returns</dt><dd class="cmt"><p>
</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="io.gearpump.streaming.dsl.partitioner.GroupByPartitioner">GroupByPartitioner</a> → <a href="../../../partitioner/UnicastPartitioner.html" class="extype" name="io.gearpump.partitioner.UnicastPartitioner">UnicastPartitioner</a></dd></dl></div>
</li><li name="io.gearpump.partitioner.UnicastPartitioner#getPartition" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getPartition(msg:io.gearpump.Message,partitionNum:Int):Int"></a>
<a id="getPartition(Message,Int):Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getPartition</span><span class="params">(<span name="msg">msg: <a href="../../../Message.html" class="extype" name="io.gearpump.Message">Message</a></span>, <span name="partitionNum">partitionNum: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@getPartition(msg:io.gearpump.Message,partitionNum:Int):Int" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../partitioner/UnicastPartitioner.html" class="extype" name="io.gearpump.partitioner.UnicastPartitioner">UnicastPartitioner</a></dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@hashCode():Int" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@isInstanceOf[T0]:Boolean" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@notify():Unit" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@notifyAll():Unit" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@synchronized[T0](x$1:=>T0):T0" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@toString():String" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@wait():Unit" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../../../index.html#io.gearpump.streaming.dsl.partitioner.GroupByPartitioner@wait(x$1:Long):Unit" title="Permalink" target="_top">
<img src="../../../../../lib/permalink.png" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="io.gearpump.partitioner.UnicastPartitioner">
<h3>Inherited from <a href="../../../partitioner/UnicastPartitioner.html" class="extype" name="io.gearpump.partitioner.UnicastPartitioner">UnicastPartitioner</a></h3>
</div><div class="parent" name="io.gearpump.partitioner.Partitioner">
<h3>Inherited from <a href="../../../partitioner/Partitioner.html" class="extype" name="io.gearpump.partitioner.Partitioner">Partitioner</a></h3>
</div><div class="parent" name="scala.Serializable">
<h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3>
</div><div class="parent" name="java.io.Serializable">
<h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html> | stanleyxu2005/gearpump.github.io | releases/0.7.6/api/scala/io/gearpump/streaming/dsl/partitioner/GroupByPartitioner.html | HTML | apache-2.0 | 32,724 |
/*
* 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.eagle.storage.jdbc.entity.impl;
import org.apache.eagle.storage.jdbc.entity.JdbcEntitySerDeserHelper;
import org.apache.eagle.storage.jdbc.schema.JdbcEntityDefinition;
import org.apache.eagle.storage.operation.CompiledQuery;
import org.apache.torque.TorqueException;
import org.apache.torque.criteria.CriteriaInterface;
import org.apache.torque.om.mapper.RecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
/**
* @since 3/27/15
*/
public class AggreagteRecordMapper implements RecordMapper<Map> {
private final static Logger LOG = LoggerFactory.getLogger(AggreagteRecordMapper.class);
private final JdbcEntityDefinition jdbcEntityDefinition;
public AggreagteRecordMapper(CompiledQuery query, JdbcEntityDefinition jdbcEntityDefinition) {
this.jdbcEntityDefinition = jdbcEntityDefinition;
}
@Override
public Map processRow(ResultSet resultSet, int rowOffset, CriteriaInterface<?> criteria) throws TorqueException {
try {
return JdbcEntitySerDeserHelper.readInternal(resultSet, this.jdbcEntityDefinition);
} catch (SQLException e) {
LOG.error("Failed to read result set",e);
throw new TorqueException(e);
} catch (IOException e) {
LOG.error("Failed to read result set",e);
throw new TorqueException(e);
}
}
} | yonzhang/incubator-eagle | eagle-core/eagle-query/eagle-storage-jdbc/src/main/java/org/apache/eagle/storage/jdbc/entity/impl/AggreagteRecordMapper.java | Java | apache-2.0 | 2,286 |
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.andes.server.store;
public interface MessageStoreRecoveryHandler
{
StoredMessageRecoveryHandler begin();
public static interface StoredMessageRecoveryHandler
{
void message(StoredMessage message);
void completeMessageRecovery();
}
}
| sdkottegoda/andes | modules/andes-core/broker/src/main/java/org/wso2/andes/server/store/MessageStoreRecoveryHandler.java | Java | apache-2.0 | 964 |
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"testing"
"time"
"github.com/docker/docker/api/types"
eventtypes "github.com/docker/docker/api/types/events"
"github.com/docker/docker/client"
eventstestutils "github.com/docker/docker/daemon/events/testutils"
"github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/icmd"
)
func (s *DockerSuite) TestEventsTimestampFormats(c *testing.T) {
name := "events-time-format-test"
// Start stopwatch, generate an event
start := daemonTime(c)
time.Sleep(1100 * time.Millisecond) // so that first event occur in different second from since (just for the case)
dockerCmd(c, "run", "--rm", "--name", name, "busybox", "true")
time.Sleep(1100 * time.Millisecond) // so that until > since
end := daemonTime(c)
// List of available time formats to --since
unixTs := func(t time.Time) string { return fmt.Sprintf("%v", t.Unix()) }
rfc3339 := func(t time.Time) string { return t.Format(time.RFC3339) }
duration := func(t time.Time) string { return time.Since(t).String() }
// --since=$start must contain only the 'untag' event
for _, f := range []func(time.Time) string{unixTs, rfc3339, duration} {
since, until := f(start), f(end)
out, _ := dockerCmd(c, "events", "--since="+since, "--until="+until)
events := strings.Split(out, "\n")
events = events[:len(events)-1]
nEvents := len(events)
assert.Assert(c, nEvents >= 5)
containerEvents := eventActionsByIDAndType(c, events, name, "container")
assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out)
}
}
func (s *DockerSuite) TestEventsUntag(c *testing.T) {
image := "busybox"
dockerCmd(c, "tag", image, "utest:tag1")
dockerCmd(c, "tag", image, "utest:tag2")
dockerCmd(c, "rmi", "utest:tag1")
dockerCmd(c, "rmi", "utest:tag2")
result := icmd.RunCmd(icmd.Cmd{
Command: []string{dockerBinary, "events", "--since=1"},
Timeout: time.Millisecond * 2500,
})
result.Assert(c, icmd.Expected{Timeout: true})
events := strings.Split(result.Stdout(), "\n")
nEvents := len(events)
// The last element after the split above will be an empty string, so we
// get the two elements before the last, which are the untags we're
// looking for.
for _, v := range events[nEvents-3 : nEvents-1] {
assert.Check(c, strings.Contains(v, "untag"), "event should be untag")
}
}
func (s *DockerSuite) TestEventsContainerEvents(c *testing.T) {
dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
out, _ := dockerCmd(c, "events", "--until", daemonUnixTime(c))
events := strings.Split(out, "\n")
events = events[:len(events)-1]
containerEvents := eventActionsByIDAndType(c, events, "container-events-test", "container")
if len(containerEvents) > 5 {
containerEvents = containerEvents[:5]
}
assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out)
}
func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *testing.T) {
since := daemonUnixTime(c)
dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
out, _ := dockerCmd(c, "events", "--filter", "container=container-events-test", "--since", since, "--until", daemonUnixTime(c))
events := strings.Split(out, "\n")
nEvents := len(events)
assert.Assert(c, nEvents >= 3)
matchedEvents := 0
for _, event := range events {
matches := eventstestutils.ScanMap(event)
if matches["eventType"] == "container" && matches["action"] == "create" {
matchedEvents++
assert.Check(c, strings.Contains(out, "(image=busybox, name=container-events-test)"), "Event attributes not sorted")
} else if matches["eventType"] == "container" && matches["action"] == "start" {
matchedEvents++
assert.Check(c, strings.Contains(out, "(image=busybox, name=container-events-test)"), "Event attributes not sorted")
}
}
assert.Equal(c, matchedEvents, 2, "missing events for container container-events-test:\n%s", out)
}
func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing.T) {
dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true")
timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
out, _ := dockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c))
events := strings.Split(out, "\n")
events = events[:len(events)-1]
nEvents := len(events)
assert.Assert(c, nEvents >= 5)
containerEvents := eventActionsByIDAndType(c, events, "since-epoch-test", "container")
assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out)
}
func (s *DockerSuite) TestEventsImageTag(c *testing.T) {
time.Sleep(1 * time.Second) // because API has seconds granularity
since := daemonUnixTime(c)
image := "testimageevents:tag"
dockerCmd(c, "tag", "busybox", image)
out, _ := dockerCmd(c, "events",
"--since", since, "--until", daemonUnixTime(c))
events := strings.Split(strings.TrimSpace(out), "\n")
assert.Equal(c, len(events), 1, "was expecting 1 event. out=%s", out)
event := strings.TrimSpace(events[0])
matches := eventstestutils.ScanMap(event)
assert.Assert(c, matchEventID(matches, image), "matches: %v\nout:\n%s", matches, out)
assert.Equal(c, matches["action"], "tag")
}
func (s *DockerSuite) TestEventsImagePull(c *testing.T) {
// TODO Windows: Enable this test once pull and reliable image names are available
testRequires(c, DaemonIsLinux)
since := daemonUnixTime(c)
testRequires(c, Network)
dockerCmd(c, "pull", "hello-world")
out, _ := dockerCmd(c, "events",
"--since", since, "--until", daemonUnixTime(c))
events := strings.Split(strings.TrimSpace(out), "\n")
event := strings.TrimSpace(events[len(events)-1])
matches := eventstestutils.ScanMap(event)
assert.Equal(c, matches["id"], "hello-world:latest")
assert.Equal(c, matches["action"], "pull")
}
func (s *DockerSuite) TestEventsImageImport(c *testing.T) {
// TODO Windows CI. This should be portable once export/import are
// more reliable (@swernli)
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
cleanedContainerID := strings.TrimSpace(out)
since := daemonUnixTime(c)
out, err := RunCommandPipelineWithOutput(
exec.Command(dockerBinary, "export", cleanedContainerID),
exec.Command(dockerBinary, "import", "-"),
)
assert.NilError(c, err, "import failed with output: %q", out)
imageRef := strings.TrimSpace(out)
out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=import")
events := strings.Split(strings.TrimSpace(out), "\n")
assert.Equal(c, len(events), 1)
matches := eventstestutils.ScanMap(events[0])
assert.Equal(c, matches["id"], imageRef, "matches: %v\nout:\n%s\n", matches, out)
assert.Equal(c, matches["action"], "import", "matches: %v\nout:\n%s\n", matches, out)
}
func (s *DockerSuite) TestEventsImageLoad(c *testing.T) {
testRequires(c, DaemonIsLinux)
myImageName := "footest:v1"
dockerCmd(c, "tag", "busybox", myImageName)
since := daemonUnixTime(c)
out, _ := dockerCmd(c, "images", "-q", "--no-trunc", myImageName)
longImageID := strings.TrimSpace(out)
assert.Assert(c, longImageID != "", "Id should not be empty")
dockerCmd(c, "save", "-o", "saveimg.tar", myImageName)
dockerCmd(c, "rmi", myImageName)
out, _ = dockerCmd(c, "images", "-q", myImageName)
noImageID := strings.TrimSpace(out)
assert.Equal(c, noImageID, "", "Should not have any image")
dockerCmd(c, "load", "-i", "saveimg.tar")
result := icmd.RunCommand("rm", "-rf", "saveimg.tar")
result.Assert(c, icmd.Success)
out, _ = dockerCmd(c, "images", "-q", "--no-trunc", myImageName)
imageID := strings.TrimSpace(out)
assert.Equal(c, imageID, longImageID, "Should have same image id as before")
out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=load")
events := strings.Split(strings.TrimSpace(out), "\n")
assert.Equal(c, len(events), 1)
matches := eventstestutils.ScanMap(events[0])
assert.Equal(c, matches["id"], imageID, "matches: %v\nout:\n%s\n", matches, out)
assert.Equal(c, matches["action"], "load", "matches: %v\nout:\n%s\n", matches, out)
out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=save")
events = strings.Split(strings.TrimSpace(out), "\n")
assert.Equal(c, len(events), 1)
matches = eventstestutils.ScanMap(events[0])
assert.Equal(c, matches["id"], imageID, "matches: %v\nout:\n%s\n", matches, out)
assert.Equal(c, matches["action"], "save", "matches: %v\nout:\n%s\n", matches, out)
}
func (s *DockerSuite) TestEventsPluginOps(c *testing.T) {
testRequires(c, DaemonIsLinux, IsAmd64, Network)
since := daemonUnixTime(c)
dockerCmd(c, "plugin", "install", pNameWithTag, "--grant-all-permissions")
dockerCmd(c, "plugin", "disable", pNameWithTag)
dockerCmd(c, "plugin", "remove", pNameWithTag)
out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c))
events := strings.Split(out, "\n")
events = events[:len(events)-1]
assert.Assert(c, len(events) >= 4)
pluginEvents := eventActionsByIDAndType(c, events, pNameWithTag, "plugin")
assert.Assert(c, is.DeepEqual(pluginEvents, []string{"pull", "enable", "disable", "remove"}), out)
}
func (s *DockerSuite) TestEventsFilters(c *testing.T) {
since := daemonUnixTime(c)
dockerCmd(c, "run", "--rm", "busybox", "true")
dockerCmd(c, "run", "--rm", "busybox", "true")
out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die")
parseEvents(c, out, "die")
out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die", "--filter", "event=start")
parseEvents(c, out, "die|start")
// make sure we at least got 2 start events
count := strings.Count(out, "start")
assert.Assert(c, count >= 2, "should have had 2 start events but had %d, out: %s", count, out)
}
func (s *DockerSuite) TestEventsFilterImageName(c *testing.T) {
since := daemonUnixTime(c)
out, _ := dockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true")
container1 := strings.TrimSpace(out)
out, _ = dockerCmd(c, "run", "--name", "container_2", "-d", "busybox", "true")
container2 := strings.TrimSpace(out)
name := "busybox"
out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name))
events := strings.Split(out, "\n")
events = events[:len(events)-1]
assert.Assert(c, len(events) != 0, "Expected events but found none for the image busybox:latest")
count1 := 0
count2 := 0
for _, e := range events {
if strings.Contains(e, container1) {
count1++
} else if strings.Contains(e, container2) {
count2++
}
}
assert.Assert(c, count1 != 0, "Expected event from container but got %d from %s", count1, container1)
assert.Assert(c, count2 != 0, "Expected event from container but got %d from %s", count2, container2)
}
func (s *DockerSuite) TestEventsFilterLabels(c *testing.T) {
since := strconv.FormatUint(uint64(daemonTime(c).Unix()), 10)
label := "io.docker.testing=foo"
out, exit := dockerCmd(c, "create", "-l", label, "busybox")
assert.Equal(c, exit, 0)
container1 := strings.TrimSpace(out)
out, exit = dockerCmd(c, "create", "busybox")
assert.Equal(c, exit, 0)
container2 := strings.TrimSpace(out)
// fetch events with `--until`, so that the client detaches after a second
// instead of staying attached, waiting for more events to arrive.
out, _ = dockerCmd(
c,
"events",
"--since", since,
"--until", strconv.FormatUint(uint64(daemonTime(c).Add(time.Second).Unix()), 10),
"--filter", "label="+label,
)
events := strings.Split(strings.TrimSpace(out), "\n")
assert.Assert(c, len(events) > 0)
var found bool
for _, e := range events {
if strings.Contains(e, container1) {
found = true
}
assert.Assert(c, !strings.Contains(e, container2))
}
assert.Assert(c, found)
}
func (s *DockerSuite) TestEventsFilterImageLabels(c *testing.T) {
since := daemonUnixTime(c)
name := "labelfiltertest"
label := "io.docker.testing=image"
// Build a test image.
buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`
FROM busybox:latest
LABEL %s`, label)))
dockerCmd(c, "tag", name, "labelfiltertest:tag1")
dockerCmd(c, "tag", name, "labelfiltertest:tag2")
dockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3")
out, _ := dockerCmd(
c,
"events",
"--since", since,
"--until", daemonUnixTime(c),
"--filter", fmt.Sprintf("label=%s", label),
"--filter", "type=image")
events := strings.Split(strings.TrimSpace(out), "\n")
// 2 events from the "docker tag" command, another one is from "docker build"
assert.Equal(c, len(events), 3, "Events == %s", events)
for _, e := range events {
assert.Check(c, strings.Contains(e, "labelfiltertest"))
}
}
func (s *DockerSuite) TestEventsFilterContainer(c *testing.T) {
since := daemonUnixTime(c)
nameID := make(map[string]string)
for _, name := range []string{"container_1", "container_2"} {
dockerCmd(c, "run", "--name", name, "busybox", "true")
id := inspectField(c, name, "Id")
nameID[name] = id
}
until := daemonUnixTime(c)
checkEvents := func(id string, events []string) error {
if len(events) != 4 { // create, attach, start, die
return fmt.Errorf("expected 4 events, got %v", events)
}
for _, event := range events {
matches := eventstestutils.ScanMap(event)
if !matchEventID(matches, id) {
return fmt.Errorf("expected event for container id %s: %s - parsed container id: %s", id, event, matches["id"])
}
}
return nil
}
for name, ID := range nameID {
// filter by names
out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+name)
events := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
assert.NilError(c, checkEvents(ID, events))
// filter by ID's
out, _ = dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+ID)
events = strings.Split(strings.TrimSuffix(out, "\n"), "\n")
assert.NilError(c, checkEvents(ID, events))
}
}
func (s *DockerSuite) TestEventsCommit(c *testing.T) {
// Problematic on Windows as cannot commit a running container
testRequires(c, DaemonIsLinux)
out := runSleepingContainer(c)
cID := strings.TrimSpace(out)
cli.WaitRun(c, cID)
cli.DockerCmd(c, "commit", "-m", "test", cID)
cli.DockerCmd(c, "stop", cID)
cli.WaitExited(c, cID, 5*time.Second)
until := daemonUnixTime(c)
out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined()
assert.Assert(c, strings.Contains(out, "commit"), "Missing 'commit' log event")
}
func (s *DockerSuite) TestEventsCopy(c *testing.T) {
// Build a test image.
buildImageSuccessfully(c, "cpimg", build.WithDockerfile(`
FROM busybox
RUN echo HI > /file`))
id := getIDByName(c, "cpimg")
// Create an empty test file.
tempFile, err := os.CreateTemp("", "test-events-copy-")
assert.NilError(c, err)
defer os.Remove(tempFile.Name())
assert.NilError(c, tempFile.Close())
dockerCmd(c, "create", "--name=cptest", id)
dockerCmd(c, "cp", "cptest:/file", tempFile.Name())
until := daemonUnixTime(c)
out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+until)
assert.Assert(c, strings.Contains(out, "archive-path"), "Missing 'archive-path' log event")
dockerCmd(c, "cp", tempFile.Name(), "cptest:/filecopy")
until = daemonUnixTime(c)
out, _ = dockerCmd(c, "events", "-f", "container=cptest", "--until="+until)
assert.Assert(c, strings.Contains(out, "extract-to-dir"), "Missing 'extract-to-dir' log event")
}
func (s *DockerSuite) TestEventsResize(c *testing.T) {
out := runSleepingContainer(c, "-d", "-t")
cID := strings.TrimSpace(out)
assert.NilError(c, waitRun(cID))
cli, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer cli.Close()
options := types.ResizeOptions{
Height: 80,
Width: 24,
}
err = cli.ContainerResize(context.Background(), cID, options)
assert.NilError(c, err)
dockerCmd(c, "stop", cID)
until := daemonUnixTime(c)
out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
assert.Assert(c, strings.Contains(out, "resize"), "Missing 'resize' log event")
}
func (s *DockerSuite) TestEventsAttach(c *testing.T) {
// TODO Windows CI: Figure out why this test fails intermittently (TP5).
testRequires(c, DaemonIsLinux)
out := cli.DockerCmd(c, "run", "-di", "busybox", "cat").Combined()
cID := strings.TrimSpace(out)
cli.WaitRun(c, cID)
cmd := exec.Command(dockerBinary, "attach", cID)
stdin, err := cmd.StdinPipe()
assert.NilError(c, err)
defer stdin.Close()
stdout, err := cmd.StdoutPipe()
assert.NilError(c, err)
defer stdout.Close()
assert.NilError(c, cmd.Start())
defer func() {
cmd.Process.Kill()
cmd.Wait()
}()
// Make sure we're done attaching by writing/reading some stuff
_, err = stdin.Write([]byte("hello\n"))
assert.NilError(c, err)
out, err = bufio.NewReader(stdout).ReadString('\n')
assert.NilError(c, err)
assert.Equal(c, strings.TrimSpace(out), "hello")
assert.NilError(c, stdin.Close())
cli.DockerCmd(c, "kill", cID)
cli.WaitExited(c, cID, 5*time.Second)
until := daemonUnixTime(c)
out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined()
assert.Assert(c, strings.Contains(out, "attach"), "Missing 'attach' log event")
}
func (s *DockerSuite) TestEventsRename(c *testing.T) {
out, _ := dockerCmd(c, "run", "--name", "oldName", "busybox", "true")
cID := strings.TrimSpace(out)
dockerCmd(c, "rename", "oldName", "newName")
until := daemonUnixTime(c)
// filter by the container id because the name in the event will be the new name.
out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until", until)
assert.Assert(c, strings.Contains(out, "rename"), "Missing 'rename' log event")
}
func (s *DockerSuite) TestEventsTop(c *testing.T) {
// Problematic on Windows as Windows does not support top
testRequires(c, DaemonIsLinux)
out := runSleepingContainer(c, "-d")
cID := strings.TrimSpace(out)
assert.NilError(c, waitRun(cID))
dockerCmd(c, "top", cID)
dockerCmd(c, "stop", cID)
until := daemonUnixTime(c)
out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
assert.Assert(c, strings.Contains(out, "top"), "Missing 'top' log event")
}
// #14316
func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *testing.T) {
// Problematic to port for Windows CI during TP5 timeframe until
// supporting push
testRequires(c, DaemonIsLinux)
testRequires(c, Network)
repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
cID := strings.TrimSpace(out)
assert.NilError(c, waitRun(cID))
dockerCmd(c, "commit", cID, repoName)
dockerCmd(c, "stop", cID)
dockerCmd(c, "push", repoName)
until := daemonUnixTime(c)
out, _ = dockerCmd(c, "events", "-f", "image="+repoName, "-f", "event=push", "--until", until)
assert.Assert(c, strings.Contains(out, repoName), "Missing 'push' log event for %s", repoName)
}
func (s *DockerSuite) TestEventsFilterType(c *testing.T) {
// FIXME(vdemeester) fails on e2e run
testRequires(c, testEnv.IsLocalDaemon)
since := daemonUnixTime(c)
name := "labelfiltertest"
label := "io.docker.testing=image"
// Build a test image.
buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`
FROM busybox:latest
LABEL %s`, label)))
dockerCmd(c, "tag", name, "labelfiltertest:tag1")
dockerCmd(c, "tag", name, "labelfiltertest:tag2")
dockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3")
out, _ := dockerCmd(
c,
"events",
"--since", since,
"--until", daemonUnixTime(c),
"--filter", fmt.Sprintf("label=%s", label),
"--filter", "type=image")
events := strings.Split(strings.TrimSpace(out), "\n")
// 2 events from the "docker tag" command, another one is from "docker build"
assert.Equal(c, len(events), 3, "Events == %s", events)
for _, e := range events {
assert.Check(c, strings.Contains(e, "labelfiltertest"))
}
out, _ = dockerCmd(
c,
"events",
"--since", since,
"--until", daemonUnixTime(c),
"--filter", fmt.Sprintf("label=%s", label),
"--filter", "type=container")
events = strings.Split(strings.TrimSpace(out), "\n")
// Events generated by the container that builds the image
assert.Equal(c, len(events), 2, "Events == %s", events)
out, _ = dockerCmd(
c,
"events",
"--since", since,
"--until", daemonUnixTime(c),
"--filter", "type=network")
events = strings.Split(strings.TrimSpace(out), "\n")
assert.Assert(c, len(events) >= 1, "Events == %s", events)
}
// #25798
func (s *DockerSuite) TestEventsSpecialFiltersWithExecCreate(c *testing.T) {
since := daemonUnixTime(c)
runSleepingContainer(c, "--name", "test-container", "-d")
waitRun("test-container")
dockerCmd(c, "exec", "test-container", "echo", "hello-world")
out, _ := dockerCmd(
c,
"events",
"--since", since,
"--until", daemonUnixTime(c),
"--filter",
"event='exec_create: echo hello-world'",
)
events := strings.Split(strings.TrimSpace(out), "\n")
assert.Equal(c, len(events), 1, out)
out, _ = dockerCmd(
c,
"events",
"--since", since,
"--until", daemonUnixTime(c),
"--filter",
"event=exec_create",
)
assert.Equal(c, len(events), 1, out)
}
func (s *DockerSuite) TestEventsFilterImageInContainerAction(c *testing.T) {
since := daemonUnixTime(c)
dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
waitRun("test-container")
out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", daemonUnixTime(c))
events := strings.Split(strings.TrimSpace(out), "\n")
assert.Assert(c, len(events) > 1, out)
}
func (s *DockerSuite) TestEventsContainerRestart(c *testing.T) {
dockerCmd(c, "run", "-d", "--name=testEvent", "--restart=on-failure:3", "busybox", "false")
// wait until test2 is auto removed.
waitTime := 10 * time.Second
if testEnv.OSType == "windows" {
// Windows takes longer...
waitTime = 90 * time.Second
}
err := waitInspect("testEvent", "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTime)
assert.NilError(c, err)
var (
createCount int
startCount int
dieCount int
)
out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container=testEvent")
events := strings.Split(strings.TrimSpace(out), "\n")
nEvents := len(events)
assert.Assert(c, nEvents >= 1)
actions := eventActionsByIDAndType(c, events, "testEvent", "container")
for _, a := range actions {
switch a {
case "create":
createCount++
case "start":
startCount++
case "die":
dieCount++
}
}
assert.Equal(c, createCount, 1, "testEvent should be created 1 times: %v", actions)
assert.Equal(c, startCount, 4, "testEvent should start 4 times: %v", actions)
assert.Equal(c, dieCount, 4, "testEvent should die 4 times: %v", actions)
}
func (s *DockerSuite) TestEventsSinceInTheFuture(c *testing.T) {
dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
waitRun("test-container")
since := daemonTime(c)
until := since.Add(time.Duration(-24) * time.Hour)
out, _, err := dockerCmdWithError("events", "--filter", "image=busybox", "--since", parseEventTime(since), "--until", parseEventTime(until))
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, "cannot be after `until`"))
}
func (s *DockerSuite) TestEventsUntilInThePast(c *testing.T) {
since := daemonUnixTime(c)
dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
waitRun("test-container")
until := daemonUnixTime(c)
dockerCmd(c, "run", "--name", "test-container2", "-d", "busybox", "true")
waitRun("test-container2")
out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", until)
assert.Assert(c, !strings.Contains(out, "test-container2"))
assert.Assert(c, strings.Contains(out, "test-container"))
}
func (s *DockerSuite) TestEventsFormat(c *testing.T) {
since := daemonUnixTime(c)
dockerCmd(c, "run", "--rm", "busybox", "true")
dockerCmd(c, "run", "--rm", "busybox", "true")
out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--format", "{{json .}}")
dec := json.NewDecoder(strings.NewReader(out))
// make sure we got 2 start events
startCount := 0
for {
var err error
var ev eventtypes.Message
if err = dec.Decode(&ev); err == io.EOF {
break
}
assert.NilError(c, err)
if ev.Status == "start" {
startCount++
}
}
assert.Equal(c, startCount, 2, "should have had 2 start events but had %d, out: %s", startCount, out)
}
func (s *DockerSuite) TestEventsFormatBadFunc(c *testing.T) {
// make sure it fails immediately, without receiving any event
result := dockerCmdWithResult("events", "--format", "{{badFuncString .}}")
result.Assert(c, icmd.Expected{
Error: "exit status 64",
ExitCode: 64,
Err: "Error parsing format: template: :1: function \"badFuncString\" not defined",
})
}
func (s *DockerSuite) TestEventsFormatBadField(c *testing.T) {
// make sure it fails immediately, without receiving any event
result := dockerCmdWithResult("events", "--format", "{{.badFieldString}}")
result.Assert(c, icmd.Expected{
Error: "exit status 64",
ExitCode: 64,
Err: "Error parsing format: template: :1:2: executing \"\" at <.badFieldString>: can't evaluate field badFieldString in type *events.Message",
})
}
| bearstech/moby | integration-cli/docker_cli_events_test.go | GO | apache-2.0 | 25,768 |
/**
* 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.storm.messaging;
import java.nio.ByteBuffer;
public class TaskMessage {
private int _task;
private byte[] _message;
public TaskMessage(int task, byte[] message) {
_task = task;
_message = message;
}
public int task() {
return _task;
}
public byte[] message() {
return _message;
}
public ByteBuffer serialize() {
ByteBuffer bb = ByteBuffer.allocate(_message.length+2);
bb.putShort((short)_task);
bb.put(_message);
return bb;
}
public void deserialize(ByteBuffer packet) {
if (packet==null) return;
_task = packet.getShort();
_message = new byte[packet.limit()-2];
packet.get(_message);
}
}
| anshuiisc/storm-Allbolts-wiring | storm-core/src/jvm/org/apache/storm/messaging/TaskMessage.java | Java | apache-2.0 | 1,579 |
cask :v1 => 'macspice' do
version '3.1.6'
sha256 '9ea9206e18ecdbe71d2fa961badbbd1cb100bad16e30e0213446cf0cd13ab7ff'
url "http://www.macspice.com/mirror/binaries/v#{version}/MacSpice3f5.dmg"
appcast 'http://www.macspice.com/AppCast-v2.xml',
:sha256 => '06453465656d258c11326d1f2cba6158a11ff9a939f557fb5da1b3b2d4402db0'
name 'MacSpice'
homepage 'http://www.macspice.com/'
license :closed
app 'MacSpice.app'
end
| gibsjose/homebrew-cask | Casks/macspice.rb | Ruby | bsd-2-clause | 437 |
object Test {
def f(ras: => IndexedSeq[Byte]): IndexedSeq[Byte] = ras
def main(args: Array[String]): Unit = {
f(new Array[Byte](0))
}
}
| yusuke2255/dotty | tests/run/t1309.scala | Scala | bsd-3-clause | 147 |
#!/bin/bash
FILE=/tmp/import_prod_done
if [ -f $FILE ]
then
echo "File $FILE exists..."
else
psql $POSTGRESQL_DATABASE < /tmp/images/production-image.sql
touch /tmp/import_prod_done
fi | fs/open-core | spec/dummy/config/cloud/cloud66/scripts/import_prod.sh | Shell | gpl-2.0 | 191 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'div', 'hu', {
IdInputLabel: 'Azonosító',
advisoryTitleInputLabel: 'Tipp szöveg',
cssClassInputLabel: 'Stíluslap osztály',
edit: 'DIV szerkesztése',
inlineStyleInputLabel: 'Inline stílus',
langDirLTRLabel: 'Balról jobbra (LTR)',
langDirLabel: 'Nyelvi irány',
langDirRTLLabel: 'Jobbról balra (RTL)',
languageCodeInputLabel: ' Nyelv kódja',
remove: 'DIV eltávolítása',
styleSelectLabel: 'Stílus',
title: 'DIV tároló létrehozása',
toolbar: 'DIV tároló létrehozása'
} );
| aodarc/flowers_room | styleguides/static/ckeditor/ckeditor/plugins/div/lang/hu.js | JavaScript | mit | 675 |
import { FaceWink24 } from "../../";
export = FaceWink24;
| markogresak/DefinitelyTyped | types/carbon__icons-react/lib/face--wink/24.d.ts | TypeScript | mit | 59 |
/*
http://www.JSON.org/json2.js
2011-02-23
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON;
if (!JSON) {
JSON = {};
}
(function () {
"use strict";
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
// Nice little hack from your friends at Airbnb - this is how all native implementations
// of JSON.parse work.
if (text == null) {
return null;
}
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
| technicolorenvy/rendr-cli | lib/generators/app/templates/javascript/assets/vendor/json2.js | JavaScript | mit | 17,599 |
/* global wp, woocommerce_admin_meta_boxes_variations, woocommerce_admin, accounting */
jQuery( function( $ ) {
/**
* Variations actions
*/
var wc_meta_boxes_product_variations_actions = {
/**
* Initialize variations actions
*/
init: function() {
$( '#variable_product_options' )
.on( 'change', 'input.variable_is_downloadable', this.variable_is_downloadable )
.on( 'change', 'input.variable_is_virtual', this.variable_is_virtual )
.on( 'change', 'input.variable_manage_stock', this.variable_manage_stock )
.on( 'click', 'button.notice-dismiss', this.notice_dismiss )
.on( 'click', 'h3 .sort', this.set_menu_order )
.on( 'reload', this.reload );
$( 'input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock' ).change();
$( '#woocommerce-product-data' ).on( 'woocommerce_variations_loaded', this.variations_loaded );
$( document.body ).on( 'woocommerce_variations_added', this.variation_added );
},
/**
* Reload UI
*
* @param {Object} event
* @param {Int} qty
*/
reload: function() {
wc_meta_boxes_product_variations_ajax.load_variations( 1 );
wc_meta_boxes_product_variations_pagenav.set_paginav( 0 );
},
/**
* Check if variation is downloadable and show/hide elements
*/
variable_is_downloadable: function() {
$( this ).closest( '.woocommerce_variation' ).find( '.show_if_variation_downloadable' ).hide();
if ( $( this ).is( ':checked' ) ) {
$( this ).closest( '.woocommerce_variation' ).find( '.show_if_variation_downloadable' ).show();
}
},
/**
* Check if variation is virtual and show/hide elements
*/
variable_is_virtual: function() {
$( this ).closest( '.woocommerce_variation' ).find( '.hide_if_variation_virtual' ).show();
if ( $( this ).is( ':checked' ) ) {
$( this ).closest( '.woocommerce_variation' ).find( '.hide_if_variation_virtual' ).hide();
}
},
/**
* Check if variation manage stock and show/hide elements
*/
variable_manage_stock: function() {
$( this ).closest( '.woocommerce_variation' ).find( '.show_if_variation_manage_stock' ).hide();
if ( $( this ).is( ':checked' ) ) {
$( this ).closest( '.woocommerce_variation' ).find( '.show_if_variation_manage_stock' ).show();
}
},
/**
* Notice dismiss
*/
notice_dismiss: function() {
$( this ).closest( 'div.notice' ).remove();
},
/**
* Run actions when variations is loaded
*
* @param {Object} event
* @param {Int} needsUpdate
*/
variations_loaded: function( event, needsUpdate ) {
needsUpdate = needsUpdate || false;
var wrapper = $( '#woocommerce-product-data' );
if ( ! needsUpdate ) {
// Show/hide downloadable, virtual and stock fields
$( 'input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock', wrapper ).change();
// Open sale schedule fields when have some sale price date
$( '.woocommerce_variation', wrapper ).each( function( index, el ) {
var $el = $( el ),
date_from = $( '.sale_price_dates_from', $el ).val(),
date_to = $( '.sale_price_dates_to', $el ).val();
if ( '' !== date_from || '' !== date_to ) {
$( 'a.sale_schedule', $el ).click();
}
});
// Remove variation-needs-update classes
$( '.woocommerce_variations .variation-needs-update', wrapper ).removeClass( 'variation-needs-update' );
// Disable cancel and save buttons
$( 'button.cancel-variation-changes, button.save-variation-changes', wrapper ).attr( 'disabled', 'disabled' );
}
// Init TipTip
$( '#tiptip_holder' ).removeAttr( 'style' );
$( '#tiptip_arrow' ).removeAttr( 'style' );
$( '.woocommerce_variations .tips, .woocommerce_variations .help_tip, .woocommerce_variations .woocommerce-help-tip', wrapper ).tipTip({
'attribute': 'data-tip',
'fadeIn': 50,
'fadeOut': 50,
'delay': 200
});
// Datepicker fields
$( '.sale_price_dates_fields', wrapper ).find( 'input' ).datepicker({
defaultDate: '',
dateFormat: 'yy-mm-dd',
numberOfMonths: 1,
showButtonPanel: true,
onSelect: function( selectedDate, instance ) {
var option = $( this ).is( '.sale_price_dates_from' ) ? 'minDate' : 'maxDate',
dates = $( this ).closest( '.sale_price_dates_fields' ).find( 'input' ),
date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings );
dates.not( this ).datepicker( 'option', option, date );
$( this ).change();
}
});
// Allow sorting
$( '.woocommerce_variations', wrapper ).sortable({
items: '.woocommerce_variation',
cursor: 'move',
axis: 'y',
handle: '.sort',
scrollSensitivity: 40,
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function() {
wc_meta_boxes_product_variations_actions.variation_row_indexes();
}
});
$( document.body ).trigger( 'wc-enhanced-select-init' );
},
/**
* Run actions when added a variation
*
* @param {Object} event
* @param {Int} qty
*/
variation_added: function( event, qty ) {
if ( 1 === qty ) {
wc_meta_boxes_product_variations_actions.variations_loaded( null, true );
}
},
/**
* Lets the user manually input menu order to move items around pages
*/
set_menu_order: function( event ) {
event.preventDefault();
var $menu_order = $( this ).closest( '.woocommerce_variation' ).find('.variation_menu_order');
var value = window.prompt( woocommerce_admin_meta_boxes_variations.i18n_enter_menu_order, $menu_order.val() );
if ( value != null ) {
// Set value, save changes and reload view
$menu_order.val( parseInt( value, 10 ) ).change();
wc_meta_boxes_product_variations_ajax.save_variations();
}
},
/**
* Set menu order
*/
variation_row_indexes: function() {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
current_page = parseInt( wrapper.attr( 'data-page' ), 10 ),
offset = parseInt( ( current_page - 1 ) * woocommerce_admin_meta_boxes_variations.variations_per_page, 10 );
$( '.woocommerce_variations .woocommerce_variation' ).each( function ( index, el ) {
$( '.variation_menu_order', el ).val( parseInt( $( el ).index( '.woocommerce_variations .woocommerce_variation' ), 10 ) + 1 + offset ).change();
});
}
};
/**
* Variations media actions
*/
var wc_meta_boxes_product_variations_media = {
/**
* wp.media frame object
*
* @type {Object}
*/
variable_image_frame: null,
/**
* Variation image ID
*
* @type {Int}
*/
setting_variation_image_id: null,
/**
* Variation image object
*
* @type {Object}
*/
setting_variation_image: null,
/**
* wp.media post ID
*
* @type {Int}
*/
wp_media_post_id: wp.media.model.settings.post.id,
/**
* Initialize media actions
*/
init: function() {
$( '#variable_product_options' ).on( 'click', '.upload_image_button', this.add_image );
$( 'a.add_media' ).on( 'click', this.restore_wp_media_post_id );
},
/**
* Added new image
*
* @param {Object} event
*/
add_image: function( event ) {
var $button = $( this ),
post_id = $button.attr( 'rel' ),
$parent = $button.closest( '.upload_image' );
wc_meta_boxes_product_variations_media.setting_variation_image = $parent;
wc_meta_boxes_product_variations_media.setting_variation_image_id = post_id;
event.preventDefault();
if ( $button.is( '.remove' ) ) {
$( '.upload_image_id', wc_meta_boxes_product_variations_media.setting_variation_image ).val( '' ).change();
wc_meta_boxes_product_variations_media.setting_variation_image.find( 'img' ).eq( 0 ).attr( 'src', woocommerce_admin_meta_boxes_variations.woocommerce_placeholder_img_src );
wc_meta_boxes_product_variations_media.setting_variation_image.find( '.upload_image_button' ).removeClass( 'remove' );
} else {
// If the media frame already exists, reopen it.
if ( wc_meta_boxes_product_variations_media.variable_image_frame ) {
wc_meta_boxes_product_variations_media.variable_image_frame.uploader.uploader.param( 'post_id', wc_meta_boxes_product_variations_media.setting_variation_image_id );
wc_meta_boxes_product_variations_media.variable_image_frame.open();
return;
} else {
wp.media.model.settings.post.id = wc_meta_boxes_product_variations_media.setting_variation_image_id;
}
// Create the media frame.
wc_meta_boxes_product_variations_media.variable_image_frame = wp.media.frames.variable_image = wp.media({
// Set the title of the modal.
title: woocommerce_admin_meta_boxes_variations.i18n_choose_image,
button: {
text: woocommerce_admin_meta_boxes_variations.i18n_set_image
},
states: [
new wp.media.controller.Library({
title: woocommerce_admin_meta_boxes_variations.i18n_choose_image,
filterable: 'all'
})
]
});
// When an image is selected, run a callback.
wc_meta_boxes_product_variations_media.variable_image_frame.on( 'select', function () {
var attachment = wc_meta_boxes_product_variations_media.variable_image_frame.state().get( 'selection' ).first().toJSON(),
url = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
$( '.upload_image_id', wc_meta_boxes_product_variations_media.setting_variation_image ).val( attachment.id ).change();
wc_meta_boxes_product_variations_media.setting_variation_image.find( '.upload_image_button' ).addClass( 'remove' );
wc_meta_boxes_product_variations_media.setting_variation_image.find( 'img' ).eq( 0 ).attr( 'src', url );
wp.media.model.settings.post.id = wc_meta_boxes_product_variations_media.wp_media_post_id;
});
// Finally, open the modal.
wc_meta_boxes_product_variations_media.variable_image_frame.open();
}
},
/**
* Restore wp.media post ID.
*/
restore_wp_media_post_id: function() {
wp.media.model.settings.post.id = wc_meta_boxes_product_variations_media.wp_media_post_id;
}
};
/**
* Product variations metabox ajax methods
*/
var wc_meta_boxes_product_variations_ajax = {
/**
* Initialize variations ajax methods
*/
init: function() {
$( 'li.variations_tab a' ).on( 'click', this.initial_load );
$( '#variable_product_options' )
.on( 'click', 'button.save-variation-changes', this.save_variations )
.on( 'click', 'button.cancel-variation-changes', this.cancel_variations )
.on( 'click', '.remove_variation', this.remove_variation );
$( document.body )
.on( 'change', '#variable_product_options .woocommerce_variations :input', this.input_changed )
.on( 'change', '.variations-defaults select', this.defaults_changed );
$( 'form#post' ).on( 'submit', this.save_on_submit );
$( '.wc-metaboxes-wrapper' ).on( 'click', 'a.do_variation_action', this.do_variation_action );
},
/**
* Check if have some changes before leave the page
*
* @return {Bool}
*/
check_for_changes: function() {
var need_update = $( '#variable_product_options' ).find( '.woocommerce_variations .variation-needs-update' );
if ( 0 < need_update.length ) {
if ( window.confirm( woocommerce_admin_meta_boxes_variations.i18n_edited_variations ) ) {
wc_meta_boxes_product_variations_ajax.save_changes();
} else {
need_update.removeClass( 'variation-needs-update' );
return false;
}
}
return true;
},
/**
* Block edit screen
*/
block: function() {
$( '#woocommerce-product-data' ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
},
/**
* Unblock edit screen
*/
unblock: function() {
$( '#woocommerce-product-data' ).unblock();
},
/**
* Initial load variations
*
* @return {Bool}
*/
initial_load: function() {
if ( 0 === $( '#variable_product_options' ).find( '.woocommerce_variations .woocommerce_variation' ).length ) {
wc_meta_boxes_product_variations_pagenav.go_to_page();
}
},
/**
* Load variations via Ajax
*
* @param {Int} page (default: 1)
* @param {Int} per_page (default: 10)
*/
load_variations: function( page, per_page ) {
page = page || 1;
per_page = per_page || woocommerce_admin_meta_boxes_variations.variations_per_page;
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' );
wc_meta_boxes_product_variations_ajax.block();
$.ajax({
url: woocommerce_admin_meta_boxes_variations.ajax_url,
data: {
action: 'woocommerce_load_variations',
security: woocommerce_admin_meta_boxes_variations.load_variations_nonce,
product_id: woocommerce_admin_meta_boxes_variations.post_id,
attributes: wrapper.data( 'attributes' ),
page: page,
per_page: per_page
},
type: 'POST',
success: function( response ) {
wrapper.empty().append( response ).attr( 'data-page', page );
$( '#woocommerce-product-data' ).trigger( 'woocommerce_variations_loaded' );
wc_meta_boxes_product_variations_ajax.unblock();
}
});
},
/**
* Ger variations fields and convert to object
*
* @param {Object} fields
*
* @return {Object}
*/
get_variations_fields: function( fields ) {
var data = $( ':input', fields ).serializeJSON();
$( '.variations-defaults select' ).each( function( index, element ) {
var select = $( element );
data[ select.attr( 'name' ) ] = select.val();
});
return data;
},
/**
* Save variations changes
*
* @param {Function} callback Called once saving is complete
*/
save_changes: function( callback ) {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
need_update = $( '.variation-needs-update', wrapper ),
data = {};
// Save only with products need update.
if ( 0 < need_update.length ) {
wc_meta_boxes_product_variations_ajax.block();
data = wc_meta_boxes_product_variations_ajax.get_variations_fields( need_update );
data.action = 'woocommerce_save_variations';
data.security = woocommerce_admin_meta_boxes_variations.save_variations_nonce;
data.product_id = woocommerce_admin_meta_boxes_variations.post_id;
data['product-type'] = $( '#product-type' ).val();
$.ajax({
url: woocommerce_admin_meta_boxes_variations.ajax_url,
data: data,
type: 'POST',
success: function( response ) {
// Allow change page, delete and add new variations
need_update.removeClass( 'variation-needs-update' );
$( 'button.cancel-variation-changes, button.save-variation-changes' ).attr( 'disabled', 'disabled' );
$( '#woocommerce-product-data' ).trigger( 'woocommerce_variations_saved' );
if ( typeof callback === 'function' ) {
callback( response );
}
wc_meta_boxes_product_variations_ajax.unblock();
}
});
}
},
/**
* Save variations
*
* @return {Bool}
*/
save_variations: function() {
$( '#variable_product_options' ).trigger( 'woocommerce_variations_save_variations_button' );
wc_meta_boxes_product_variations_ajax.save_changes( function( error ) {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
current = wrapper.attr( 'data-page' );
$( '#variable_product_options' ).find( '#woocommerce_errors' ).remove();
if ( error ) {
wrapper.before( error );
}
$( '.variations-defaults select' ).each( function() {
$( this ).attr( 'data-current', $( this ).val() );
});
wc_meta_boxes_product_variations_pagenav.go_to_page( current );
});
return false;
},
/**
* Save on post form submit
*/
save_on_submit: function( e ) {
var need_update = $( '#variable_product_options' ).find( '.woocommerce_variations .variation-needs-update' );
if ( 0 < need_update.length ) {
e.preventDefault();
$( '#variable_product_options' ).trigger( 'woocommerce_variations_save_variations_on_submit' );
wc_meta_boxes_product_variations_ajax.save_changes( wc_meta_boxes_product_variations_ajax.save_on_submit_done );
}
},
/**
* After saved, continue with form submission
*/
save_on_submit_done: function() {
$( 'form#post' ).submit();
},
/**
* Discart changes.
*
* @return {Bool}
*/
cancel_variations: function() {
var current = parseInt( $( '#variable_product_options' ).find( '.woocommerce_variations' ).attr( 'data-page' ), 10 );
$( '#variable_product_options' ).find( '.woocommerce_variations .variation-needs-update' ).removeClass( 'variation-needs-update' );
$( '.variations-defaults select' ).each( function() {
$( this ).val( $( this ).attr( 'data-current' ) );
});
wc_meta_boxes_product_variations_pagenav.go_to_page( current );
return false;
},
/**
* Add variation
*
* @return {Bool}
*/
add_variation: function() {
wc_meta_boxes_product_variations_ajax.block();
var data = {
action: 'woocommerce_add_variation',
post_id: woocommerce_admin_meta_boxes_variations.post_id,
loop: $( '.woocommerce_variation' ).length,
security: woocommerce_admin_meta_boxes_variations.add_variation_nonce
};
$.post( woocommerce_admin_meta_boxes_variations.ajax_url, data, function( response ) {
var variation = $( response );
variation.addClass( 'variation-needs-update' );
$( '#variable_product_options' ).find( '.woocommerce_variations' ).prepend( variation );
$( 'button.cancel-variation-changes, button.save-variation-changes' ).removeAttr( 'disabled' );
$( '#variable_product_options' ).trigger( 'woocommerce_variations_added', 1 );
wc_meta_boxes_product_variations_ajax.unblock();
});
return false;
},
/**
* Remove variation
*
* @return {Bool}
*/
remove_variation: function() {
wc_meta_boxes_product_variations_ajax.check_for_changes();
if ( window.confirm( woocommerce_admin_meta_boxes_variations.i18n_remove_variation ) ) {
var variation = $( this ).attr( 'rel' ),
variation_ids = [],
data = {
action: 'woocommerce_remove_variations'
};
wc_meta_boxes_product_variations_ajax.block();
if ( 0 < variation ) {
variation_ids.push( variation );
data.variation_ids = variation_ids;
data.security = woocommerce_admin_meta_boxes_variations.delete_variations_nonce;
$.post( woocommerce_admin_meta_boxes_variations.ajax_url, data, function() {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
current_page = parseInt( wrapper.attr( 'data-page' ), 10 ),
total_pages = Math.ceil( ( parseInt( wrapper.attr( 'data-total' ), 10 ) - 1 ) / woocommerce_admin_meta_boxes_variations.variations_per_page ),
page = 1;
$( '#woocommerce-product-data' ).trigger( 'woocommerce_variations_removed' );
if ( current_page === total_pages || current_page <= total_pages ) {
page = current_page;
} else if ( current_page > total_pages && 0 !== total_pages ) {
page = total_pages;
}
wc_meta_boxes_product_variations_pagenav.go_to_page( page, -1 );
});
} else {
wc_meta_boxes_product_variations_ajax.unblock();
}
}
return false;
},
/**
* Link all variations (or at least try :p)
*
* @return {Bool}
*/
link_all_variations: function() {
wc_meta_boxes_product_variations_ajax.check_for_changes();
if ( window.confirm( woocommerce_admin_meta_boxes_variations.i18n_link_all_variations ) ) {
wc_meta_boxes_product_variations_ajax.block();
var data = {
action: 'woocommerce_link_all_variations',
post_id: woocommerce_admin_meta_boxes_variations.post_id,
security: woocommerce_admin_meta_boxes_variations.link_variation_nonce
};
$.post( woocommerce_admin_meta_boxes_variations.ajax_url, data, function( response ) {
var count = parseInt( response, 10 );
if ( 1 === count ) {
window.alert( count + ' ' + woocommerce_admin_meta_boxes_variations.i18n_variation_added );
} else if ( 0 === count || count > 1 ) {
window.alert( count + ' ' + woocommerce_admin_meta_boxes_variations.i18n_variations_added );
} else {
window.alert( woocommerce_admin_meta_boxes_variations.i18n_no_variations_added );
}
if ( count > 0 ) {
wc_meta_boxes_product_variations_pagenav.go_to_page( 1, count );
$( '#variable_product_options' ).trigger( 'woocommerce_variations_added', count );
} else {
wc_meta_boxes_product_variations_ajax.unblock();
}
});
}
return false;
},
/**
* Add new class when have changes in some input
*/
input_changed: function() {
$( this )
.closest( '.woocommerce_variation' )
.addClass( 'variation-needs-update' );
$( 'button.cancel-variation-changes, button.save-variation-changes' ).removeAttr( 'disabled' );
$( '#variable_product_options' ).trigger( 'woocommerce_variations_input_changed' );
},
/**
* Added new .variation-needs-update class when defaults is changed
*/
defaults_changed: function() {
$( this )
.closest( '#variable_product_options' )
.find( '.woocommerce_variation:first' )
.addClass( 'variation-needs-update' );
$( 'button.cancel-variation-changes, button.save-variation-changes' ).removeAttr( 'disabled' );
$( '#variable_product_options' ).trigger( 'woocommerce_variations_defaults_changed' );
},
/**
* Actions
*/
do_variation_action: function() {
var do_variation_action = $( 'select.variation_actions' ).val(),
data = {},
changes = 0,
value;
switch ( do_variation_action ) {
case 'add_variation' :
wc_meta_boxes_product_variations_ajax.add_variation();
return;
case 'link_all_variations' :
wc_meta_boxes_product_variations_ajax.link_all_variations();
return;
case 'delete_all' :
if ( window.confirm( woocommerce_admin_meta_boxes_variations.i18n_delete_all_variations ) ) {
if ( window.confirm( woocommerce_admin_meta_boxes_variations.i18n_last_warning ) ) {
data.allowed = true;
changes = parseInt( $( '#variable_product_options' ).find( '.woocommerce_variations' ).attr( 'data-total' ), 10 ) * -1;
}
}
break;
case 'variable_regular_price_increase' :
case 'variable_regular_price_decrease' :
case 'variable_sale_price_increase' :
case 'variable_sale_price_decrease' :
value = window.prompt( woocommerce_admin_meta_boxes_variations.i18n_enter_a_value_fixed_or_percent );
if ( value != null ) {
if ( value.indexOf( '%' ) >= 0 ) {
data.value = accounting.unformat( value.replace( /\%/, '' ), woocommerce_admin.mon_decimal_point ) + '%';
} else {
data.value = accounting.unformat( value, woocommerce_admin.mon_decimal_point );
}
}
break;
case 'variable_regular_price' :
case 'variable_sale_price' :
case 'variable_stock' :
case 'variable_weight' :
case 'variable_length' :
case 'variable_width' :
case 'variable_height' :
case 'variable_download_limit' :
case 'variable_download_expiry' :
value = window.prompt( woocommerce_admin_meta_boxes_variations.i18n_enter_a_value );
if ( value != null ) {
data.value = value;
}
break;
case 'variable_sale_schedule' :
data.date_from = window.prompt( woocommerce_admin_meta_boxes_variations.i18n_scheduled_sale_start );
data.date_to = window.prompt( woocommerce_admin_meta_boxes_variations.i18n_scheduled_sale_end );
if ( null === data.date_from ) {
data.date_from = false;
}
if ( null === data.date_to ) {
data.date_to = false;
}
break;
default :
$( 'select.variation_actions' ).trigger( do_variation_action );
data = $( 'select.variation_actions' ).triggerHandler( do_variation_action + '_ajax_data', data );
break;
}
if ( 'delete_all' === do_variation_action && data.allowed ) {
$( '#variable_product_options' ).find( '.variation-needs-update' ).removeClass( 'variation-needs-update' );
} else {
wc_meta_boxes_product_variations_ajax.check_for_changes();
}
wc_meta_boxes_product_variations_ajax.block();
$.ajax({
url: woocommerce_admin_meta_boxes_variations.ajax_url,
data: {
action: 'woocommerce_bulk_edit_variations',
security: woocommerce_admin_meta_boxes_variations.bulk_edit_variations_nonce,
product_id: woocommerce_admin_meta_boxes_variations.post_id,
product_type: $( '#product-type' ).val(),
bulk_action: do_variation_action,
data: data
},
type: 'POST',
success: function() {
wc_meta_boxes_product_variations_pagenav.go_to_page( 1, changes );
}
});
}
};
/**
* Product variations pagenav
*/
var wc_meta_boxes_product_variations_pagenav = {
/**
* Initialize products variations meta box
*/
init: function() {
$( document.body )
.on( 'woocommerce_variations_added', this.update_single_quantity )
.on( 'change', '.variations-pagenav .page-selector', this.page_selector )
.on( 'click', '.variations-pagenav .first-page', this.first_page )
.on( 'click', '.variations-pagenav .prev-page', this.prev_page )
.on( 'click', '.variations-pagenav .next-page', this.next_page )
.on( 'click', '.variations-pagenav .last-page', this.last_page );
},
/**
* Set variations count
*
* @param {Int} qty
*
* @return {Int}
*/
update_variations_count: function( qty ) {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
total = parseInt( wrapper.attr( 'data-total' ), 10 ) + qty,
displaying_num = $( '.variations-pagenav .displaying-num' );
// Set the new total of variations
wrapper.attr( 'data-total', total );
if ( 1 === total ) {
displaying_num.text( woocommerce_admin_meta_boxes_variations.i18n_variation_count_single.replace( '%qty%', total ) );
} else {
displaying_num.text( woocommerce_admin_meta_boxes_variations.i18n_variation_count_plural.replace( '%qty%', total ) );
}
return total;
},
/**
* Update variations quantity when add a new variation
*
* @param {Object} event
* @param {Int} qty
*/
update_single_quantity: function( event, qty ) {
if ( 1 === qty ) {
var page_nav = $( '.variations-pagenav' );
wc_meta_boxes_product_variations_pagenav.update_variations_count( qty );
if ( page_nav.is( ':hidden' ) ) {
$( 'option, optgroup', '.variation_actions' ).show();
$( '.variation_actions' ).val( 'add_variation' );
$( '#variable_product_options' ).find( '.toolbar' ).show();
page_nav.show();
$( '.pagination-links', page_nav ).hide();
}
}
},
/**
* Set the pagenav fields
*
* @param {Int} qty
*/
set_paginav: function( qty ) {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
new_qty = wc_meta_boxes_product_variations_pagenav.update_variations_count( qty ),
toolbar = $( '#variable_product_options' ).find( '.toolbar' ),
variation_action = $( '.variation_actions' ),
page_nav = $( '.variations-pagenav' ),
displaying_links = $( '.pagination-links', page_nav ),
total_pages = Math.ceil( new_qty / woocommerce_admin_meta_boxes_variations.variations_per_page ),
options = '';
// Set the new total of pages
wrapper.attr( 'data-total_pages', total_pages );
$( '.total-pages', page_nav ).text( total_pages );
// Set the new pagenav options
for ( var i = 1; i <= total_pages; i++ ) {
options += '<option value="' + i + '">' + i + '</option>';
}
$( '.page-selector', page_nav ).empty().html( options );
// Show/hide pagenav
if ( 0 === new_qty ) {
toolbar.not( '.toolbar-top, .toolbar-buttons' ).hide();
page_nav.hide();
$( 'option, optgroup', variation_action ).hide();
$( '.variation_actions' ).val( 'add_variation' );
$( 'option[data-global="true"]', variation_action ).show();
} else {
toolbar.show();
page_nav.show();
$( 'option, optgroup', variation_action ).show();
$( '.variation_actions' ).val( 'add_variation' );
// Show/hide links
if ( 1 === total_pages ) {
displaying_links.hide();
} else {
displaying_links.show();
}
}
},
/**
* Check button if enabled and if don't have changes
*
* @return {Bool}
*/
check_is_enabled: function( current ) {
return ! $( current ).hasClass( 'disabled' );
},
/**
* Change "disabled" class on pagenav
*/
change_classes: function( selected, total ) {
var first_page = $( '.variations-pagenav .first-page' ),
prev_page = $( '.variations-pagenav .prev-page' ),
next_page = $( '.variations-pagenav .next-page' ),
last_page = $( '.variations-pagenav .last-page' );
if ( 1 === selected ) {
first_page.addClass( 'disabled' );
prev_page.addClass( 'disabled' );
} else {
first_page.removeClass( 'disabled' );
prev_page.removeClass( 'disabled' );
}
if ( total === selected ) {
next_page.addClass( 'disabled' );
last_page.addClass( 'disabled' );
} else {
next_page.removeClass( 'disabled' );
last_page.removeClass( 'disabled' );
}
},
/**
* Set page
*/
set_page: function( page ) {
$( '.variations-pagenav .page-selector' ).val( page ).first().change();
},
/**
* Navigate on variations pages
*
* @param {Int} page
* @param {Int} qty
*/
go_to_page: function( page, qty ) {
page = page || 1;
qty = qty || 0;
wc_meta_boxes_product_variations_pagenav.set_paginav( qty );
wc_meta_boxes_product_variations_pagenav.set_page( page );
},
/**
* Paginav pagination selector
*/
page_selector: function() {
var selected = parseInt( $( this ).val(), 10 ),
wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' );
$( '.variations-pagenav .page-selector' ).val( selected );
wc_meta_boxes_product_variations_ajax.check_for_changes();
wc_meta_boxes_product_variations_pagenav.change_classes( selected, parseInt( wrapper.attr( 'data-total_pages' ), 10 ) );
wc_meta_boxes_product_variations_ajax.load_variations( selected );
},
/**
* Go to first page
*
* @return {Bool}
*/
first_page: function() {
if ( wc_meta_boxes_product_variations_pagenav.check_is_enabled( this ) ) {
wc_meta_boxes_product_variations_pagenav.set_page( 1 );
}
return false;
},
/**
* Go to previous page
*
* @return {Bool}
*/
prev_page: function() {
if ( wc_meta_boxes_product_variations_pagenav.check_is_enabled( this ) ) {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
prev_page = parseInt( wrapper.attr( 'data-page' ), 10 ) - 1,
new_page = ( 0 < prev_page ) ? prev_page : 1;
wc_meta_boxes_product_variations_pagenav.set_page( new_page );
}
return false;
},
/**
* Go to next page
*
* @return {Bool}
*/
next_page: function() {
if ( wc_meta_boxes_product_variations_pagenav.check_is_enabled( this ) ) {
var wrapper = $( '#variable_product_options' ).find( '.woocommerce_variations' ),
total_pages = parseInt( wrapper.attr( 'data-total_pages' ), 10 ),
next_page = parseInt( wrapper.attr( 'data-page' ), 10 ) + 1,
new_page = ( total_pages >= next_page ) ? next_page : total_pages;
wc_meta_boxes_product_variations_pagenav.set_page( new_page );
}
return false;
},
/**
* Go to last page
*
* @return {Bool}
*/
last_page: function() {
if ( wc_meta_boxes_product_variations_pagenav.check_is_enabled( this ) ) {
var last_page = $( '#variable_product_options' ).find( '.woocommerce_variations' ).attr( 'data-total_pages' );
wc_meta_boxes_product_variations_pagenav.set_page( last_page );
}
return false;
}
};
wc_meta_boxes_product_variations_actions.init();
wc_meta_boxes_product_variations_media.init();
wc_meta_boxes_product_variations_ajax.init();
wc_meta_boxes_product_variations_pagenav.init();
});
| TheNaI/mummily | wp-content/plugins/woocommerce/assets/js/admin/meta-boxes-product-variation.js | JavaScript | mit | 32,595 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Debug\Tests;
use Symfony\Component\Debug\DebugClassLoader;
use Symfony\Component\Debug\ErrorHandler;
class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
{
/**
* @var int Error reporting level before running tests
*/
private $errorReporting;
private $loader;
protected function setUp()
{
$this->errorReporting = error_reporting(E_ALL | E_STRICT);
$this->loader = new ClassLoader();
spl_autoload_register(array($this->loader, 'loadClass'), true, true);
DebugClassLoader::enable();
}
protected function tearDown()
{
DebugClassLoader::disable();
spl_autoload_unregister(array($this->loader, 'loadClass'));
error_reporting($this->errorReporting);
}
public function testIdempotence()
{
DebugClassLoader::enable();
$functions = spl_autoload_functions();
foreach ($functions as $function) {
if (is_array($function) && $function[0] instanceof DebugClassLoader) {
$reflClass = new \ReflectionClass($function[0]);
$reflProp = $reflClass->getProperty('classLoader');
$reflProp->setAccessible(true);
$this->assertNotInstanceOf('Symfony\Component\Debug\DebugClassLoader', $reflProp->getValue($function[0]));
return;
}
}
$this->fail('DebugClassLoader did not register');
}
public function testUnsilencing()
{
if (PHP_VERSION_ID >= 70000) {
$this->markTestSkipped('PHP7 throws exceptions, unsilencing is not required anymore.');
}
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('HHVM is not handled in this test case.');
}
ob_start();
$this->iniSet('log_errors', 0);
$this->iniSet('display_errors', 1);
// See below: this will fail with parse error
// but this should not be @-silenced.
@class_exists(__NAMESPACE__.'\TestingUnsilencing', true);
$output = ob_get_clean();
$this->assertStringMatchesFormat('%aParse error%a', $output);
}
public function testStacking()
{
// the ContextErrorException must not be loaded to test the workaround
// for https://bugs.php.net/65322.
if (class_exists('Symfony\Component\Debug\Exception\ContextErrorException', false)) {
$this->markTestSkipped('The ContextErrorException class is already loaded.');
}
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('HHVM is not handled in this test case.');
}
ErrorHandler::register();
try {
// Trigger autoloading + E_STRICT at compile time
// which in turn triggers $errorHandler->handle()
// that again triggers autoloading for ContextErrorException.
// Error stacking works around the bug above and everything is fine.
eval('
namespace '.__NAMESPACE__.';
class ChildTestingStacking extends TestingStacking { function foo($bar) {} }
');
$this->fail('ContextErrorException expected');
} catch (\ErrorException $exception) {
// if an exception is thrown, the test passed
restore_error_handler();
restore_exception_handler();
$this->assertStringStartsWith(__FILE__, $exception->getFile());
if (PHP_VERSION_ID < 70000) {
$this->assertRegExp('/^Runtime Notice: Declaration/', $exception->getMessage());
$this->assertEquals(E_STRICT, $exception->getSeverity());
} else {
$this->assertRegExp('/^Warning: Declaration/', $exception->getMessage());
$this->assertEquals(E_WARNING, $exception->getSeverity());
}
} catch (\Exception $exception) {
restore_error_handler();
restore_exception_handler();
throw $exception;
}
}
/**
* @expectedException \RuntimeException
*/
public function testNameCaseMismatch()
{
class_exists(__NAMESPACE__.'\TestingCaseMismatch', true);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Case mismatch between class and real file names
*/
public function testFileCaseMismatch()
{
if (!file_exists(__DIR__.'/Fixtures/CaseMismatch.php')) {
$this->markTestSkipped('Can only be run on case insensitive filesystems');
}
class_exists(__NAMESPACE__.'\Fixtures\CaseMismatch', true);
}
/**
* @expectedException \RuntimeException
*/
public function testPsr4CaseMismatch()
{
class_exists(__NAMESPACE__.'\Fixtures\Psr4CaseMismatch', true);
}
public function testNotPsr0()
{
$this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\NotPSR0', true));
}
public function testNotPsr0Bis()
{
$this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\NotPSR0bis', true));
}
public function testClassAlias()
{
$this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\ClassAlias', true));
}
/**
* @dataProvider provideDeprecatedSuper
*/
public function testDeprecatedSuper($class, $super, $type)
{
set_error_handler(function () { return false; });
$e = error_reporting(0);
trigger_error('', E_USER_DEPRECATED);
class_exists('Test\\'.__NAMESPACE__.'\\'.$class, true);
error_reporting($e);
restore_error_handler();
$lastError = error_get_last();
unset($lastError['file'], $lastError['line']);
$xError = array(
'type' => E_USER_DEPRECATED,
'message' => 'The Test\Symfony\Component\Debug\Tests\\'.$class.' class '.$type.' Symfony\Component\Debug\Tests\Fixtures\\'.$super.' that is deprecated but this is a test deprecation notice.',
);
$this->assertSame($xError, $lastError);
}
public function provideDeprecatedSuper()
{
return array(
array('DeprecatedInterfaceClass', 'DeprecatedInterface', 'implements'),
array('DeprecatedParentClass', 'DeprecatedClass', 'extends'),
);
}
public function testDeprecatedSuperInSameNamespace()
{
set_error_handler(function () { return false; });
$e = error_reporting(0);
trigger_error('', E_USER_NOTICE);
class_exists('Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent', true);
error_reporting($e);
restore_error_handler();
$lastError = error_get_last();
unset($lastError['file'], $lastError['line']);
$xError = array(
'type' => E_USER_NOTICE,
'message' => '',
);
$this->assertSame($xError, $lastError);
}
public function testReservedForPhp7()
{
if (PHP_VERSION_ID >= 70000) {
$this->markTestSkipped('PHP7 already prevents using reserved names.');
}
set_error_handler(function () { return false; });
$e = error_reporting(0);
trigger_error('', E_USER_NOTICE);
class_exists('Test\\'.__NAMESPACE__.'\\Float', true);
error_reporting($e);
restore_error_handler();
$lastError = error_get_last();
unset($lastError['file'], $lastError['line']);
$xError = array(
'type' => E_USER_DEPRECATED,
'message' => 'Test\Symfony\Component\Debug\Tests\Float uses a reserved class name (Float) that will break on PHP 7 and higher',
);
$this->assertSame($xError, $lastError);
}
}
class ClassLoader
{
public function loadClass($class)
{
}
public function getClassMap()
{
return array(__NAMESPACE__.'\Fixtures\NotPSR0bis' => __DIR__.'/Fixtures/notPsr0Bis.php');
}
public function findFile($class)
{
$fixtureDir = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR;
if (__NAMESPACE__.'\TestingUnsilencing' === $class) {
eval('-- parse error --');
} elseif (__NAMESPACE__.'\TestingStacking' === $class) {
eval('namespace '.__NAMESPACE__.'; class TestingStacking { function foo() {} }');
} elseif (__NAMESPACE__.'\TestingCaseMismatch' === $class) {
eval('namespace '.__NAMESPACE__.'; class TestingCaseMisMatch {}');
} elseif (__NAMESPACE__.'\Fixtures\CaseMismatch' === $class) {
return $fixtureDir.'CaseMismatch.php';
} elseif (__NAMESPACE__.'\Fixtures\Psr4CaseMismatch' === $class) {
return $fixtureDir.'psr4'.DIRECTORY_SEPARATOR.'Psr4CaseMismatch.php';
} elseif (__NAMESPACE__.'\Fixtures\NotPSR0' === $class) {
return $fixtureDir.'reallyNotPsr0.php';
} elseif (__NAMESPACE__.'\Fixtures\NotPSR0bis' === $class) {
return $fixtureDir.'notPsr0Bis.php';
} elseif (__NAMESPACE__.'\Fixtures\DeprecatedInterface' === $class) {
return $fixtureDir.'DeprecatedInterface.php';
} elseif ('Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent' === $class) {
eval('namespace Symfony\Bridge\Debug\Tests\Fixtures; class ExtendsDeprecatedParent extends \\'.__NAMESPACE__.'\Fixtures\DeprecatedClass {}');
} elseif ('Test\\'.__NAMESPACE__.'\DeprecatedParentClass' === $class) {
eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedParentClass extends \\'.__NAMESPACE__.'\Fixtures\DeprecatedClass {}');
} elseif ('Test\\'.__NAMESPACE__.'\DeprecatedInterfaceClass' === $class) {
eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedInterfaceClass implements \\'.__NAMESPACE__.'\Fixtures\DeprecatedInterface {}');
} elseif ('Test\\'.__NAMESPACE__.'\Float' === $class) {
eval('namespace Test\\'.__NAMESPACE__.'; class Float {}');
}
}
}
| elqueace/TS | vendor/symfony/symfony/src/Symfony/Component/Debug/Tests/DebugClassLoaderTest.php | PHP | mit | 10,241 |
import chug from 'gulp-chug';
import gulp from 'gulp';
import yargs from 'yargs';
const { argv } = yargs
.options({
rootPath: {
description: '<path> path to public assets directory',
type: 'string',
requiresArg: true,
required: false,
},
nodeModulesPath: {
description: '<path> path to node_modules directory',
type: 'string',
requiresArg: true,
required: false,
},
});
const config = [
'--rootPath',
argv.rootPath || '../../../../public/assets',
'--nodeModulesPath',
argv.nodeModulesPath || '../../../../node_modules',
];
export const buildAdmin = function buildAdmin() {
return gulp.src('src/Sylius/Bundle/AdminBundle/gulpfile.babel.js', { read: false })
.pipe(chug({ args: config, tasks: 'build' }));
};
buildAdmin.description = 'Build admin assets.';
export const watchAdmin = function watchAdmin() {
return gulp.src('src/Sylius/Bundle/AdminBundle/gulpfile.babel.js', { read: false })
.pipe(chug({ args: config, tasks: 'watch' }));
};
watchAdmin.description = 'Watch admin asset sources and rebuild on changes.';
export const buildShop = function buildShop() {
return gulp.src('src/Sylius/Bundle/ShopBundle/gulpfile.babel.js', { read: false })
.pipe(chug({ args: config, tasks: 'build' }));
};
buildShop.description = 'Build shop assets.';
export const watchShop = function watchShop() {
return gulp.src('src/Sylius/Bundle/ShopBundle/gulpfile.babel.js', { read: false })
.pipe(chug({ args: config, tasks: 'watch' }));
};
watchShop.description = 'Watch shop asset sources and rebuild on changes.';
export const build = gulp.parallel(buildAdmin, buildShop);
build.description = 'Build assets.';
gulp.task('admin', buildAdmin);
gulp.task('admin-watch', watchAdmin);
gulp.task('shop', buildShop);
gulp.task('shop-watch', watchShop);
export default build;
| Brille24/Sylius | gulpfile.babel.js | JavaScript | mit | 1,864 |
/**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.satel.internal.protocol;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a message sent to (a command) or received from (a response)
* {@link SatelModule}. It consists of one byte that specifies command type or
* response status and certain number of payload bytes. Number of payload byte
* depends on command type. The class allows to serialize a command to bytes and
* deserialize a response from given bytes. It also computes and validates
* message checksum.
*
* @author Krzysztof Goworek
* @since 1.7.0
*/
public class SatelMessage {
private static final Logger logger = LoggerFactory.getLogger(SatelMessage.class);
private byte command;
private byte[] payload;
private static final byte[] EMPTY_PAYLOAD = new byte[0];
/**
* Creates new instance with specified command code and payload.
*
* @param command
* command code
* @param payload
* command payload
*/
public SatelMessage(byte command, byte[] payload) {
this.command = command;
this.payload = payload;
}
/**
* Creates new instance with specified command code and empty payload.
*
* @param command
* command code
*/
public SatelMessage(byte command) {
this(command, EMPTY_PAYLOAD);
}
/**
* Deserializes new message instance from specified byte buffer.
*
* @param buffer
* bytes to deserialize a message from
* @return deserialized message instance
*/
public static SatelMessage fromBytes(byte[] buffer) {
// we need at least command and checksum
if (buffer.length < 3) {
logger.error("Invalid message length: {}", buffer.length);
return null;
}
// check crc
int receivedCrc = 0xffff & ((buffer[buffer.length - 2] << 8) | (buffer[buffer.length - 1] & 0xff));
int expectedCrc = calculateChecksum(buffer, buffer.length - 2);
if (receivedCrc != expectedCrc) {
logger.error("Invalid message checksum: received = {}, expected = {}", receivedCrc, expectedCrc);
return null;
}
SatelMessage message = new SatelMessage(buffer[0], new byte[buffer.length - 3]);
if (message.payload.length > 0) {
System.arraycopy(buffer, 1, message.payload, 0, buffer.length - 3);
}
return message;
}
/**
* Returns command byte.
*
* @return the command
*/
public byte getCommand() {
return this.command;
}
/**
* Returns the payload bytes.
*
* @return payload as byte array
*/
public byte[] getPayload() {
return this.payload;
}
/**
* Returns the message serialized as array of bytes with checksum calculated
* at last two bytes.
*
* @return the message as array of bytes
*/
public byte[] getBytes() {
byte buffer[] = new byte[this.payload.length + 3];
buffer[0] = this.command;
if (this.payload.length > 0) {
System.arraycopy(this.payload, 0, buffer, 1, this.payload.length);
}
int checksum = calculateChecksum(buffer, buffer.length - 2);
buffer[buffer.length - 2] = (byte) ((checksum >> 8) & 0xff);
buffer[buffer.length - 1] = (byte) (checksum & 0xff);
return buffer;
}
private String getPayloadAsHex() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < this.payload.length; ++i) {
if (i > 0) {
result.append(" ");
}
result.append(String.format("%02X", this.payload[i]));
}
return result.toString();
}
/**
* Calculates a checksum for the specified buffer.
*
* @param buffer
* the buffer to calculate.
* @return the checksum value.
*/
private static int calculateChecksum(byte[] buffer, int length) {
int checkSum = 0x147a;
for (int i = 0; i < length; i++) {
checkSum = ((checkSum << 1) | ((checkSum >> 15) & 1));
checkSum ^= 0xffff;
checkSum += ((checkSum >> 8) & 0xff) + (buffer[i] & 0xff);
}
checkSum &= 0xffff;
logger.trace("Calculated checksum = {}", String.format("%04X", checkSum));
return checkSum;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("Message: command = %02X, payload = %s", this.command, getPayloadAsHex());
};
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!obj.getClass().equals(this.getClass())) {
return false;
}
SatelMessage other = (SatelMessage) obj;
if (other.command != this.command) {
return false;
}
if (!Arrays.equals(other.payload, this.payload)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + command;
result = prime * result + Arrays.hashCode(payload);
return result;
}
}
| paolodenti/openhab | bundles/binding/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/SatelMessage.java | Java | epl-1.0 | 5,954 |
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "../game/q_shared.h"
#include "qcommon.h"
/*
packet header
-------------
4 outgoing sequence. high bit will be set if this is a fragmented message
[2 qport (only for client to server)]
[2 fragment start byte]
[2 fragment length. if < FRAGMENT_SIZE, this is the last fragment]
if the sequence number is -1, the packet should be handled as an out-of-band
message instead of as part of a netcon.
All fragments will have the same sequence numbers.
The qport field is a workaround for bad address translating routers that
sometimes remap the client's source port on a packet during gameplay.
If the base part of the net address matches and the qport matches, then the
channel matches even if the IP port differs. The IP port should be updated
to the new value before sending out any replies.
*/
#define MAX_PACKETLEN 1400 // max size of a network packet
#define FRAGMENT_SIZE (MAX_PACKETLEN - 100)
#define PACKET_HEADER 10 // two ints and a short
#define FRAGMENT_BIT (1<<31)
cvar_t *showpackets;
cvar_t *showdrop;
cvar_t *qport;
static char *netsrcString[2] = {
"client",
"server"
};
/*
===============
Netchan_Init
===============
*/
void Netchan_Init( int port ) {
port &= 0xffff;
showpackets = Cvar_Get ("showpackets", "0", CVAR_TEMP );
showdrop = Cvar_Get ("showdrop", "0", CVAR_TEMP );
qport = Cvar_Get ("net_qport", va("%i", port), CVAR_INIT );
}
/*
==============
Netchan_Setup
called to open a channel to a remote system
==============
*/
void Netchan_Setup( netsrc_t sock, netchan_t *chan, netadr_t adr, int qport ) {
Com_Memset (chan, 0, sizeof(*chan));
chan->sock = sock;
chan->remoteAddress = adr;
chan->qport = qport;
chan->incomingSequence = 0;
chan->outgoingSequence = 1;
}
// TTimo: unused, commenting out to make gcc happy
#if 0
/*
==============
Netchan_ScramblePacket
A probably futile attempt to make proxy hacking somewhat
more difficult.
==============
*/
#define SCRAMBLE_START 6
static void Netchan_ScramblePacket( msg_t *buf ) {
unsigned seed;
int i, j, c, mask, temp;
int seq[MAX_PACKETLEN];
seed = ( LittleLong( *(unsigned *)buf->data ) * 3 ) ^ ( buf->cursize * 123 );
c = buf->cursize;
if ( c <= SCRAMBLE_START ) {
return;
}
if ( c > MAX_PACKETLEN ) {
Com_Error( ERR_DROP, "MAX_PACKETLEN" );
}
// generate a sequence of "random" numbers
for (i = 0 ; i < c ; i++) {
seed = (119 * seed + 1);
seq[i] = seed;
}
// transpose each character
for ( mask = 1 ; mask < c-SCRAMBLE_START ; mask = ( mask << 1 ) + 1 ) {
}
mask >>= 1;
for (i = SCRAMBLE_START ; i < c ; i++) {
j = SCRAMBLE_START + ( seq[i] & mask );
temp = buf->data[j];
buf->data[j] = buf->data[i];
buf->data[i] = temp;
}
// byte xor the data after the header
for (i = SCRAMBLE_START ; i < c ; i++) {
buf->data[i] ^= seq[i];
}
}
static void Netchan_UnScramblePacket( msg_t *buf ) {
unsigned seed;
int i, j, c, mask, temp;
int seq[MAX_PACKETLEN];
seed = ( LittleLong( *(unsigned *)buf->data ) * 3 ) ^ ( buf->cursize * 123 );
c = buf->cursize;
if ( c <= SCRAMBLE_START ) {
return;
}
if ( c > MAX_PACKETLEN ) {
Com_Error( ERR_DROP, "MAX_PACKETLEN" );
}
// generate a sequence of "random" numbers
for (i = 0 ; i < c ; i++) {
seed = (119 * seed + 1);
seq[i] = seed;
}
// byte xor the data after the header
for (i = SCRAMBLE_START ; i < c ; i++) {
buf->data[i] ^= seq[i];
}
// transpose each character in reverse order
for ( mask = 1 ; mask < c-SCRAMBLE_START ; mask = ( mask << 1 ) + 1 ) {
}
mask >>= 1;
for (i = c-1 ; i >= SCRAMBLE_START ; i--) {
j = SCRAMBLE_START + ( seq[i] & mask );
temp = buf->data[j];
buf->data[j] = buf->data[i];
buf->data[i] = temp;
}
}
#endif
/*
=================
Netchan_TransmitNextFragment
Send one fragment of the current message
=================
*/
void Netchan_TransmitNextFragment( netchan_t *chan ) {
msg_t send;
byte send_buf[MAX_PACKETLEN];
int fragmentLength;
// write the packet header
MSG_InitOOB (&send, send_buf, sizeof(send_buf)); // <-- only do the oob here
MSG_WriteLong( &send, chan->outgoingSequence | FRAGMENT_BIT );
// send the qport if we are a client
if ( chan->sock == NS_CLIENT ) {
MSG_WriteShort( &send, qport->integer );
}
// copy the reliable message to the packet first
fragmentLength = FRAGMENT_SIZE;
if ( chan->unsentFragmentStart + fragmentLength > chan->unsentLength ) {
fragmentLength = chan->unsentLength - chan->unsentFragmentStart;
}
MSG_WriteShort( &send, chan->unsentFragmentStart );
MSG_WriteShort( &send, fragmentLength );
MSG_WriteData( &send, chan->unsentBuffer + chan->unsentFragmentStart, fragmentLength );
// send the datagram
NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress );
if ( showpackets->integer ) {
Com_Printf ("%s send %4i : s=%i fragment=%i,%i\n"
, netsrcString[ chan->sock ]
, send.cursize
, chan->outgoingSequence
, chan->unsentFragmentStart, fragmentLength);
}
chan->unsentFragmentStart += fragmentLength;
// this exit condition is a little tricky, because a packet
// that is exactly the fragment length still needs to send
// a second packet of zero length so that the other side
// can tell there aren't more to follow
if ( chan->unsentFragmentStart == chan->unsentLength && fragmentLength != FRAGMENT_SIZE ) {
chan->outgoingSequence++;
chan->unsentFragments = qfalse;
}
}
/*
===============
Netchan_Transmit
Sends a message to a connection, fragmenting if necessary
A 0 length will still generate a packet.
================
*/
void Netchan_Transmit( netchan_t *chan, int length, const byte *data ) {
msg_t send;
byte send_buf[MAX_PACKETLEN];
if ( length > MAX_MSGLEN ) {
Com_Error( ERR_DROP, "Netchan_Transmit: length = %i", length );
}
chan->unsentFragmentStart = 0;
// fragment large reliable messages
if ( length >= FRAGMENT_SIZE ) {
chan->unsentFragments = qtrue;
chan->unsentLength = length;
Com_Memcpy( chan->unsentBuffer, data, length );
// only send the first fragment now
Netchan_TransmitNextFragment( chan );
return;
}
// write the packet header
MSG_InitOOB (&send, send_buf, sizeof(send_buf));
MSG_WriteLong( &send, chan->outgoingSequence );
chan->outgoingSequence++;
// send the qport if we are a client
if ( chan->sock == NS_CLIENT ) {
MSG_WriteShort( &send, qport->integer );
}
MSG_WriteData( &send, data, length );
// send the datagram
NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress );
if ( showpackets->integer ) {
Com_Printf( "%s send %4i : s=%i ack=%i\n"
, netsrcString[ chan->sock ]
, send.cursize
, chan->outgoingSequence - 1
, chan->incomingSequence );
}
}
/*
=================
Netchan_Process
Returns qfalse if the message should not be processed due to being
out of order or a fragment.
Msg must be large enough to hold MAX_MSGLEN, because if this is the
final fragment of a multi-part message, the entire thing will be
copied out.
=================
*/
qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) {
int sequence;
int qport;
int fragmentStart, fragmentLength;
qboolean fragmented;
// XOR unscramble all data in the packet after the header
// Netchan_UnScramblePacket( msg );
// get sequence numbers
MSG_BeginReadingOOB( msg );
sequence = MSG_ReadLong( msg );
// check for fragment information
if ( sequence & FRAGMENT_BIT ) {
sequence &= ~FRAGMENT_BIT;
fragmented = qtrue;
} else {
fragmented = qfalse;
}
// read the qport if we are a server
if ( chan->sock == NS_SERVER ) {
qport = MSG_ReadShort( msg );
}
// read the fragment information
if ( fragmented ) {
fragmentStart = MSG_ReadShort( msg );
fragmentLength = MSG_ReadShort( msg );
} else {
fragmentStart = 0; // stop warning message
fragmentLength = 0;
}
if ( showpackets->integer ) {
if ( fragmented ) {
Com_Printf( "%s recv %4i : s=%i fragment=%i,%i\n"
, netsrcString[ chan->sock ]
, msg->cursize
, sequence
, fragmentStart, fragmentLength );
} else {
Com_Printf( "%s recv %4i : s=%i\n"
, netsrcString[ chan->sock ]
, msg->cursize
, sequence );
}
}
//
// discard out of order or duplicated packets
//
if ( sequence <= chan->incomingSequence ) {
if ( showdrop->integer || showpackets->integer ) {
Com_Printf( "%s:Out of order packet %i at %i\n"
, NET_AdrToString( chan->remoteAddress )
, sequence
, chan->incomingSequence );
}
return qfalse;
}
//
// dropped packets don't keep the message from being used
//
chan->dropped = sequence - (chan->incomingSequence+1);
if ( chan->dropped > 0 ) {
if ( showdrop->integer || showpackets->integer ) {
Com_Printf( "%s:Dropped %i packets at %i\n"
, NET_AdrToString( chan->remoteAddress )
, chan->dropped
, sequence );
}
}
//
// if this is the final framgent of a reliable message,
// bump incoming_reliable_sequence
//
if ( fragmented ) {
// TTimo
// make sure we add the fragments in correct order
// either a packet was dropped, or we received this one too soon
// we don't reconstruct the fragments. we will wait till this fragment gets to us again
// (NOTE: we could probably try to rebuild by out of order chunks if needed)
if ( sequence != chan->fragmentSequence ) {
chan->fragmentSequence = sequence;
chan->fragmentLength = 0;
}
// if we missed a fragment, dump the message
if ( fragmentStart != chan->fragmentLength ) {
if ( showdrop->integer || showpackets->integer ) {
Com_Printf( "%s:Dropped a message fragment\n"
, NET_AdrToString( chan->remoteAddress )
, sequence);
}
// we can still keep the part that we have so far,
// so we don't need to clear chan->fragmentLength
return qfalse;
}
// copy the fragment to the fragment buffer
if ( fragmentLength < 0 || msg->readcount + fragmentLength > msg->cursize ||
chan->fragmentLength + fragmentLength > sizeof( chan->fragmentBuffer ) ) {
if ( showdrop->integer || showpackets->integer ) {
Com_Printf ("%s:illegal fragment length\n"
, NET_AdrToString (chan->remoteAddress ) );
}
return qfalse;
}
Com_Memcpy( chan->fragmentBuffer + chan->fragmentLength,
msg->data + msg->readcount, fragmentLength );
chan->fragmentLength += fragmentLength;
// if this wasn't the last fragment, don't process anything
if ( fragmentLength == FRAGMENT_SIZE ) {
return qfalse;
}
if ( chan->fragmentLength > msg->maxsize ) {
Com_Printf( "%s:fragmentLength %i > msg->maxsize\n"
, NET_AdrToString (chan->remoteAddress ),
chan->fragmentLength );
return qfalse;
}
// copy the full message over the partial fragment
// make sure the sequence number is still there
*(int *)msg->data = LittleLong( sequence );
Com_Memcpy( msg->data + 4, chan->fragmentBuffer, chan->fragmentLength );
msg->cursize = chan->fragmentLength + 4;
chan->fragmentLength = 0;
msg->readcount = 4; // past the sequence number
msg->bit = 32; // past the sequence number
// TTimo
// clients were not acking fragmented messages
chan->incomingSequence = sequence;
return qtrue;
}
//
// the message can now be read from the current message pointer
//
chan->incomingSequence = sequence;
return qtrue;
}
//==============================================================================
/*
===================
NET_CompareBaseAdr
Compares without the port
===================
*/
qboolean NET_CompareBaseAdr (netadr_t a, netadr_t b)
{
if (a.type != b.type)
return qfalse;
if (a.type == NA_LOOPBACK)
return qtrue;
if (a.type == NA_IP)
{
if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3])
return qtrue;
return qfalse;
}
if (a.type == NA_IPX)
{
if ((memcmp(a.ipx, b.ipx, 10) == 0))
return qtrue;
return qfalse;
}
Com_Printf ("NET_CompareBaseAdr: bad address type\n");
return qfalse;
}
const char *NET_AdrToString (netadr_t a)
{
static char s[64];
if (a.type == NA_LOOPBACK) {
Com_sprintf (s, sizeof(s), "loopback");
} else if (a.type == NA_BOT) {
Com_sprintf (s, sizeof(s), "bot");
} else if (a.type == NA_IP) {
Com_sprintf (s, sizeof(s), "%i.%i.%i.%i:%hu",
a.ip[0], a.ip[1], a.ip[2], a.ip[3], BigShort(a.port));
} else {
Com_sprintf (s, sizeof(s), "%02x%02x%02x%02x.%02x%02x%02x%02x%02x%02x:%hu",
a.ipx[0], a.ipx[1], a.ipx[2], a.ipx[3], a.ipx[4], a.ipx[5], a.ipx[6], a.ipx[7], a.ipx[8], a.ipx[9],
BigShort(a.port));
}
return s;
}
qboolean NET_CompareAdr (netadr_t a, netadr_t b)
{
if (a.type != b.type)
return qfalse;
if (a.type == NA_LOOPBACK)
return qtrue;
if (a.type == NA_IP)
{
if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3] && a.port == b.port)
return qtrue;
return qfalse;
}
if (a.type == NA_IPX)
{
if ((memcmp(a.ipx, b.ipx, 10) == 0) && a.port == b.port)
return qtrue;
return qfalse;
}
Com_Printf ("NET_CompareAdr: bad address type\n");
return qfalse;
}
qboolean NET_IsLocalAddress( netadr_t adr ) {
return adr.type == NA_LOOPBACK;
}
/*
=============================================================================
LOOPBACK BUFFERS FOR LOCAL PLAYER
=============================================================================
*/
// there needs to be enough loopback messages to hold a complete
// gamestate of maximum size
#define MAX_LOOPBACK 16
typedef struct {
byte data[MAX_PACKETLEN];
int datalen;
} loopmsg_t;
typedef struct {
loopmsg_t msgs[MAX_LOOPBACK];
int get, send;
} loopback_t;
loopback_t loopbacks[2];
qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, msg_t *net_message)
{
int i;
loopback_t *loop;
loop = &loopbacks[sock];
if (loop->send - loop->get > MAX_LOOPBACK)
loop->get = loop->send - MAX_LOOPBACK;
if (loop->get >= loop->send)
return qfalse;
i = loop->get & (MAX_LOOPBACK-1);
loop->get++;
Com_Memcpy (net_message->data, loop->msgs[i].data, loop->msgs[i].datalen);
net_message->cursize = loop->msgs[i].datalen;
Com_Memset (net_from, 0, sizeof(*net_from));
net_from->type = NA_LOOPBACK;
return qtrue;
}
void NET_SendLoopPacket (netsrc_t sock, int length, const void *data, netadr_t to)
{
int i;
loopback_t *loop;
loop = &loopbacks[sock^1];
i = loop->send & (MAX_LOOPBACK-1);
loop->send++;
Com_Memcpy (loop->msgs[i].data, data, length);
loop->msgs[i].datalen = length;
}
//=============================================================================
void NET_SendPacket( netsrc_t sock, int length, const void *data, netadr_t to ) {
// sequenced packets are shown in netchan, so just show oob
if ( showpackets->integer && *(int *)data == -1 ) {
Com_Printf ("send packet %4i\n", length);
}
if ( to.type == NA_LOOPBACK ) {
NET_SendLoopPacket (sock, length, data, to);
return;
}
if ( to.type == NA_BOT ) {
return;
}
if ( to.type == NA_BAD ) {
return;
}
Sys_SendPacket( length, data, to );
}
/*
===============
NET_OutOfBandPrint
Sends a text message in an out-of-band datagram
================
*/
void QDECL NET_OutOfBandPrint( netsrc_t sock, netadr_t adr, const char *format, ... ) {
va_list argptr;
char string[MAX_MSGLEN];
// set the header
string[0] = -1;
string[1] = -1;
string[2] = -1;
string[3] = -1;
va_start( argptr, format );
vsprintf( string+4, format, argptr );
va_end( argptr );
// send the datagram
NET_SendPacket( sock, strlen( string ), string, adr );
}
/*
===============
NET_OutOfBandPrint
Sends a data message in an out-of-band datagram (only used for "connect")
================
*/
void QDECL NET_OutOfBandData( netsrc_t sock, netadr_t adr, byte *format, int len ) {
byte string[MAX_MSGLEN*2];
int i;
msg_t mbuf;
// set the header
string[0] = 0xff;
string[1] = 0xff;
string[2] = 0xff;
string[3] = 0xff;
for(i=0;i<len;i++) {
string[i+4] = format[i];
}
mbuf.data = string;
mbuf.cursize = len+4;
Huff_Compress( &mbuf, 12);
// send the datagram
NET_SendPacket( sock, mbuf.cursize, mbuf.data, adr );
}
/*
=============
NET_StringToAdr
Traps "localhost" for loopback, passes everything else to system
=============
*/
qboolean NET_StringToAdr( const char *s, netadr_t *a ) {
qboolean r;
char base[MAX_STRING_CHARS];
char *port;
if (!strcmp (s, "localhost")) {
Com_Memset (a, 0, sizeof(*a));
a->type = NA_LOOPBACK;
return qtrue;
}
// look for a port number
Q_strncpyz( base, s, sizeof( base ) );
port = strstr( base, ":" );
if ( port ) {
*port = 0;
port++;
}
r = Sys_StringToAdr( base, a );
if ( !r ) {
a->type = NA_BAD;
return qfalse;
}
// inet_addr returns this if out of range
if ( a->ip[0] == 255 && a->ip[1] == 255 && a->ip[2] == 255 && a->ip[3] == 255 ) {
a->type = NA_BAD;
return qfalse;
}
if ( port ) {
a->port = BigShort( (short)atoi( port ) );
} else {
a->port = BigShort( PORT_SERVER );
}
return qtrue;
}
| entdark/q3mme | trunk/code/qcommon/net_chan.c | C | gpl-2.0 | 17,808 |
#
# (C) Copyright 2000-2004
# Wolfgang Denk, DENX Software Engineering, [email protected].
#
# 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
#
include $(TOPDIR)/config.mk
LIB = lib$(BOARD).a
OBJS = $(BOARD).o ../common/flash.o ../common/kup.o ../common/load_sernum_ethaddr.o ../common/pcmcia.o
$(LIB): .depend $(OBJS)
$(AR) crv $@ $(OBJS)
#########################################################################
.depend: Makefile $(SOBJS:.o=.S) $(OBJS:.o=.c)
$(CC) -M $(CFLAGS) $(SOBJS:.o=.S) $(OBJS:.o=.c) > $@
sinclude .depend
#########################################################################
| astarasikov/uboot-bn-nook-hd-fastboot | board/kup/kup4x/Makefile | Makefile | gpl-2.0 | 1,335 |
<?php
/**
* Generates the styles for the frontend.
* Handles the 'output' argument of fields.
* Usage instructions on https://github.com/reduxframework/kirki/wiki/output
*
* @package Kirki
* @category Core
* @author Aristeides Stathopoulos
* @copyright Copyright (c) 2015, Aristeides Stathopoulos
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Early exit if the class already exists
if ( class_exists( 'Kirki_Styles_Frontend' ) ) {
return;
}
class Kirki_Styles_Frontend {
public function __construct() {
$priority = ( isset( $config['styles_priority'] ) ) ? intval( $config['styles_priority'] ) : 150;
add_action( 'wp_enqueue_scripts', array( $this, 'frontend_styles' ), $priority );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ), $priority );
}
/**
* Add the inline styles
*/
public function enqueue_styles() {
$config = apply_filters( 'kirki/config', array() );
/**
* If we have set $config['disable_output'] to true,
* then do not proceed any further.
*/
if ( isset( $config['disable_output'] ) && true == $config['disable_output'] ) {
return;
}
wp_add_inline_style( 'kirki-styles', $this->loop_controls() );
}
/**
* Add a dummy, empty stylesheet.
*/
public function frontend_styles() {
$config = apply_filters( 'kirki/config', array() );
/**
* If we have set $config['disable_output'] to true,
* then do not proceed any further.
*/
if ( isset( $config['disable_output'] ) && true == $config['disable_output'] ) {
return;
}
wp_enqueue_style( 'kirki-styles', trailingslashit( kirki_url() ).'assets/css/kirki-styles.css', null, null );
}
/**
* loop through all fields and create an array of style definitions
*/
public function loop_controls() {
$fields = Kirki::$fields;
$css = array();
// Early exit if no fields are found.
if ( empty( $fields ) ) {
return;
}
foreach ( $fields as $field ) {
// Only continue if $field['output'] is set
if ( isset( $field['output'] ) && ! empty( $field['output'] ) && 'background' != $field['type'] ) {
$css = array_merge_recursive( $css, Kirki_Output::css(
Kirki_Field::sanitize_field( $field )
) );
}
}
if ( is_array( $css ) ) {
return Kirki_Output::styles_parse( Kirki_Output::add_prefixes( $css ) );
}
return;
}
}
| MartinDepero/dih | wp-content/themes/thewest/admin/kirki/includes/class-kirki-styles-frontend.php | PHP | gpl-2.0 | 2,477 |
/*
* QLogic QLA41xx NIC HBA Driver
* Copyright (c) 2003-2006 QLogic Corporation
*
* See LICENSE.qlge for copyright and licensing details.
*/
#ifndef _QLGE_H_
#define _QLGE_H_
#include <linux/pci.h>
#include <linux/netdevice.h>
/*
* General definitions...
*/
#define DRV_NAME "qlge"
#define DRV_STRING "QLogic 10 Gigabit PCI-E Ethernet Driver "
#define DRV_VERSION "v1.00.00-b3"
#define PFX "qlge: "
#define QPRINTK(qdev, nlevel, klevel, fmt, args...) \
do { \
if (!((qdev)->msg_enable & NETIF_MSG_##nlevel)) \
; \
else \
dev_printk(KERN_##klevel, &((qdev)->pdev->dev), \
"%s: " fmt, __func__, ##args); \
} while (0)
#define WQ_ADDR_ALIGN 0x3 /* 4 byte alignment */
#define QLGE_VENDOR_ID 0x1077
#define QLGE_DEVICE_ID_8012 0x8012
#define QLGE_DEVICE_ID_8000 0x8000
#define MAX_CPUS 8
#define MAX_TX_RINGS MAX_CPUS
#define MAX_RX_RINGS ((MAX_CPUS * 2) + 1)
#define NUM_TX_RING_ENTRIES 256
#define NUM_RX_RING_ENTRIES 256
#define NUM_SMALL_BUFFERS 512
#define NUM_LARGE_BUFFERS 512
#define DB_PAGE_SIZE 4096
/* Calculate the number of (4k) pages required to
* contain a buffer queue of the given length.
*/
#define MAX_DB_PAGES_PER_BQ(x) \
(((x * sizeof(u64)) / DB_PAGE_SIZE) + \
(((x * sizeof(u64)) % DB_PAGE_SIZE) ? 1 : 0))
#define RX_RING_SHADOW_SPACE (sizeof(u64) + \
MAX_DB_PAGES_PER_BQ(NUM_SMALL_BUFFERS) * sizeof(u64) + \
MAX_DB_PAGES_PER_BQ(NUM_LARGE_BUFFERS) * sizeof(u64))
#define SMALL_BUFFER_SIZE 256
#define LARGE_BUFFER_SIZE PAGE_SIZE
#define MAX_SPLIT_SIZE 1023
#define QLGE_SB_PAD 32
#define MAX_CQ 128
#define DFLT_COALESCE_WAIT 100 /* 100 usec wait for coalescing */
#define MAX_INTER_FRAME_WAIT 10 /* 10 usec max interframe-wait for coalescing */
#define DFLT_INTER_FRAME_WAIT (MAX_INTER_FRAME_WAIT/2)
#define UDELAY_COUNT 3
#define UDELAY_DELAY 100
#define TX_DESC_PER_IOCB 8
/* The maximum number of frags we handle is based
* on PAGE_SIZE...
*/
#if (PAGE_SHIFT == 12) || (PAGE_SHIFT == 13) /* 4k & 8k pages */
#define TX_DESC_PER_OAL ((MAX_SKB_FRAGS - TX_DESC_PER_IOCB) + 2)
#else /* all other page sizes */
#define TX_DESC_PER_OAL 0
#endif
/* MPI test register definitions. This register
* is used for determining alternate NIC function's
* PCI->func number.
*/
enum {
MPI_TEST_FUNC_PORT_CFG = 0x1002,
MPI_TEST_NIC1_FUNC_SHIFT = 1,
MPI_TEST_NIC2_FUNC_SHIFT = 5,
MPI_TEST_NIC_FUNC_MASK = 0x00000007,
};
/*
* Processor Address Register (PROC_ADDR) bit definitions.
*/
enum {
/* Misc. stuff */
MAILBOX_COUNT = 16,
PROC_ADDR_RDY = (1 << 31),
PROC_ADDR_R = (1 << 30),
PROC_ADDR_ERR = (1 << 29),
PROC_ADDR_DA = (1 << 28),
PROC_ADDR_FUNC0_MBI = 0x00001180,
PROC_ADDR_FUNC0_MBO = (PROC_ADDR_FUNC0_MBI + MAILBOX_COUNT),
PROC_ADDR_FUNC0_CTL = 0x000011a1,
PROC_ADDR_FUNC2_MBI = 0x00001280,
PROC_ADDR_FUNC2_MBO = (PROC_ADDR_FUNC2_MBI + MAILBOX_COUNT),
PROC_ADDR_FUNC2_CTL = 0x000012a1,
PROC_ADDR_MPI_RISC = 0x00000000,
PROC_ADDR_MDE = 0x00010000,
PROC_ADDR_REGBLOCK = 0x00020000,
PROC_ADDR_RISC_REG = 0x00030000,
};
/*
* System Register (SYS) bit definitions.
*/
enum {
SYS_EFE = (1 << 0),
SYS_FAE = (1 << 1),
SYS_MDC = (1 << 2),
SYS_DST = (1 << 3),
SYS_DWC = (1 << 4),
SYS_EVW = (1 << 5),
SYS_OMP_DLY_MASK = 0x3f000000,
/*
* There are no values defined as of edit #15.
*/
SYS_ODI = (1 << 14),
};
/*
* Reset/Failover Register (RST_FO) bit definitions.
*/
enum {
RST_FO_TFO = (1 << 0),
RST_FO_RR_MASK = 0x00060000,
RST_FO_RR_CQ_CAM = 0x00000000,
RST_FO_RR_DROP = 0x00000001,
RST_FO_RR_DQ = 0x00000002,
RST_FO_RR_RCV_FUNC_CQ = 0x00000003,
RST_FO_FRB = (1 << 12),
RST_FO_MOP = (1 << 13),
RST_FO_REG = (1 << 14),
RST_FO_FR = (1 << 15),
};
/*
* Function Specific Control Register (FSC) bit definitions.
*/
enum {
FSC_DBRST_MASK = 0x00070000,
FSC_DBRST_256 = 0x00000000,
FSC_DBRST_512 = 0x00000001,
FSC_DBRST_768 = 0x00000002,
FSC_DBRST_1024 = 0x00000003,
FSC_DBL_MASK = 0x00180000,
FSC_DBL_DBRST = 0x00000000,
FSC_DBL_MAX_PLD = 0x00000008,
FSC_DBL_MAX_BRST = 0x00000010,
FSC_DBL_128_BYTES = 0x00000018,
FSC_EC = (1 << 5),
FSC_EPC_MASK = 0x00c00000,
FSC_EPC_INBOUND = (1 << 6),
FSC_EPC_OUTBOUND = (1 << 7),
FSC_VM_PAGESIZE_MASK = 0x07000000,
FSC_VM_PAGE_2K = 0x00000100,
FSC_VM_PAGE_4K = 0x00000200,
FSC_VM_PAGE_8K = 0x00000300,
FSC_VM_PAGE_64K = 0x00000600,
FSC_SH = (1 << 11),
FSC_DSB = (1 << 12),
FSC_STE = (1 << 13),
FSC_FE = (1 << 15),
};
/*
* Host Command Status Register (CSR) bit definitions.
*/
enum {
CSR_ERR_STS_MASK = 0x0000003f,
/*
* There are no valued defined as of edit #15.
*/
CSR_RR = (1 << 8),
CSR_HRI = (1 << 9),
CSR_RP = (1 << 10),
CSR_CMD_PARM_SHIFT = 22,
CSR_CMD_NOP = 0x00000000,
CSR_CMD_SET_RST = 0x10000000,
CSR_CMD_CLR_RST = 0x20000000,
CSR_CMD_SET_PAUSE = 0x30000000,
CSR_CMD_CLR_PAUSE = 0x40000000,
CSR_CMD_SET_H2R_INT = 0x50000000,
CSR_CMD_CLR_H2R_INT = 0x60000000,
CSR_CMD_PAR_EN = 0x70000000,
CSR_CMD_SET_BAD_PAR = 0x80000000,
CSR_CMD_CLR_BAD_PAR = 0x90000000,
CSR_CMD_CLR_R2PCI_INT = 0xa0000000,
};
/*
* Configuration Register (CFG) bit definitions.
*/
enum {
CFG_LRQ = (1 << 0),
CFG_DRQ = (1 << 1),
CFG_LR = (1 << 2),
CFG_DR = (1 << 3),
CFG_LE = (1 << 5),
CFG_LCQ = (1 << 6),
CFG_DCQ = (1 << 7),
CFG_Q_SHIFT = 8,
CFG_Q_MASK = 0x7f000000,
};
/*
* Status Register (STS) bit definitions.
*/
enum {
STS_FE = (1 << 0),
STS_PI = (1 << 1),
STS_PL0 = (1 << 2),
STS_PL1 = (1 << 3),
STS_PI0 = (1 << 4),
STS_PI1 = (1 << 5),
STS_FUNC_ID_MASK = 0x000000c0,
STS_FUNC_ID_SHIFT = 6,
STS_F0E = (1 << 8),
STS_F1E = (1 << 9),
STS_F2E = (1 << 10),
STS_F3E = (1 << 11),
STS_NFE = (1 << 12),
};
/*
* Interrupt Enable Register (INTR_EN) bit definitions.
*/
enum {
INTR_EN_INTR_MASK = 0x007f0000,
INTR_EN_TYPE_MASK = 0x03000000,
INTR_EN_TYPE_ENABLE = 0x00000100,
INTR_EN_TYPE_DISABLE = 0x00000200,
INTR_EN_TYPE_READ = 0x00000300,
INTR_EN_IHD = (1 << 13),
INTR_EN_IHD_MASK = (INTR_EN_IHD << 16),
INTR_EN_EI = (1 << 14),
INTR_EN_EN = (1 << 15),
};
/*
* Interrupt Mask Register (INTR_MASK) bit definitions.
*/
enum {
INTR_MASK_PI = (1 << 0),
INTR_MASK_HL0 = (1 << 1),
INTR_MASK_LH0 = (1 << 2),
INTR_MASK_HL1 = (1 << 3),
INTR_MASK_LH1 = (1 << 4),
INTR_MASK_SE = (1 << 5),
INTR_MASK_LSC = (1 << 6),
INTR_MASK_MC = (1 << 7),
INTR_MASK_LINK_IRQS = INTR_MASK_LSC | INTR_MASK_SE | INTR_MASK_MC,
};
/*
* Register (REV_ID) bit definitions.
*/
enum {
REV_ID_MASK = 0x0000000f,
REV_ID_NICROLL_SHIFT = 0,
REV_ID_NICREV_SHIFT = 4,
REV_ID_XGROLL_SHIFT = 8,
REV_ID_XGREV_SHIFT = 12,
REV_ID_CHIPREV_SHIFT = 28,
};
/*
* Force ECC Error Register (FRC_ECC_ERR) bit definitions.
*/
enum {
FRC_ECC_ERR_VW = (1 << 12),
FRC_ECC_ERR_VB = (1 << 13),
FRC_ECC_ERR_NI = (1 << 14),
FRC_ECC_ERR_NO = (1 << 15),
FRC_ECC_PFE_SHIFT = 16,
FRC_ECC_ERR_DO = (1 << 18),
FRC_ECC_P14 = (1 << 19),
};
/*
* Error Status Register (ERR_STS) bit definitions.
*/
enum {
ERR_STS_NOF = (1 << 0),
ERR_STS_NIF = (1 << 1),
ERR_STS_DRP = (1 << 2),
ERR_STS_XGP = (1 << 3),
ERR_STS_FOU = (1 << 4),
ERR_STS_FOC = (1 << 5),
ERR_STS_FOF = (1 << 6),
ERR_STS_FIU = (1 << 7),
ERR_STS_FIC = (1 << 8),
ERR_STS_FIF = (1 << 9),
ERR_STS_MOF = (1 << 10),
ERR_STS_TA = (1 << 11),
ERR_STS_MA = (1 << 12),
ERR_STS_MPE = (1 << 13),
ERR_STS_SCE = (1 << 14),
ERR_STS_STE = (1 << 15),
ERR_STS_FOW = (1 << 16),
ERR_STS_UE = (1 << 17),
ERR_STS_MCH = (1 << 26),
ERR_STS_LOC_SHIFT = 27,
};
/*
* RAM Debug Address Register (RAM_DBG_ADDR) bit definitions.
*/
enum {
RAM_DBG_ADDR_FW = (1 << 30),
RAM_DBG_ADDR_FR = (1 << 31),
};
/*
* Semaphore Register (SEM) bit definitions.
*/
enum {
/*
* Example:
* reg = SEM_XGMAC0_MASK | (SEM_SET << SEM_XGMAC0_SHIFT)
*/
SEM_CLEAR = 0,
SEM_SET = 1,
SEM_FORCE = 3,
SEM_XGMAC0_SHIFT = 0,
SEM_XGMAC1_SHIFT = 2,
SEM_ICB_SHIFT = 4,
SEM_MAC_ADDR_SHIFT = 6,
SEM_FLASH_SHIFT = 8,
SEM_PROBE_SHIFT = 10,
SEM_RT_IDX_SHIFT = 12,
SEM_PROC_REG_SHIFT = 14,
SEM_XGMAC0_MASK = 0x00030000,
SEM_XGMAC1_MASK = 0x000c0000,
SEM_ICB_MASK = 0x00300000,
SEM_MAC_ADDR_MASK = 0x00c00000,
SEM_FLASH_MASK = 0x03000000,
SEM_PROBE_MASK = 0x0c000000,
SEM_RT_IDX_MASK = 0x30000000,
SEM_PROC_REG_MASK = 0xc0000000,
};
/*
* 10G MAC Address Register (XGMAC_ADDR) bit definitions.
*/
enum {
XGMAC_ADDR_RDY = (1 << 31),
XGMAC_ADDR_R = (1 << 30),
XGMAC_ADDR_XME = (1 << 29),
/* XGMAC control registers */
PAUSE_SRC_LO = 0x00000100,
PAUSE_SRC_HI = 0x00000104,
GLOBAL_CFG = 0x00000108,
GLOBAL_CFG_RESET = (1 << 0),
GLOBAL_CFG_JUMBO = (1 << 6),
GLOBAL_CFG_TX_STAT_EN = (1 << 10),
GLOBAL_CFG_RX_STAT_EN = (1 << 11),
TX_CFG = 0x0000010c,
TX_CFG_RESET = (1 << 0),
TX_CFG_EN = (1 << 1),
TX_CFG_PREAM = (1 << 2),
RX_CFG = 0x00000110,
RX_CFG_RESET = (1 << 0),
RX_CFG_EN = (1 << 1),
RX_CFG_PREAM = (1 << 2),
FLOW_CTL = 0x0000011c,
PAUSE_OPCODE = 0x00000120,
PAUSE_TIMER = 0x00000124,
PAUSE_FRM_DEST_LO = 0x00000128,
PAUSE_FRM_DEST_HI = 0x0000012c,
MAC_TX_PARAMS = 0x00000134,
MAC_TX_PARAMS_JUMBO = (1 << 31),
MAC_TX_PARAMS_SIZE_SHIFT = 16,
MAC_RX_PARAMS = 0x00000138,
MAC_SYS_INT = 0x00000144,
MAC_SYS_INT_MASK = 0x00000148,
MAC_MGMT_INT = 0x0000014c,
MAC_MGMT_IN_MASK = 0x00000150,
EXT_ARB_MODE = 0x000001fc,
/* XGMAC TX statistics registers */
TX_PKTS = 0x00000200,
TX_BYTES = 0x00000208,
TX_MCAST_PKTS = 0x00000210,
TX_BCAST_PKTS = 0x00000218,
TX_UCAST_PKTS = 0x00000220,
TX_CTL_PKTS = 0x00000228,
TX_PAUSE_PKTS = 0x00000230,
TX_64_PKT = 0x00000238,
TX_65_TO_127_PKT = 0x00000240,
TX_128_TO_255_PKT = 0x00000248,
TX_256_511_PKT = 0x00000250,
TX_512_TO_1023_PKT = 0x00000258,
TX_1024_TO_1518_PKT = 0x00000260,
TX_1519_TO_MAX_PKT = 0x00000268,
TX_UNDERSIZE_PKT = 0x00000270,
TX_OVERSIZE_PKT = 0x00000278,
/* XGMAC statistics control registers */
RX_HALF_FULL_DET = 0x000002a0,
TX_HALF_FULL_DET = 0x000002a4,
RX_OVERFLOW_DET = 0x000002a8,
TX_OVERFLOW_DET = 0x000002ac,
RX_HALF_FULL_MASK = 0x000002b0,
TX_HALF_FULL_MASK = 0x000002b4,
RX_OVERFLOW_MASK = 0x000002b8,
TX_OVERFLOW_MASK = 0x000002bc,
STAT_CNT_CTL = 0x000002c0,
STAT_CNT_CTL_CLEAR_TX = (1 << 0),
STAT_CNT_CTL_CLEAR_RX = (1 << 1),
AUX_RX_HALF_FULL_DET = 0x000002d0,
AUX_TX_HALF_FULL_DET = 0x000002d4,
AUX_RX_OVERFLOW_DET = 0x000002d8,
AUX_TX_OVERFLOW_DET = 0x000002dc,
AUX_RX_HALF_FULL_MASK = 0x000002f0,
AUX_TX_HALF_FULL_MASK = 0x000002f4,
AUX_RX_OVERFLOW_MASK = 0x000002f8,
AUX_TX_OVERFLOW_MASK = 0x000002fc,
/* XGMAC RX statistics registers */
RX_BYTES = 0x00000300,
RX_BYTES_OK = 0x00000308,
RX_PKTS = 0x00000310,
RX_PKTS_OK = 0x00000318,
RX_BCAST_PKTS = 0x00000320,
RX_MCAST_PKTS = 0x00000328,
RX_UCAST_PKTS = 0x00000330,
RX_UNDERSIZE_PKTS = 0x00000338,
RX_OVERSIZE_PKTS = 0x00000340,
RX_JABBER_PKTS = 0x00000348,
RX_UNDERSIZE_FCERR_PKTS = 0x00000350,
RX_DROP_EVENTS = 0x00000358,
RX_FCERR_PKTS = 0x00000360,
RX_ALIGN_ERR = 0x00000368,
RX_SYMBOL_ERR = 0x00000370,
RX_MAC_ERR = 0x00000378,
RX_CTL_PKTS = 0x00000380,
RX_PAUSE_PKTS = 0x00000388,
RX_64_PKTS = 0x00000390,
RX_65_TO_127_PKTS = 0x00000398,
RX_128_255_PKTS = 0x000003a0,
RX_256_511_PKTS = 0x000003a8,
RX_512_TO_1023_PKTS = 0x000003b0,
RX_1024_TO_1518_PKTS = 0x000003b8,
RX_1519_TO_MAX_PKTS = 0x000003c0,
RX_LEN_ERR_PKTS = 0x000003c8,
/* XGMAC MDIO control registers */
MDIO_TX_DATA = 0x00000400,
MDIO_RX_DATA = 0x00000410,
MDIO_CMD = 0x00000420,
MDIO_PHY_ADDR = 0x00000430,
MDIO_PORT = 0x00000440,
MDIO_STATUS = 0x00000450,
/* XGMAC AUX statistics registers */
};
/*
* Enhanced Transmission Schedule Registers (NIC_ETS,CNA_ETS) bit definitions.
*/
enum {
ETS_QUEUE_SHIFT = 29,
ETS_REF = (1 << 26),
ETS_RS = (1 << 27),
ETS_P = (1 << 28),
ETS_FC_COS_SHIFT = 23,
};
/*
* Flash Address Register (FLASH_ADDR) bit definitions.
*/
enum {
FLASH_ADDR_RDY = (1 << 31),
FLASH_ADDR_R = (1 << 30),
FLASH_ADDR_ERR = (1 << 29),
};
/*
* Stop CQ Processing Register (CQ_STOP) bit definitions.
*/
enum {
CQ_STOP_QUEUE_MASK = (0x007f0000),
CQ_STOP_TYPE_MASK = (0x03000000),
CQ_STOP_TYPE_START = 0x00000100,
CQ_STOP_TYPE_STOP = 0x00000200,
CQ_STOP_TYPE_READ = 0x00000300,
CQ_STOP_EN = (1 << 15),
};
/*
* MAC Protocol Address Index Register (MAC_ADDR_IDX) bit definitions.
*/
enum {
MAC_ADDR_IDX_SHIFT = 4,
MAC_ADDR_TYPE_SHIFT = 16,
MAC_ADDR_TYPE_MASK = 0x000f0000,
MAC_ADDR_TYPE_CAM_MAC = 0x00000000,
MAC_ADDR_TYPE_MULTI_MAC = 0x00010000,
MAC_ADDR_TYPE_VLAN = 0x00020000,
MAC_ADDR_TYPE_MULTI_FLTR = 0x00030000,
MAC_ADDR_TYPE_FC_MAC = 0x00040000,
MAC_ADDR_TYPE_MGMT_MAC = 0x00050000,
MAC_ADDR_TYPE_MGMT_VLAN = 0x00060000,
MAC_ADDR_TYPE_MGMT_V4 = 0x00070000,
MAC_ADDR_TYPE_MGMT_V6 = 0x00080000,
MAC_ADDR_TYPE_MGMT_TU_DP = 0x00090000,
MAC_ADDR_ADR = (1 << 25),
MAC_ADDR_RS = (1 << 26),
MAC_ADDR_E = (1 << 27),
MAC_ADDR_MR = (1 << 30),
MAC_ADDR_MW = (1 << 31),
MAX_MULTICAST_ENTRIES = 32,
};
/*
* MAC Protocol Address Index Register (SPLT_HDR) bit definitions.
*/
enum {
SPLT_HDR_EP = (1 << 31),
};
/*
* FCoE Receive Configuration Register (FC_RCV_CFG) bit definitions.
*/
enum {
FC_RCV_CFG_ECT = (1 << 15),
FC_RCV_CFG_DFH = (1 << 20),
FC_RCV_CFG_DVF = (1 << 21),
FC_RCV_CFG_RCE = (1 << 27),
FC_RCV_CFG_RFE = (1 << 28),
FC_RCV_CFG_TEE = (1 << 29),
FC_RCV_CFG_TCE = (1 << 30),
FC_RCV_CFG_TFE = (1 << 31),
};
/*
* NIC Receive Configuration Register (NIC_RCV_CFG) bit definitions.
*/
enum {
NIC_RCV_CFG_PPE = (1 << 0),
NIC_RCV_CFG_VLAN_MASK = 0x00060000,
NIC_RCV_CFG_VLAN_ALL = 0x00000000,
NIC_RCV_CFG_VLAN_MATCH_ONLY = 0x00000002,
NIC_RCV_CFG_VLAN_MATCH_AND_NON = 0x00000004,
NIC_RCV_CFG_VLAN_NONE_AND_NON = 0x00000006,
NIC_RCV_CFG_RV = (1 << 3),
NIC_RCV_CFG_DFQ_MASK = (0x7f000000),
NIC_RCV_CFG_DFQ_SHIFT = 8,
NIC_RCV_CFG_DFQ = 0, /* HARDCODE default queue to 0. */
};
/*
* Mgmt Receive Configuration Register (MGMT_RCV_CFG) bit definitions.
*/
enum {
MGMT_RCV_CFG_ARP = (1 << 0),
MGMT_RCV_CFG_DHC = (1 << 1),
MGMT_RCV_CFG_DHS = (1 << 2),
MGMT_RCV_CFG_NP = (1 << 3),
MGMT_RCV_CFG_I6N = (1 << 4),
MGMT_RCV_CFG_I6R = (1 << 5),
MGMT_RCV_CFG_DH6 = (1 << 6),
MGMT_RCV_CFG_UD1 = (1 << 7),
MGMT_RCV_CFG_UD0 = (1 << 8),
MGMT_RCV_CFG_BCT = (1 << 9),
MGMT_RCV_CFG_MCT = (1 << 10),
MGMT_RCV_CFG_DM = (1 << 11),
MGMT_RCV_CFG_RM = (1 << 12),
MGMT_RCV_CFG_STL = (1 << 13),
MGMT_RCV_CFG_VLAN_MASK = 0xc0000000,
MGMT_RCV_CFG_VLAN_ALL = 0x00000000,
MGMT_RCV_CFG_VLAN_MATCH_ONLY = 0x00004000,
MGMT_RCV_CFG_VLAN_MATCH_AND_NON = 0x00008000,
MGMT_RCV_CFG_VLAN_NONE_AND_NON = 0x0000c000,
};
/*
* Routing Index Register (RT_IDX) bit definitions.
*/
enum {
RT_IDX_IDX_SHIFT = 8,
RT_IDX_TYPE_MASK = 0x000f0000,
RT_IDX_TYPE_RT = 0x00000000,
RT_IDX_TYPE_RT_INV = 0x00010000,
RT_IDX_TYPE_NICQ = 0x00020000,
RT_IDX_TYPE_NICQ_INV = 0x00030000,
RT_IDX_DST_MASK = 0x00700000,
RT_IDX_DST_RSS = 0x00000000,
RT_IDX_DST_CAM_Q = 0x00100000,
RT_IDX_DST_COS_Q = 0x00200000,
RT_IDX_DST_DFLT_Q = 0x00300000,
RT_IDX_DST_DEST_Q = 0x00400000,
RT_IDX_RS = (1 << 26),
RT_IDX_E = (1 << 27),
RT_IDX_MR = (1 << 30),
RT_IDX_MW = (1 << 31),
/* Nic Queue format - type 2 bits */
RT_IDX_BCAST = (1 << 0),
RT_IDX_MCAST = (1 << 1),
RT_IDX_MCAST_MATCH = (1 << 2),
RT_IDX_MCAST_REG_MATCH = (1 << 3),
RT_IDX_MCAST_HASH_MATCH = (1 << 4),
RT_IDX_FC_MACH = (1 << 5),
RT_IDX_ETH_FCOE = (1 << 6),
RT_IDX_CAM_HIT = (1 << 7),
RT_IDX_CAM_BIT0 = (1 << 8),
RT_IDX_CAM_BIT1 = (1 << 9),
RT_IDX_VLAN_TAG = (1 << 10),
RT_IDX_VLAN_MATCH = (1 << 11),
RT_IDX_VLAN_FILTER = (1 << 12),
RT_IDX_ETH_SKIP1 = (1 << 13),
RT_IDX_ETH_SKIP2 = (1 << 14),
RT_IDX_BCAST_MCAST_MATCH = (1 << 15),
RT_IDX_802_3 = (1 << 16),
RT_IDX_LLDP = (1 << 17),
RT_IDX_UNUSED018 = (1 << 18),
RT_IDX_UNUSED019 = (1 << 19),
RT_IDX_UNUSED20 = (1 << 20),
RT_IDX_UNUSED21 = (1 << 21),
RT_IDX_ERR = (1 << 22),
RT_IDX_VALID = (1 << 23),
RT_IDX_TU_CSUM_ERR = (1 << 24),
RT_IDX_IP_CSUM_ERR = (1 << 25),
RT_IDX_MAC_ERR = (1 << 26),
RT_IDX_RSS_TCP6 = (1 << 27),
RT_IDX_RSS_TCP4 = (1 << 28),
RT_IDX_RSS_IPV6 = (1 << 29),
RT_IDX_RSS_IPV4 = (1 << 30),
RT_IDX_RSS_MATCH = (1 << 31),
/* Hierarchy for the NIC Queue Mask */
RT_IDX_ALL_ERR_SLOT = 0,
RT_IDX_MAC_ERR_SLOT = 0,
RT_IDX_IP_CSUM_ERR_SLOT = 1,
RT_IDX_TCP_UDP_CSUM_ERR_SLOT = 2,
RT_IDX_BCAST_SLOT = 3,
RT_IDX_MCAST_MATCH_SLOT = 4,
RT_IDX_ALLMULTI_SLOT = 5,
RT_IDX_UNUSED6_SLOT = 6,
RT_IDX_UNUSED7_SLOT = 7,
RT_IDX_RSS_MATCH_SLOT = 8,
RT_IDX_RSS_IPV4_SLOT = 8,
RT_IDX_RSS_IPV6_SLOT = 9,
RT_IDX_RSS_TCP4_SLOT = 10,
RT_IDX_RSS_TCP6_SLOT = 11,
RT_IDX_CAM_HIT_SLOT = 12,
RT_IDX_UNUSED013 = 13,
RT_IDX_UNUSED014 = 14,
RT_IDX_PROMISCUOUS_SLOT = 15,
RT_IDX_MAX_SLOTS = 16,
};
/*
* Control Register Set Map
*/
enum {
PROC_ADDR = 0, /* Use semaphore */
PROC_DATA = 0x04, /* Use semaphore */
SYS = 0x08,
RST_FO = 0x0c,
FSC = 0x10,
CSR = 0x14,
LED = 0x18,
ICB_RID = 0x1c, /* Use semaphore */
ICB_L = 0x20, /* Use semaphore */
ICB_H = 0x24, /* Use semaphore */
CFG = 0x28,
BIOS_ADDR = 0x2c,
STS = 0x30,
INTR_EN = 0x34,
INTR_MASK = 0x38,
ISR1 = 0x3c,
ISR2 = 0x40,
ISR3 = 0x44,
ISR4 = 0x48,
REV_ID = 0x4c,
FRC_ECC_ERR = 0x50,
ERR_STS = 0x54,
RAM_DBG_ADDR = 0x58,
RAM_DBG_DATA = 0x5c,
ECC_ERR_CNT = 0x60,
SEM = 0x64,
GPIO_1 = 0x68, /* Use semaphore */
GPIO_2 = 0x6c, /* Use semaphore */
GPIO_3 = 0x70, /* Use semaphore */
RSVD2 = 0x74,
XGMAC_ADDR = 0x78, /* Use semaphore */
XGMAC_DATA = 0x7c, /* Use semaphore */
NIC_ETS = 0x80,
CNA_ETS = 0x84,
FLASH_ADDR = 0x88, /* Use semaphore */
FLASH_DATA = 0x8c, /* Use semaphore */
CQ_STOP = 0x90,
PAGE_TBL_RID = 0x94,
WQ_PAGE_TBL_LO = 0x98,
WQ_PAGE_TBL_HI = 0x9c,
CQ_PAGE_TBL_LO = 0xa0,
CQ_PAGE_TBL_HI = 0xa4,
MAC_ADDR_IDX = 0xa8, /* Use semaphore */
MAC_ADDR_DATA = 0xac, /* Use semaphore */
COS_DFLT_CQ1 = 0xb0,
COS_DFLT_CQ2 = 0xb4,
ETYPE_SKIP1 = 0xb8,
ETYPE_SKIP2 = 0xbc,
SPLT_HDR = 0xc0,
FC_PAUSE_THRES = 0xc4,
NIC_PAUSE_THRES = 0xc8,
FC_ETHERTYPE = 0xcc,
FC_RCV_CFG = 0xd0,
NIC_RCV_CFG = 0xd4,
FC_COS_TAGS = 0xd8,
NIC_COS_TAGS = 0xdc,
MGMT_RCV_CFG = 0xe0,
RT_IDX = 0xe4,
RT_DATA = 0xe8,
RSVD7 = 0xec,
XG_SERDES_ADDR = 0xf0,
XG_SERDES_DATA = 0xf4,
PRB_MX_ADDR = 0xf8, /* Use semaphore */
PRB_MX_DATA = 0xfc, /* Use semaphore */
};
/*
* CAM output format.
*/
enum {
CAM_OUT_ROUTE_FC = 0,
CAM_OUT_ROUTE_NIC = 1,
CAM_OUT_FUNC_SHIFT = 2,
CAM_OUT_RV = (1 << 4),
CAM_OUT_SH = (1 << 15),
CAM_OUT_CQ_ID_SHIFT = 5,
};
/*
* Mailbox definitions
*/
enum {
/* Asynchronous Event Notifications */
AEN_SYS_ERR = 0x00008002,
AEN_LINK_UP = 0x00008011,
AEN_LINK_DOWN = 0x00008012,
AEN_IDC_CMPLT = 0x00008100,
AEN_IDC_REQ = 0x00008101,
AEN_IDC_EXT = 0x00008102,
AEN_DCBX_CHG = 0x00008110,
AEN_AEN_LOST = 0x00008120,
AEN_AEN_SFP_IN = 0x00008130,
AEN_AEN_SFP_OUT = 0x00008131,
AEN_FW_INIT_DONE = 0x00008400,
AEN_FW_INIT_FAIL = 0x00008401,
/* Mailbox Command Opcodes. */
MB_CMD_NOP = 0x00000000,
MB_CMD_EX_FW = 0x00000002,
MB_CMD_MB_TEST = 0x00000006,
MB_CMD_CSUM_TEST = 0x00000007, /* Verify Checksum */
MB_CMD_ABOUT_FW = 0x00000008,
MB_CMD_COPY_RISC_RAM = 0x0000000a,
MB_CMD_LOAD_RISC_RAM = 0x0000000b,
MB_CMD_DUMP_RISC_RAM = 0x0000000c,
MB_CMD_WRITE_RAM = 0x0000000d,
MB_CMD_INIT_RISC_RAM = 0x0000000e,
MB_CMD_READ_RAM = 0x0000000f,
MB_CMD_STOP_FW = 0x00000014,
MB_CMD_MAKE_SYS_ERR = 0x0000002a,
MB_CMD_WRITE_SFP = 0x00000030,
MB_CMD_READ_SFP = 0x00000031,
MB_CMD_INIT_FW = 0x00000060,
MB_CMD_GET_IFCB = 0x00000061,
MB_CMD_GET_FW_STATE = 0x00000069,
MB_CMD_IDC_REQ = 0x00000100, /* Inter-Driver Communication */
MB_CMD_IDC_ACK = 0x00000101, /* Inter-Driver Communication */
MB_CMD_SET_WOL_MODE = 0x00000110, /* Wake On Lan */
MB_WOL_DISABLE = 0,
MB_WOL_MAGIC_PKT = (1 << 1),
MB_WOL_FLTR = (1 << 2),
MB_WOL_UCAST = (1 << 3),
MB_WOL_MCAST = (1 << 4),
MB_WOL_BCAST = (1 << 5),
MB_WOL_LINK_UP = (1 << 6),
MB_WOL_LINK_DOWN = (1 << 7),
MB_CMD_SET_WOL_FLTR = 0x00000111, /* Wake On Lan Filter */
MB_CMD_CLEAR_WOL_FLTR = 0x00000112, /* Wake On Lan Filter */
MB_CMD_SET_WOL_MAGIC = 0x00000113, /* Wake On Lan Magic Packet */
MB_CMD_CLEAR_WOL_MAGIC = 0x00000114,/* Wake On Lan Magic Packet */
MB_CMD_SET_WOL_IMMED = 0x00000115,
MB_CMD_PORT_RESET = 0x00000120,
MB_CMD_SET_PORT_CFG = 0x00000122,
MB_CMD_GET_PORT_CFG = 0x00000123,
MB_CMD_GET_LINK_STS = 0x00000124,
/* Mailbox Command Status. */
MB_CMD_STS_GOOD = 0x00004000, /* Success. */
MB_CMD_STS_INTRMDT = 0x00001000, /* Intermediate Complete. */
MB_CMD_STS_INVLD_CMD = 0x00004001, /* Invalid. */
MB_CMD_STS_XFC_ERR = 0x00004002, /* Interface Error. */
MB_CMD_STS_CSUM_ERR = 0x00004003, /* Csum Error. */
MB_CMD_STS_ERR = 0x00004005, /* System Error. */
MB_CMD_STS_PARAM_ERR = 0x00004006, /* Parameter Error. */
};
struct mbox_params {
u32 mbox_in[MAILBOX_COUNT];
u32 mbox_out[MAILBOX_COUNT];
int in_count;
int out_count;
};
struct flash_params_8012 {
u8 dev_id_str[4];
__le16 size;
__le16 csum;
__le16 ver;
__le16 sub_dev_id;
u8 mac_addr[6];
__le16 res;
};
/* 8000 device's flash is a different structure
* at a different offset in flash.
*/
#define FUNC0_FLASH_OFFSET 0x140200
#define FUNC1_FLASH_OFFSET 0x140600
/* Flash related data structures. */
struct flash_params_8000 {
u8 dev_id_str[4]; /* "8000" */
__le16 ver;
__le16 size;
__le16 csum;
__le16 reserved0;
__le16 total_size;
__le16 entry_count;
u8 data_type0;
u8 data_size0;
u8 mac_addr[6];
u8 data_type1;
u8 data_size1;
u8 mac_addr1[6];
u8 data_type2;
u8 data_size2;
__le16 vlan_id;
u8 data_type3;
u8 data_size3;
__le16 last;
u8 reserved1[464];
__le16 subsys_ven_id;
__le16 subsys_dev_id;
u8 reserved2[4];
};
union flash_params {
struct flash_params_8012 flash_params_8012;
struct flash_params_8000 flash_params_8000;
};
/*
* doorbell space for the rx ring context
*/
struct rx_doorbell_context {
u32 cnsmr_idx; /* 0x00 */
u32 valid; /* 0x04 */
u32 reserved[4]; /* 0x08-0x14 */
u32 lbq_prod_idx; /* 0x18 */
u32 sbq_prod_idx; /* 0x1c */
};
/*
* doorbell space for the tx ring context
*/
struct tx_doorbell_context {
u32 prod_idx; /* 0x00 */
u32 valid; /* 0x04 */
u32 reserved[4]; /* 0x08-0x14 */
u32 lbq_prod_idx; /* 0x18 */
u32 sbq_prod_idx; /* 0x1c */
};
/* DATA STRUCTURES SHARED WITH HARDWARE. */
struct tx_buf_desc {
__le64 addr;
__le32 len;
#define TX_DESC_LEN_MASK 0x000fffff
#define TX_DESC_C 0x40000000
#define TX_DESC_E 0x80000000
} __attribute((packed));
/*
* IOCB Definitions...
*/
#define OPCODE_OB_MAC_IOCB 0x01
#define OPCODE_OB_MAC_TSO_IOCB 0x02
#define OPCODE_IB_MAC_IOCB 0x20
#define OPCODE_IB_MPI_IOCB 0x21
#define OPCODE_IB_AE_IOCB 0x3f
struct ob_mac_iocb_req {
u8 opcode;
u8 flags1;
#define OB_MAC_IOCB_REQ_OI 0x01
#define OB_MAC_IOCB_REQ_I 0x02
#define OB_MAC_IOCB_REQ_D 0x08
#define OB_MAC_IOCB_REQ_F 0x10
u8 flags2;
u8 flags3;
#define OB_MAC_IOCB_DFP 0x02
#define OB_MAC_IOCB_V 0x04
__le32 reserved1[2];
__le16 frame_len;
#define OB_MAC_IOCB_LEN_MASK 0x3ffff
__le16 reserved2;
u32 tid;
u32 txq_idx;
__le32 reserved3;
__le16 vlan_tci;
__le16 reserved4;
struct tx_buf_desc tbd[TX_DESC_PER_IOCB];
} __attribute((packed));
struct ob_mac_iocb_rsp {
u8 opcode; /* */
u8 flags1; /* */
#define OB_MAC_IOCB_RSP_OI 0x01 /* */
#define OB_MAC_IOCB_RSP_I 0x02 /* */
#define OB_MAC_IOCB_RSP_E 0x08 /* */
#define OB_MAC_IOCB_RSP_S 0x10 /* too Short */
#define OB_MAC_IOCB_RSP_L 0x20 /* too Large */
#define OB_MAC_IOCB_RSP_P 0x40 /* Padded */
u8 flags2; /* */
u8 flags3; /* */
#define OB_MAC_IOCB_RSP_B 0x80 /* */
u32 tid;
u32 txq_idx;
__le32 reserved[13];
} __attribute((packed));
struct ob_mac_tso_iocb_req {
u8 opcode;
u8 flags1;
#define OB_MAC_TSO_IOCB_OI 0x01
#define OB_MAC_TSO_IOCB_I 0x02
#define OB_MAC_TSO_IOCB_D 0x08
#define OB_MAC_TSO_IOCB_IP4 0x40
#define OB_MAC_TSO_IOCB_IP6 0x80
u8 flags2;
#define OB_MAC_TSO_IOCB_LSO 0x20
#define OB_MAC_TSO_IOCB_UC 0x40
#define OB_MAC_TSO_IOCB_TC 0x80
u8 flags3;
#define OB_MAC_TSO_IOCB_IC 0x01
#define OB_MAC_TSO_IOCB_DFP 0x02
#define OB_MAC_TSO_IOCB_V 0x04
__le32 reserved1[2];
__le32 frame_len;
u32 tid;
u32 txq_idx;
__le16 total_hdrs_len;
__le16 net_trans_offset;
#define OB_MAC_TRANSPORT_HDR_SHIFT 6
__le16 vlan_tci;
__le16 mss;
struct tx_buf_desc tbd[TX_DESC_PER_IOCB];
} __attribute((packed));
struct ob_mac_tso_iocb_rsp {
u8 opcode;
u8 flags1;
#define OB_MAC_TSO_IOCB_RSP_OI 0x01
#define OB_MAC_TSO_IOCB_RSP_I 0x02
#define OB_MAC_TSO_IOCB_RSP_E 0x08
#define OB_MAC_TSO_IOCB_RSP_S 0x10
#define OB_MAC_TSO_IOCB_RSP_L 0x20
#define OB_MAC_TSO_IOCB_RSP_P 0x40
u8 flags2; /* */
u8 flags3; /* */
#define OB_MAC_TSO_IOCB_RSP_B 0x8000
u32 tid;
u32 txq_idx;
__le32 reserved2[13];
} __attribute((packed));
struct ib_mac_iocb_rsp {
u8 opcode; /* 0x20 */
u8 flags1;
#define IB_MAC_IOCB_RSP_OI 0x01 /* Overide intr delay */
#define IB_MAC_IOCB_RSP_I 0x02 /* Disble Intr Generation */
#define IB_MAC_CSUM_ERR_MASK 0x1c /* A mask to use for csum errs */
#define IB_MAC_IOCB_RSP_TE 0x04 /* Checksum error */
#define IB_MAC_IOCB_RSP_NU 0x08 /* No checksum rcvd */
#define IB_MAC_IOCB_RSP_IE 0x10 /* IPv4 checksum error */
#define IB_MAC_IOCB_RSP_M_MASK 0x60 /* Multicast info */
#define IB_MAC_IOCB_RSP_M_NONE 0x00 /* Not mcast frame */
#define IB_MAC_IOCB_RSP_M_HASH 0x20 /* HASH mcast frame */
#define IB_MAC_IOCB_RSP_M_REG 0x40 /* Registered mcast frame */
#define IB_MAC_IOCB_RSP_M_PROM 0x60 /* Promiscuous mcast frame */
#define IB_MAC_IOCB_RSP_B 0x80 /* Broadcast frame */
u8 flags2;
#define IB_MAC_IOCB_RSP_P 0x01 /* Promiscuous frame */
#define IB_MAC_IOCB_RSP_V 0x02 /* Vlan tag present */
#define IB_MAC_IOCB_RSP_ERR_MASK 0x1c /* */
#define IB_MAC_IOCB_RSP_ERR_CODE_ERR 0x04
#define IB_MAC_IOCB_RSP_ERR_OVERSIZE 0x08
#define IB_MAC_IOCB_RSP_ERR_UNDERSIZE 0x10
#define IB_MAC_IOCB_RSP_ERR_PREAMBLE 0x14
#define IB_MAC_IOCB_RSP_ERR_FRAME_LEN 0x18
#define IB_MAC_IOCB_RSP_ERR_CRC 0x1c
#define IB_MAC_IOCB_RSP_U 0x20 /* UDP packet */
#define IB_MAC_IOCB_RSP_T 0x40 /* TCP packet */
#define IB_MAC_IOCB_RSP_FO 0x80 /* Failover port */
u8 flags3;
#define IB_MAC_IOCB_RSP_RSS_MASK 0x07 /* RSS mask */
#define IB_MAC_IOCB_RSP_M_NONE 0x00 /* No RSS match */
#define IB_MAC_IOCB_RSP_M_IPV4 0x04 /* IPv4 RSS match */
#define IB_MAC_IOCB_RSP_M_IPV6 0x02 /* IPv6 RSS match */
#define IB_MAC_IOCB_RSP_M_TCP_V4 0x05 /* TCP with IPv4 */
#define IB_MAC_IOCB_RSP_M_TCP_V6 0x03 /* TCP with IPv6 */
#define IB_MAC_IOCB_RSP_V4 0x08 /* IPV4 */
#define IB_MAC_IOCB_RSP_V6 0x10 /* IPV6 */
#define IB_MAC_IOCB_RSP_IH 0x20 /* Split after IP header */
#define IB_MAC_IOCB_RSP_DS 0x40 /* data is in small buffer */
#define IB_MAC_IOCB_RSP_DL 0x80 /* data is in large buffer */
__le32 data_len; /* */
__le64 data_addr; /* */
__le32 rss; /* */
__le16 vlan_id; /* 12 bits */
#define IB_MAC_IOCB_RSP_C 0x1000 /* VLAN CFI bit */
#define IB_MAC_IOCB_RSP_COS_SHIFT 12 /* class of service value */
#define IB_MAC_IOCB_RSP_VLAN_MASK 0x0ffff
__le16 reserved1;
__le32 reserved2[6];
u8 reserved3[3];
u8 flags4;
#define IB_MAC_IOCB_RSP_HV 0x20
#define IB_MAC_IOCB_RSP_HS 0x40
#define IB_MAC_IOCB_RSP_HL 0x80
__le32 hdr_len; /* */
__le64 hdr_addr; /* */
} __attribute((packed));
struct ib_ae_iocb_rsp {
u8 opcode;
u8 flags1;
#define IB_AE_IOCB_RSP_OI 0x01
#define IB_AE_IOCB_RSP_I 0x02
u8 event;
#define LINK_UP_EVENT 0x00
#define LINK_DOWN_EVENT 0x01
#define CAM_LOOKUP_ERR_EVENT 0x06
#define SOFT_ECC_ERROR_EVENT 0x07
#define MGMT_ERR_EVENT 0x08
#define TEN_GIG_MAC_EVENT 0x09
#define GPI0_H2L_EVENT 0x10
#define GPI0_L2H_EVENT 0x20
#define GPI1_H2L_EVENT 0x11
#define GPI1_L2H_EVENT 0x21
#define PCI_ERR_ANON_BUF_RD 0x40
u8 q_id;
__le32 reserved[15];
} __attribute((packed));
/*
* These three structures are for generic
* handling of ib and ob iocbs.
*/
struct ql_net_rsp_iocb {
u8 opcode;
u8 flags0;
__le16 length;
__le32 tid;
__le32 reserved[14];
} __attribute((packed));
struct net_req_iocb {
u8 opcode;
u8 flags0;
__le16 flags1;
__le32 tid;
__le32 reserved1[30];
} __attribute((packed));
/*
* tx ring initialization control block for chip.
* It is defined as:
* "Work Queue Initialization Control Block"
*/
struct wqicb {
__le16 len;
#define Q_LEN_V (1 << 4)
#define Q_LEN_CPP_CONT 0x0000
#define Q_LEN_CPP_16 0x0001
#define Q_LEN_CPP_32 0x0002
#define Q_LEN_CPP_64 0x0003
#define Q_LEN_CPP_512 0x0006
__le16 flags;
#define Q_PRI_SHIFT 1
#define Q_FLAGS_LC 0x1000
#define Q_FLAGS_LB 0x2000
#define Q_FLAGS_LI 0x4000
#define Q_FLAGS_LO 0x8000
__le16 cq_id_rss;
#define Q_CQ_ID_RSS_RV 0x8000
__le16 rid;
__le64 addr;
__le64 cnsmr_idx_addr;
} __attribute((packed));
/*
* rx ring initialization control block for chip.
* It is defined as:
* "Completion Queue Initialization Control Block"
*/
struct cqicb {
u8 msix_vect;
u8 reserved1;
u8 reserved2;
u8 flags;
#define FLAGS_LV 0x08
#define FLAGS_LS 0x10
#define FLAGS_LL 0x20
#define FLAGS_LI 0x40
#define FLAGS_LC 0x80
__le16 len;
#define LEN_V (1 << 4)
#define LEN_CPP_CONT 0x0000
#define LEN_CPP_32 0x0001
#define LEN_CPP_64 0x0002
#define LEN_CPP_128 0x0003
__le16 rid;
__le64 addr;
__le64 prod_idx_addr;
__le16 pkt_delay;
__le16 irq_delay;
__le64 lbq_addr;
__le16 lbq_buf_size;
__le16 lbq_len; /* entry count */
__le64 sbq_addr;
__le16 sbq_buf_size;
__le16 sbq_len; /* entry count */
} __attribute((packed));
struct ricb {
u8 base_cq;
#define RSS_L4K 0x80
u8 flags;
#define RSS_L6K 0x01
#define RSS_LI 0x02
#define RSS_LB 0x04
#define RSS_LM 0x08
#define RSS_RI4 0x10
#define RSS_RT4 0x20
#define RSS_RI6 0x40
#define RSS_RT6 0x80
__le16 mask;
__le32 hash_cq_id[256];
__le32 ipv6_hash_key[10];
__le32 ipv4_hash_key[4];
} __attribute((packed));
/* SOFTWARE/DRIVER DATA STRUCTURES. */
struct oal {
struct tx_buf_desc oal[TX_DESC_PER_OAL];
};
struct map_list {
DECLARE_PCI_UNMAP_ADDR(mapaddr);
DECLARE_PCI_UNMAP_LEN(maplen);
};
struct tx_ring_desc {
struct sk_buff *skb;
struct ob_mac_iocb_req *queue_entry;
u32 index;
struct oal oal;
struct map_list map[MAX_SKB_FRAGS + 1];
int map_cnt;
struct tx_ring_desc *next;
};
struct bq_desc {
union {
struct page *lbq_page;
struct sk_buff *skb;
} p;
__le64 *addr;
u32 index;
DECLARE_PCI_UNMAP_ADDR(mapaddr);
DECLARE_PCI_UNMAP_LEN(maplen);
};
#define QL_TXQ_IDX(qdev, skb) (smp_processor_id()%(qdev->tx_ring_count))
struct tx_ring {
/*
* queue info.
*/
struct wqicb wqicb; /* structure used to inform chip of new queue */
void *wq_base; /* pci_alloc:virtual addr for tx */
dma_addr_t wq_base_dma; /* pci_alloc:dma addr for tx */
__le32 *cnsmr_idx_sh_reg; /* shadow copy of consumer idx */
dma_addr_t cnsmr_idx_sh_reg_dma; /* dma-shadow copy of consumer */
u32 wq_size; /* size in bytes of queue area */
u32 wq_len; /* number of entries in queue */
void __iomem *prod_idx_db_reg; /* doorbell area index reg at offset 0x00 */
void __iomem *valid_db_reg; /* doorbell area valid reg at offset 0x04 */
u16 prod_idx; /* current value for prod idx */
u16 cq_id; /* completion (rx) queue for tx completions */
u8 wq_id; /* queue id for this entry */
u8 reserved1[3];
struct tx_ring_desc *q; /* descriptor list for the queue */
spinlock_t lock;
atomic_t tx_count; /* counts down for every outstanding IO */
atomic_t queue_stopped; /* Turns queue off when full. */
struct delayed_work tx_work;
struct ql_adapter *qdev;
};
/*
* Type of inbound queue.
*/
enum {
DEFAULT_Q = 2, /* Handles slow queue and chip/MPI events. */
TX_Q = 3, /* Handles outbound completions. */
RX_Q = 4, /* Handles inbound completions. */
};
struct rx_ring {
struct cqicb cqicb; /* The chip's completion queue init control block. */
/* Completion queue elements. */
void *cq_base;
dma_addr_t cq_base_dma;
u32 cq_size;
u32 cq_len;
u16 cq_id;
__le32 *prod_idx_sh_reg; /* Shadowed producer register. */
dma_addr_t prod_idx_sh_reg_dma;
void __iomem *cnsmr_idx_db_reg; /* PCI doorbell mem area + 0 */
u32 cnsmr_idx; /* current sw idx */
struct ql_net_rsp_iocb *curr_entry; /* next entry on queue */
void __iomem *valid_db_reg; /* PCI doorbell mem area + 0x04 */
/* Large buffer queue elements. */
u32 lbq_len; /* entry count */
u32 lbq_size; /* size in bytes of queue */
u32 lbq_buf_size;
void *lbq_base;
dma_addr_t lbq_base_dma;
void *lbq_base_indirect;
dma_addr_t lbq_base_indirect_dma;
struct bq_desc *lbq; /* array of control blocks */
void __iomem *lbq_prod_idx_db_reg; /* PCI doorbell mem area + 0x18 */
u32 lbq_prod_idx; /* current sw prod idx */
u32 lbq_curr_idx; /* next entry we expect */
u32 lbq_clean_idx; /* beginning of new descs */
u32 lbq_free_cnt; /* free buffer desc cnt */
/* Small buffer queue elements. */
u32 sbq_len; /* entry count */
u32 sbq_size; /* size in bytes of queue */
u32 sbq_buf_size;
void *sbq_base;
dma_addr_t sbq_base_dma;
void *sbq_base_indirect;
dma_addr_t sbq_base_indirect_dma;
struct bq_desc *sbq; /* array of control blocks */
void __iomem *sbq_prod_idx_db_reg; /* PCI doorbell mem area + 0x1c */
u32 sbq_prod_idx; /* current sw prod idx */
u32 sbq_curr_idx; /* next entry we expect */
u32 sbq_clean_idx; /* beginning of new descs */
u32 sbq_free_cnt; /* free buffer desc cnt */
/* Misc. handler elements. */
u32 type; /* Type of queue, tx, rx, or default. */
u32 irq; /* Which vector this ring is assigned. */
u32 cpu; /* Which CPU this should run on. */
char name[IFNAMSIZ + 5];
struct napi_struct napi;
struct delayed_work rx_work;
u8 reserved;
struct ql_adapter *qdev;
};
/*
* RSS Initialization Control Block
*/
struct hash_id {
u8 value[4];
};
struct nic_stats {
/*
* These stats come from offset 200h to 278h
* in the XGMAC register.
*/
u64 tx_pkts;
u64 tx_bytes;
u64 tx_mcast_pkts;
u64 tx_bcast_pkts;
u64 tx_ucast_pkts;
u64 tx_ctl_pkts;
u64 tx_pause_pkts;
u64 tx_64_pkt;
u64 tx_65_to_127_pkt;
u64 tx_128_to_255_pkt;
u64 tx_256_511_pkt;
u64 tx_512_to_1023_pkt;
u64 tx_1024_to_1518_pkt;
u64 tx_1519_to_max_pkt;
u64 tx_undersize_pkt;
u64 tx_oversize_pkt;
/*
* These stats come from offset 300h to 3C8h
* in the XGMAC register.
*/
u64 rx_bytes;
u64 rx_bytes_ok;
u64 rx_pkts;
u64 rx_pkts_ok;
u64 rx_bcast_pkts;
u64 rx_mcast_pkts;
u64 rx_ucast_pkts;
u64 rx_undersize_pkts;
u64 rx_oversize_pkts;
u64 rx_jabber_pkts;
u64 rx_undersize_fcerr_pkts;
u64 rx_drop_events;
u64 rx_fcerr_pkts;
u64 rx_align_err;
u64 rx_symbol_err;
u64 rx_mac_err;
u64 rx_ctl_pkts;
u64 rx_pause_pkts;
u64 rx_64_pkts;
u64 rx_65_to_127_pkts;
u64 rx_128_255_pkts;
u64 rx_256_511_pkts;
u64 rx_512_to_1023_pkts;
u64 rx_1024_to_1518_pkts;
u64 rx_1519_to_max_pkts;
u64 rx_len_err_pkts;
};
/*
* intr_context structure is used during initialization
* to hook the interrupts. It is also used in a single
* irq environment as a context to the ISR.
*/
struct intr_context {
struct ql_adapter *qdev;
u32 intr;
u32 hooked;
u32 intr_en_mask; /* value/mask used to enable this intr */
u32 intr_dis_mask; /* value/mask used to disable this intr */
u32 intr_read_mask; /* value/mask used to read this intr */
char name[IFNAMSIZ * 2];
atomic_t irq_cnt; /* irq_cnt is used in single vector
* environment. It's incremented for each
* irq handler that is scheduled. When each
* handler finishes it decrements irq_cnt and
* enables interrupts if it's zero. */
irq_handler_t handler;
};
/* adapter flags definitions. */
enum {
QL_ADAPTER_UP = (1 << 0), /* Adapter has been brought up. */
QL_LEGACY_ENABLED = (1 << 3),
QL_MSI_ENABLED = (1 << 3),
QL_MSIX_ENABLED = (1 << 4),
QL_DMA64 = (1 << 5),
QL_PROMISCUOUS = (1 << 6),
QL_ALLMULTI = (1 << 7),
QL_PORT_CFG = (1 << 8),
QL_CAM_RT_SET = (1 << 9),
};
/* link_status bit definitions */
enum {
STS_LOOPBACK_MASK = 0x00000700,
STS_LOOPBACK_PCS = 0x00000100,
STS_LOOPBACK_HSS = 0x00000200,
STS_LOOPBACK_EXT = 0x00000300,
STS_PAUSE_MASK = 0x000000c0,
STS_PAUSE_STD = 0x00000040,
STS_PAUSE_PRI = 0x00000080,
STS_SPEED_MASK = 0x00000038,
STS_SPEED_100Mb = 0x00000000,
STS_SPEED_1Gb = 0x00000008,
STS_SPEED_10Gb = 0x00000010,
STS_LINK_TYPE_MASK = 0x00000007,
STS_LINK_TYPE_XFI = 0x00000001,
STS_LINK_TYPE_XAUI = 0x00000002,
STS_LINK_TYPE_XFI_BP = 0x00000003,
STS_LINK_TYPE_XAUI_BP = 0x00000004,
STS_LINK_TYPE_10GBASET = 0x00000005,
};
/* link_config bit definitions */
enum {
CFG_JUMBO_FRAME_SIZE = 0x00010000,
CFG_PAUSE_MASK = 0x00000060,
CFG_PAUSE_STD = 0x00000020,
CFG_PAUSE_PRI = 0x00000040,
CFG_DCBX = 0x00000010,
CFG_LOOPBACK_MASK = 0x00000007,
CFG_LOOPBACK_PCS = 0x00000002,
CFG_LOOPBACK_HSS = 0x00000004,
CFG_LOOPBACK_EXT = 0x00000006,
CFG_DEFAULT_MAX_FRAME_SIZE = 0x00002580,
};
struct nic_operations {
int (*get_flash) (struct ql_adapter *);
int (*port_initialize) (struct ql_adapter *);
};
/*
* The main Adapter structure definition.
* This structure has all fields relevant to the hardware.
*/
struct ql_adapter {
struct ricb ricb;
unsigned long flags;
u32 wol;
struct nic_stats nic_stats;
struct vlan_group *vlgrp;
/* PCI Configuration information for this device */
struct pci_dev *pdev;
struct net_device *ndev; /* Parent NET device */
/* Hardware information */
u32 chip_rev_id;
u32 fw_rev_id;
u32 func; /* PCI function for this adapter */
u32 alt_func; /* PCI function for alternate adapter */
u32 port; /* Port number this adapter */
spinlock_t adapter_lock;
spinlock_t hw_lock;
spinlock_t stats_lock;
/* PCI Bus Relative Register Addresses */
void __iomem *reg_base;
void __iomem *doorbell_area;
u32 doorbell_area_size;
u32 msg_enable;
/* Page for Shadow Registers */
void *rx_ring_shadow_reg_area;
dma_addr_t rx_ring_shadow_reg_dma;
void *tx_ring_shadow_reg_area;
dma_addr_t tx_ring_shadow_reg_dma;
u32 mailbox_in;
u32 mailbox_out;
struct mbox_params idc_mbc;
struct mutex mpi_mutex;
int tx_ring_size;
int rx_ring_size;
u32 intr_count;
struct msix_entry *msi_x_entry;
struct intr_context intr_context[MAX_RX_RINGS];
int tx_ring_count; /* One per online CPU. */
u32 rss_ring_first_cq_id;/* index of first inbound (rss) rx_ring */
u32 rss_ring_count; /* One per online CPU. */
/*
* rx_ring_count =
* one default queue +
* (CPU count * outbound completion rx_ring) +
* (CPU count * inbound (RSS) completion rx_ring)
*/
int rx_ring_count;
int ring_mem_size;
void *ring_mem;
struct rx_ring rx_ring[MAX_RX_RINGS];
struct tx_ring tx_ring[MAX_TX_RINGS];
int rx_csum;
u32 default_rx_queue;
u16 rx_coalesce_usecs; /* cqicb->int_delay */
u16 rx_max_coalesced_frames; /* cqicb->pkt_int_delay */
u16 tx_coalesce_usecs; /* cqicb->int_delay */
u16 tx_max_coalesced_frames; /* cqicb->pkt_int_delay */
u32 xg_sem_mask;
u32 port_link_up;
u32 port_init;
u32 link_status;
u32 link_config;
u32 max_frame_size;
union flash_params flash;
struct net_device_stats stats;
struct workqueue_struct *q_workqueue;
struct workqueue_struct *workqueue;
struct delayed_work asic_reset_work;
struct delayed_work mpi_reset_work;
struct delayed_work mpi_work;
struct delayed_work mpi_port_cfg_work;
struct delayed_work mpi_idc_work;
struct completion ide_completion;
struct nic_operations *nic_ops;
u16 device_id;
};
/*
* Typical Register accessor for memory mapped device.
*/
static inline u32 ql_read32(const struct ql_adapter *qdev, int reg)
{
return readl(qdev->reg_base + reg);
}
/*
* Typical Register accessor for memory mapped device.
*/
static inline void ql_write32(const struct ql_adapter *qdev, int reg, u32 val)
{
writel(val, qdev->reg_base + reg);
}
/*
* Doorbell Registers:
* Doorbell registers are virtual registers in the PCI memory space.
* The space is allocated by the chip during PCI initialization. The
* device driver finds the doorbell address in BAR 3 in PCI config space.
* The registers are used to control outbound and inbound queues. For
* example, the producer index for an outbound queue. Each queue uses
* 1 4k chunk of memory. The lower half of the space is for outbound
* queues. The upper half is for inbound queues.
*/
static inline void ql_write_db_reg(u32 val, void __iomem *addr)
{
writel(val, addr);
mmiowb();
}
/*
* Shadow Registers:
* Outbound queues have a consumer index that is maintained by the chip.
* Inbound queues have a producer index that is maintained by the chip.
* For lower overhead, these registers are "shadowed" to host memory
* which allows the device driver to track the queue progress without
* PCI reads. When an entry is placed on an inbound queue, the chip will
* update the relevant index register and then copy the value to the
* shadow register in host memory.
*/
static inline u32 ql_read_sh_reg(__le32 *addr)
{
u32 reg;
reg = le32_to_cpu(*addr);
rmb();
return reg;
}
extern char qlge_driver_name[];
extern const char qlge_driver_version[];
extern const struct ethtool_ops qlge_ethtool_ops;
extern int ql_sem_spinlock(struct ql_adapter *qdev, u32 sem_mask);
extern void ql_sem_unlock(struct ql_adapter *qdev, u32 sem_mask);
extern int ql_read_xgmac_reg(struct ql_adapter *qdev, u32 reg, u32 *data);
extern int ql_get_mac_addr_reg(struct ql_adapter *qdev, u32 type, u16 index,
u32 *value);
extern int ql_get_routing_reg(struct ql_adapter *qdev, u32 index, u32 *value);
extern int ql_write_cfg(struct ql_adapter *qdev, void *ptr, int size, u32 bit,
u16 q_id);
void ql_queue_fw_error(struct ql_adapter *qdev);
void ql_mpi_work(struct work_struct *work);
void ql_mpi_reset_work(struct work_struct *work);
int ql_wait_reg_rdy(struct ql_adapter *qdev, u32 reg, u32 bit, u32 ebit);
void ql_queue_asic_error(struct ql_adapter *qdev);
u32 ql_enable_completion_interrupt(struct ql_adapter *qdev, u32 intr);
void ql_set_ethtool_ops(struct net_device *ndev);
int ql_read_xgmac_reg64(struct ql_adapter *qdev, u32 reg, u64 *data);
void ql_mpi_idc_work(struct work_struct *work);
void ql_mpi_port_cfg_work(struct work_struct *work);
int ql_mb_get_fw_state(struct ql_adapter *qdev);
int ql_cam_route_initialize(struct ql_adapter *qdev);
int ql_read_mpi_reg(struct ql_adapter *qdev, u32 reg, u32 *data);
int ql_mb_about_fw(struct ql_adapter *qdev);
void ql_link_on(struct ql_adapter *qdev);
void ql_link_off(struct ql_adapter *qdev);
#if 1
#define QL_ALL_DUMP
#define QL_REG_DUMP
#define QL_DEV_DUMP
#define QL_CB_DUMP
/* #define QL_IB_DUMP */
/* #define QL_OB_DUMP */
#endif
#ifdef QL_REG_DUMP
extern void ql_dump_xgmac_control_regs(struct ql_adapter *qdev);
extern void ql_dump_routing_entries(struct ql_adapter *qdev);
extern void ql_dump_regs(struct ql_adapter *qdev);
#define QL_DUMP_REGS(qdev) ql_dump_regs(qdev)
#define QL_DUMP_ROUTE(qdev) ql_dump_routing_entries(qdev)
#define QL_DUMP_XGMAC_CONTROL_REGS(qdev) ql_dump_xgmac_control_regs(qdev)
#else
#define QL_DUMP_REGS(qdev)
#define QL_DUMP_ROUTE(qdev)
#define QL_DUMP_XGMAC_CONTROL_REGS(qdev)
#endif
#ifdef QL_STAT_DUMP
extern void ql_dump_stat(struct ql_adapter *qdev);
#define QL_DUMP_STAT(qdev) ql_dump_stat(qdev)
#else
#define QL_DUMP_STAT(qdev)
#endif
#ifdef QL_DEV_DUMP
extern void ql_dump_qdev(struct ql_adapter *qdev);
#define QL_DUMP_QDEV(qdev) ql_dump_qdev(qdev)
#else
#define QL_DUMP_QDEV(qdev)
#endif
#ifdef QL_CB_DUMP
extern void ql_dump_wqicb(struct wqicb *wqicb);
extern void ql_dump_tx_ring(struct tx_ring *tx_ring);
extern void ql_dump_ricb(struct ricb *ricb);
extern void ql_dump_cqicb(struct cqicb *cqicb);
extern void ql_dump_rx_ring(struct rx_ring *rx_ring);
extern void ql_dump_hw_cb(struct ql_adapter *qdev, int size, u32 bit, u16 q_id);
#define QL_DUMP_RICB(ricb) ql_dump_ricb(ricb)
#define QL_DUMP_WQICB(wqicb) ql_dump_wqicb(wqicb)
#define QL_DUMP_TX_RING(tx_ring) ql_dump_tx_ring(tx_ring)
#define QL_DUMP_CQICB(cqicb) ql_dump_cqicb(cqicb)
#define QL_DUMP_RX_RING(rx_ring) ql_dump_rx_ring(rx_ring)
#define QL_DUMP_HW_CB(qdev, size, bit, q_id) \
ql_dump_hw_cb(qdev, size, bit, q_id)
#else
#define QL_DUMP_RICB(ricb)
#define QL_DUMP_WQICB(wqicb)
#define QL_DUMP_TX_RING(tx_ring)
#define QL_DUMP_CQICB(cqicb)
#define QL_DUMP_RX_RING(rx_ring)
#define QL_DUMP_HW_CB(qdev, size, bit, q_id)
#endif
#ifdef QL_OB_DUMP
extern void ql_dump_tx_desc(struct tx_buf_desc *tbd);
extern void ql_dump_ob_mac_iocb(struct ob_mac_iocb_req *ob_mac_iocb);
extern void ql_dump_ob_mac_rsp(struct ob_mac_iocb_rsp *ob_mac_rsp);
#define QL_DUMP_OB_MAC_IOCB(ob_mac_iocb) ql_dump_ob_mac_iocb(ob_mac_iocb)
#define QL_DUMP_OB_MAC_RSP(ob_mac_rsp) ql_dump_ob_mac_rsp(ob_mac_rsp)
#else
#define QL_DUMP_OB_MAC_IOCB(ob_mac_iocb)
#define QL_DUMP_OB_MAC_RSP(ob_mac_rsp)
#endif
#ifdef QL_IB_DUMP
extern void ql_dump_ib_mac_rsp(struct ib_mac_iocb_rsp *ib_mac_rsp);
#define QL_DUMP_IB_MAC_RSP(ib_mac_rsp) ql_dump_ib_mac_rsp(ib_mac_rsp)
#else
#define QL_DUMP_IB_MAC_RSP(ib_mac_rsp)
#endif
#ifdef QL_ALL_DUMP
extern void ql_dump_all(struct ql_adapter *qdev);
#define QL_DUMP_ALL(qdev) ql_dump_all(qdev)
#else
#define QL_DUMP_ALL(qdev)
#endif
#endif /* _QLGE_H_ */
| stevelord/PR30 | linux-2.6.31/drivers/net/qlge/qlge.h | C | gpl-2.0 | 44,752 |
include ../../Makefile.include
include FFMPEG-VERSION
DEPS= ../../Makefile.include FFMPEG-VERSION Makefile
# set to "yes" to enable patching
# we don't apply patches until we move to a vanilla ffmpeg tarball
APPLY_PATCHES=no
# configuration settings
ffmpg_config = --prefix=$(PREFIX) --extra-version="kodi-$(VERSION)"
ffmpg_config += --cc=$(CC) --cxx=$(CXX) --ar=$(AR) --ranlib=$(RANLIB)
ffmpg_config += --disable-devices --disable-doc
ffmpg_config += --disable-ffplay --disable-ffmpeg --disable-sdl
ffmpg_config += --disable-ffprobe --disable-ffserver
ffmpg_config += --enable-gpl --enable-runtime-cpudetect
ffmpg_config += --enable-postproc --enable-pthreads
ffmpg_config += --enable-muxer=spdif --enable-muxer=adts
ffmpg_config += --enable-muxer=asf --enable-muxer=ipod
ffmpg_config += --enable-encoder=ac3 --enable-encoder=aac
ffmpg_config += --enable-encoder=wmav2 --enable-protocol=http
ffmpg_config += --enable-gnutls
ffmpg_config += --enable-encoder=png --enable-encoder=mjpeg
ifeq ($(CROSS_COMPILING), yes)
ffmpg_config += --arch=$(CPU) --enable-cross-compile
endif
ifeq ($(OS), linux)
ffmpg_config += --target-os=$(OS) --cpu=$(CPU)
ffmpg_config += --enable-vdpau --enable-vaapi --enable-pic
endif
ifeq ($(OS), android)
ifeq ($(findstring arm64, $(CPU)), arm64)
ffmpg_config += --arch=aarch64 --cpu=cortex-a53
else
ifeq ($(findstring arm, $(CPU)), arm)
ffmpg_config += --cpu=cortex-a9
else
ffmpg_config += --cpu=i686 --disable-mmx
endif
endif
ffmpg_config += --target-os=linux --extra-libs=-liconv
endif
ifeq ($(OS), ios)
ifneq ($(CPU), arm64)
ffmpg_config += --cpu=cortex-a8
endif
ffmpg_config += --yasmexe=$(NATIVEPREFIX)/bin/yasm
ffmpg_config += --disable-decoder=mpeg_xvmc --disable-vda --disable-crystalhd --enable-videotoolbox
ffmpg_config += --target-os=darwin
endif
ifeq ($(OS), osx)
ffmpg_config += --disable-outdev=sdl
ffmpg_config += --disable-decoder=mpeg_xvmc --disable-vda --disable-crystalhd --enable-videotoolbox
ffmpg_config += --target-os=darwin
ffmpg_config += --disable-securetransport
endif
ifeq ($(findstring arm, $(CPU)), arm)
ffmpg_config += --enable-pic --disable-armv5te --disable-armv6t2
endif
ifeq ($(findstring mips, $(CPU)), mips)
ffmpg_config += --disable-mips32r2 --disable-mipsdspr1 --disable-mipsdspr2
endif
ifeq ($(Configuration), Release)
ffmpg_config += --disable-debug
endif
CLEAN_FILES=$(ARCHIVE) $(PLATFORM)
all: .installed-$(PLATFORM)
$(TARBALLS_LOCATION)/$(ARCHIVE):
cd $(TARBALLS_LOCATION); $(RETRIEVE_TOOL) -Ls --create-dirs -f -o $(TARBALLS_LOCATION)/$(ARCHIVE) $(BASE_URL)/$(VERSION).tar.gz
$(PLATFORM): $(TARBALLS_LOCATION)/$(ARCHIVE) $(DEPS)
rm -rf $(PLATFORM); mkdir -p $(PLATFORM)
cd $(PLATFORM); $(ARCHIVE_TOOL) $(ARCHIVE_TOOL_FLAGS) $(TARBALLS_LOCATION)/$(ARCHIVE)
cd $(PLATFORM); sed -i".bak" -e "s%pkg_config_default=pkg-config%export PKG_CONFIG_LIBDIR=$(PREFIX)/lib/pkgconfig \&\& pkg_config_default=$(NATIVEPREFIX)/bin/pkg-config%" configure
cd $(PLATFORM);\
CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" CPPFLAGS="$(CPPFLAGS)" LDFLAGS="$(LDFLAGS)" \
./configure $(ffmpg_config)
build: $(PLATFORM)
$(MAKE) -C $(PLATFORM)
.installed-$(PLATFORM): build
$(MAKE) -C $(PLATFORM) install
touch $@
clean:
$(MAKE) -C $(PLATFORM) clean
rm -f .installed-$(PLATFORM)
distclean::
rm -rf $(PLATFORM) .installed-$(PLATFORM)
| EmbER-Dev/Kodi | tools/depends/target/ffmpeg/Makefile | Makefile | gpl-2.0 | 3,366 |
/*
Samba Unix/Linux SMB client library
net share commands
Copyright (C) 2002 Andrew Tridgell ([email protected])
Copyright (C) 2008 Kai Blin ([email protected])
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, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "utils/net.h"
int net_share_usage(struct net_context *c, int argc, const char **argv)
{
d_printf(_(
"\nnet [<method>] share [misc. options] [targets] \n"
"\tenumerates all exported resources (network shares) "
"on target server\n\n"
"net [<method>] share ADD <name=serverpath> [misc. options] [targets]"
"\n\tadds a share from a server (makes the export active)\n\n"
"net [<method>] share DELETE <sharename> [misc. options] [targets]"
"\n\tdeletes a share from a server (makes the export inactive)\n\n"
"net [<method>] share ALLOWEDUSERS [<filename>] "
"[misc. options] [targets]"
"\n\tshows a list of all shares together with all users allowed to"
"\n\taccess them. This needs the output of 'net usersidlist' on"
"\n\tstdin or in <filename>.\n\n"
"net [<method>] share MIGRATE FILES <sharename> [misc. options] [targets]"
"\n\tMigrates files from remote to local server\n\n"
"net [<method>] share MIGRATE SHARES <sharename> [misc. options] [targets]"
"\n\tMigrates shares from remote to local server\n\n"
"net [<method>] share MIGRATE SECURITY <sharename> [misc. options] [targets]"
"\n\tMigrates share-ACLs from remote to local server\n\n"
"net [<method>] share MIGRATE ALL <sharename> [misc. options] [targets]"
"\n\tMigrates shares (including directories, files) from remote\n"
"\tto local server\n\n"
));
net_common_methods_usage(c, argc, argv);
net_common_flags_usage(c, argc, argv);
d_printf(_(
"\t-C or --comment=<comment>\tdescriptive comment (for add only)\n"
"\t-M or --maxusers=<num>\t\tmax users allowed for share\n"
"\t --acls\t\t\tcopies ACLs as well\n"
"\t --attrs\t\t\tcopies DOS Attributes as well\n"
"\t --timestamps\t\tpreserve timestamps while copying files\n"
"\t --destination\t\tmigration target server (default: localhost)\n"
"\t-e or --exclude\t\t\tlist of shares to be excluded from mirroring\n"
"\t-v or --verbose\t\t\tgive verbose output\n"));
return -1;
}
int net_share(struct net_context *c, int argc, const char **argv)
{
if (argc > 0 && StrCaseCmp(argv[0], "HELP") == 0) {
net_share_usage(c, argc, argv);
return 0;
}
if (net_rpc_check(c, 0))
return net_rpc_share(c, argc, argv);
return net_rap_share(c, argc, argv);
}
| hajuuk/asuswrt | release/src/router/samba-3.5.8/source3/utils/net_share.c | C | gpl-2.0 | 3,093 |
/*
* admCtrlWpa.c
*
* Copyright(c) 1998 - 2010 Texas Instruments. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Texas Instruments nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file admCtrl.c
* \brief Admission control API implimentation
*
* \see admCtrl.h
*/
/****************************************************************************
* *
* MODULE: Admission Control *
* PURPOSE: Admission Control Module API *
* *
****************************************************************************/
#define __FILE_ID__ FILE_ID_19
#include "osApi.h"
#include "paramOut.h"
#include "mlmeApi.h"
#include "802_11Defs.h"
#include "DataCtrl_Api.h"
#include "report.h"
#include "rsn.h"
#include "admCtrl.h"
#include "admCtrlWpa.h"
#include "admCtrlWpa2.h"
#ifdef XCC_MODULE_INCLUDED
#include "admCtrlXCC.h"
#include "XCCMngr.h"
#endif
#include "siteMgrApi.h"
#include "TWDriver.h"
/* Constants */
#define MAX_NETWORK_MODE 2
#define MAX_WPA_CIPHER_SUITE 7
/* Enumerations */
/* Typedefs */
/* Structures */
/* External data definitions */
/* Local functions definitions */
/* Global variables */
static TI_UINT8 wpaIeOuiIe[3] = { 0x00, 0x50, 0xf2};
static TI_BOOL broadcastCipherSuiteValidity[MAX_NETWORK_MODE][MAX_WPA_CIPHER_SUITE]=
{
/* RSN_IBSS */ {
/* NONE */ TI_FALSE,
/* WEP40 */ TI_FALSE,
/* TKIP */ TI_TRUE,
/* AES_WRAP */ TI_TRUE,
/* AES_CCMP */ TI_TRUE,
/* WEP104 */ TI_FALSE,
/* CKIP */ TI_FALSE},
/* RSN_INFRASTRUCTURE */ {
/* NONE */ TI_FALSE,
/* WEP */ TI_TRUE,
/* TKIP */ TI_TRUE,
/* AES_WRAP */ TI_TRUE,
/* AES_CCMP */ TI_TRUE,
/* WEP104 */ TI_TRUE,
/* CKIP */ TI_TRUE}
};
/** WPA admission table. Used to verify admission parameters to an AP */
/* table parameters:
Max unicast cipher in the IE
Max broadcast cipher in the IE
Encryption status
*/
typedef struct
{
TI_STATUS status;
ECipherSuite unicast;
ECipherSuite broadcast;
TI_UINT8 evaluation;
} admCtrlWpa_validity_t;
static admCtrlWpa_validity_t admCtrlWpa_validityTable[MAX_WPA_CIPHER_SUITE][MAX_WPA_CIPHER_SUITE][MAX_WPA_CIPHER_SUITE] =
{
/* AP unicast NONE */ {
/* AP multicast NONE */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP40 */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP40 */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP40 */ { TI_OK, TWD_CIPHER_NONE, TWD_CIPHER_WEP ,1},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_OK, TWD_CIPHER_NONE, TWD_CIPHER_WEP104 ,1}},
/* AP multicast TKIP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_OK, TWD_CIPHER_NONE, TWD_CIPHER_TKIP ,2},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WRAP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_OK, TWD_CIPHER_NONE, TWD_CIPHER_AES_WRAP ,3},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast CCMP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_OK, TWD_CIPHER_NONE, TWD_CIPHER_AES_CCMP ,3},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP104 */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP40 */ { TI_OK, TWD_CIPHER_NONE, TWD_CIPHER_WEP ,1},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_OK, TWD_CIPHER_NONE, TWD_CIPHER_WEP104 ,1}}},
/* AP unicast WEP */ {
/* AP multicast NONE */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_OK, TWD_CIPHER_WEP, TWD_CIPHER_WEP ,1},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_OK, TWD_CIPHER_WEP, TWD_CIPHER_WEP ,1},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast TKIP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WRAP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WRAP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast CCMP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP104 */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}}},
/* AP unicast TKIP */ {
/* AP multicast NONE */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_OK, TWD_CIPHER_TKIP, TWD_CIPHER_WEP ,4},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast TKIP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_OK, TWD_CIPHER_TKIP, TWD_CIPHER_TKIP ,7},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WRAP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast CCMP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP104 */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_OK, TWD_CIPHER_TKIP, TWD_CIPHER_WEP104 ,4},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}}},
/* AP unicast AES_WRAP */ {
/* AP multicast NONE */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP40 */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_OK, TWD_CIPHER_AES_WRAP, TWD_CIPHER_WEP ,5},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast TKIP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_OK, TWD_CIPHER_AES_WRAP, TWD_CIPHER_TKIP ,6},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WRAP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_OK, TWD_CIPHER_AES_WRAP, TWD_CIPHER_AES_WRAP ,8},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast CCMP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP104 */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_OK, TWD_CIPHER_AES_WRAP, TWD_CIPHER_WEP104 ,5},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}}},
/* AP unicast AES_CCMP */ {
/* AP multicast NONE */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_OK, TWD_CIPHER_AES_CCMP, TWD_CIPHER_WEP ,5},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast TKIP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_OK, TWD_CIPHER_AES_CCMP, TWD_CIPHER_TKIP ,6},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WRAP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast CCMP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_OK, TWD_CIPHER_AES_CCMP, TWD_CIPHER_AES_CCMP ,7},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_OK, TWD_CIPHER_AES_CCMP, TWD_CIPHER_WEP104 ,5},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}}},
/* AP unicast WEP104 */ {
/* AP multicast NONE */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast TKIP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WRAP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast CCMP */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP104 */{ TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0}},
/* AP multicast WEP104 */ {
/* STA NONE */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA WEP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA TKIP */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA AES */ { TI_NOK, TWD_CIPHER_NONE, TWD_CIPHER_NONE ,0},
/* STA CCMP */ { TI_OK, TWD_CIPHER_WEP104, TWD_CIPHER_WEP104 ,1},
/* STA WEP104 */{ TI_OK, TWD_CIPHER_WEP104, TWD_CIPHER_WEP104 ,1}}}
};
/* Function prototypes */
TI_STATUS admCtrlWpa_parseIe(admCtrl_t *pAdmCtrl, TI_UINT8 *pWpaIe, wpaIeData_t *pWpaData);
TI_UINT16 admCtrlWpa_buildCapabilities(TI_UINT16 replayCnt);
TI_UINT32 admCtrlWpa_parseSuiteVal(admCtrl_t *pAdmCtrl, TI_UINT8* suiteVal,wpaIeData_t *pWpaData,TI_UINT32 maxVal);
TI_STATUS admCtrlWpa_checkCipherSuiteValidity (ECipherSuite unicastSuite, ECipherSuite broadcastSuite, ECipherSuite encryptionStatus);
static TI_STATUS admCtrlWpa_get802_1x_AkmExists (admCtrl_t *pAdmCtrl, TI_BOOL *wpa_802_1x_AkmExists);
/**
*
* admCtrlWpa_config - Configure XCC admission control.
*
* \b Description:
*
* Configure XCC admission control.
*
* \b ARGS:
*
* I - pAdmCtrl - context \n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK on failure.
*
* \sa
*/
TI_STATUS admCtrlWpa_config(admCtrl_t *pAdmCtrl)
{
TI_STATUS status;
TRsnPaeConfig paeConfig;
/* check and set admission control default parameters */
pAdmCtrl->authSuite = RSN_AUTH_OPEN;
if (pAdmCtrl->unicastSuite == TWD_CIPHER_NONE)
{
pAdmCtrl->unicastSuite = TWD_CIPHER_TKIP;
}
if (pAdmCtrl->broadcastSuite == TWD_CIPHER_NONE)
{
pAdmCtrl->broadcastSuite = TWD_CIPHER_TKIP;
}
/* set callback functions (API) */
pAdmCtrl->getInfoElement = admCtrlWpa_getInfoElement;
pAdmCtrl->setSite = admCtrlWpa_setSite;
pAdmCtrl->evalSite = admCtrlWpa_evalSite;
pAdmCtrl->getPmkidList = admCtrl_nullGetPMKIDlist;
pAdmCtrl->setPmkidList = admCtrl_nullSetPMKIDlist;
pAdmCtrl->resetPmkidList = admCtrl_resetPMKIDlist;
pAdmCtrl->getPreAuthStatus = admCtrl_nullGetPreAuthStatus;
pAdmCtrl->startPreAuth = admCtrl_nullStartPreAuth;
pAdmCtrl->get802_1x_AkmExists = admCtrlWpa_get802_1x_AkmExists;
/* set cipher suite */
switch (pAdmCtrl->externalAuthMode)
{
case RSN_EXT_AUTH_MODE_WPA:
case RSN_EXT_AUTH_MODE_WPAPSK:
/* The cipher suite should be set by the External source via
the Encryption field*/
pAdmCtrl->keyMngSuite = RSN_KEY_MNG_802_1X;
break;
case RSN_EXT_AUTH_MODE_WPANONE:
pAdmCtrl->keyMngSuite = RSN_KEY_MNG_NONE;
/* Not supported */
default:
return TI_NOK;
}
paeConfig.authProtocol = pAdmCtrl->externalAuthMode;
paeConfig.unicastSuite = pAdmCtrl->unicastSuite;
paeConfig.broadcastSuite = pAdmCtrl->broadcastSuite;
paeConfig.keyExchangeProtocol = pAdmCtrl->keyMngSuite;
/* set default PAE configuration */
status = pAdmCtrl->pRsn->setPaeConfig(pAdmCtrl->pRsn, &paeConfig);
return status;
}
TI_STATUS admCtrlWpa_dynamicConfig(admCtrl_t *pAdmCtrl,wpaIeData_t *pWpaData)
{
TI_STATUS status;
TRsnPaeConfig paeConfig;
/* set callback functions (API) */
pAdmCtrl->getInfoElement = admCtrlWpa_getInfoElement;
switch (pAdmCtrl->externalAuthMode)
{
case RSN_EXT_AUTH_MODE_WPA:
case RSN_EXT_AUTH_MODE_WPAPSK:
/* The cipher suite should be set by the External source via
the Encryption field*/
pAdmCtrl->keyMngSuite = RSN_KEY_MNG_802_1X;
break;
case RSN_EXT_AUTH_MODE_WPANONE:
pAdmCtrl->keyMngSuite = RSN_KEY_MNG_NONE;
/* Not supported */
default:
return TI_NOK;
}
paeConfig.authProtocol = pAdmCtrl->externalAuthMode;
paeConfig.unicastSuite = pWpaData->unicastSuite[0];
paeConfig.broadcastSuite = pWpaData->broadcastSuite;
paeConfig.keyExchangeProtocol = pAdmCtrl->keyMngSuite;
/* set default PAE configuration */
status = pAdmCtrl->pRsn->setPaeConfig(pAdmCtrl->pRsn, &paeConfig);
return status;
}
/**
*
* admCtrlWpa_getInfoElement - Get the current information element.
*
* \b Description:
*
* Get the current information element.
*
* \b ARGS:
*
* I - pAdmCtrl - context \n
* I - pIe - IE buffer \n
* I - pLength - length of IE \n
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK on failure.
*
* \sa
*/
TI_STATUS admCtrlWpa_getInfoElement(admCtrl_t *pAdmCtrl, TI_UINT8 *pIe, TI_UINT32 *pLength)
{
wpaIePacket_t localWpaPkt;
wpaIePacket_t *pWpaIePacket;
TI_UINT8 length;
TI_UINT16 tempInt;
TIWLN_SIMPLE_CONFIG_MODE wscMode;
/* Get Simple-Config state */
siteMgr_getParamWSC(pAdmCtrl->pRsn->hSiteMgr, &wscMode); /* SITE_MGR_SIMPLE_CONFIG_MODE */
if (pIe==NULL)
{
*pLength = 0;
return TI_NOK;
}
if ((wscMode != TIWLN_SIMPLE_CONFIG_OFF) &&
(pAdmCtrl->broadcastSuite == TWD_CIPHER_NONE) &&
(pAdmCtrl->unicastSuite == TWD_CIPHER_NONE))
{
*pLength = 0;
return TI_NOK;
}
/* Check validity of WPA IE */
if (!broadcastCipherSuiteValidity[pAdmCtrl->networkMode][pAdmCtrl->broadcastSuite])
{ /* check Group suite validity */
*pLength = 0;
return TI_NOK;
}
if (pAdmCtrl->unicastSuite == TWD_CIPHER_WEP)
{ /* check pairwise suite validity */
*pLength = 0;
return TI_NOK;
}
/* Build Wpa IE */
pWpaIePacket = &localWpaPkt;
os_memoryZero(pAdmCtrl->hOs, pWpaIePacket, sizeof(wpaIePacket_t));
pWpaIePacket->elementid= WPA_IE_ID;
os_memoryCopy(pAdmCtrl->hOs, (void *)pWpaIePacket->oui, wpaIeOuiIe, 3);
pWpaIePacket->ouiType = WPA_OUI_DEF_TYPE;
tempInt = WPA_OUI_MAX_VERSION;
COPY_WLAN_WORD(&pWpaIePacket->version, &tempInt);
length = sizeof(wpaIePacket_t)-2;
/* check defaults */
if (pAdmCtrl->replayCnt==1)
{
length -= 2; /* 2: capabilities + 4: keyMng suite, 2: keyMng count*/
#if 0 /* The following was removed since there are APs which do no accept
the default WPA IE */
if (pAdmCtrl->externalAuthMode == RSN_EXT_AUTH_MODE_WPA)
{
length -= 6; /* 2: capabilities + 4: keyMng suite, 2: keyMng count*/
if (pAdmCtrl->unicastSuite == TWD_CIPHER_TKIP)
{
length -= 6; /* 4: unicast suite, 2: unicast count */
if (pAdmCtrl->broadcastSuite == TWD_CIPHER_TKIP)
{
length -= 4; /* broadcast suite */
}
}
}
#endif
}
pWpaIePacket->length = length;
*pLength = length+2;
if (length>=WPA_IE_MIN_DEFAULT_LENGTH)
{ /* build Capabilities */
pWpaIePacket->capabilities = ENDIAN_HANDLE_WORD(admCtrlWpa_buildCapabilities(pAdmCtrl->replayCnt));
}
if (length>=WPA_IE_MIN_KEY_MNG_SUITE_LENGTH(1))
{
/* build keyMng suite */
tempInt = 0x0001;
COPY_WLAN_WORD(&pWpaIePacket->authKeyMngSuiteCnt, &tempInt);
os_memoryCopy(pAdmCtrl->hOs, (void *)pWpaIePacket->authKeyMngSuite, wpaIeOuiIe, 3);
switch (pAdmCtrl->externalAuthMode)
{
case RSN_EXT_AUTH_MODE_OPEN:
case RSN_EXT_AUTH_MODE_SHARED_KEY:
case RSN_EXT_AUTH_MODE_AUTO_SWITCH:
pWpaIePacket->authKeyMngSuite[3] = WPA_IE_KEY_MNG_NONE;
break;
case RSN_EXT_AUTH_MODE_WPA:
{
#ifdef XCC_MODULE_INCLUDED
TI_UINT8 akmSuite[DOT11_OUI_LEN];
if (admCtrlXCC_getCckmAkm(pAdmCtrl, akmSuite))
{
os_memoryCopy(pAdmCtrl->hOs, (void*)pWpaIePacket->authKeyMngSuite, akmSuite, DOT11_OUI_LEN);
}
else
#endif
{
pWpaIePacket->authKeyMngSuite[3] = WPA_IE_KEY_MNG_801_1X;
}
}
break;
case RSN_EXT_AUTH_MODE_WPAPSK:
pWpaIePacket->authKeyMngSuite[3] = WPA_IE_KEY_MNG_PSK_801_1X;
break;
default:
pWpaIePacket->authKeyMngSuite[3] = WPA_IE_KEY_MNG_NONE;
break;
}
}
if (length>=WPA_IE_MIN_PAIRWISE_SUITE_LENGTH)
{
#ifdef XCC_MODULE_INCLUDED
if ((pAdmCtrl->pRsn->paeConfig.unicastSuite==TWD_CIPHER_CKIP) ||
(pAdmCtrl->pRsn->paeConfig.broadcastSuite==TWD_CIPHER_CKIP))
{
admCtrlXCC_getWpaCipherInfo(pAdmCtrl,pWpaIePacket);
}
else
#endif
{
/* build pairwise suite */
tempInt = 0x0001;
COPY_WLAN_WORD(&pWpaIePacket->pairwiseSuiteCnt, &tempInt);
os_memoryCopy(pAdmCtrl->hOs, (void *)pWpaIePacket->pairwiseSuite, wpaIeOuiIe, 3);
pWpaIePacket->pairwiseSuite[3] = (TI_UINT8)pAdmCtrl->pRsn->paeConfig.unicastSuite;
if (length>=WPA_IE_GROUP_SUITE_LENGTH)
{ /* build group suite */
os_memoryCopy(pAdmCtrl->hOs, (void *)pWpaIePacket->groupSuite, wpaIeOuiIe, 3);
pWpaIePacket->groupSuite[3] = (TI_UINT8)pAdmCtrl->pRsn->paeConfig.broadcastSuite;
}
}
}
os_memoryCopy(pAdmCtrl->hOs, (TI_UINT8*)pIe, (TI_UINT8*)pWpaIePacket, sizeof(wpaIePacket_t));
return TI_OK;
}
/**
*
* admCtrlWpa_setSite - Set current primary site parameters for registration.
*
* \b Description:
*
* Set current primary site parameters for registration.
*
* \b ARGS:
*
* I - pAdmCtrl - context \n
* I - pRsnData - site's RSN data \n
* O - pAssocIe - result IE of evaluation \n
* O - pAssocIeLen - length of result IE of evaluation \n
*
* \b RETURNS:
*
* TI_OK on site is aproved, TI_NOK on site is rejected.
*
* \sa
*/
TI_STATUS admCtrlWpa_setSite(admCtrl_t *pAdmCtrl, TRsnData *pRsnData, TI_UINT8 *pAssocIe, TI_UINT8 *pAssocIeLen)
{
TI_STATUS status;
paramInfo_t *pParam;
TTwdParamInfo tTwdParam;
wpaIeData_t wpaData;
ECipherSuite encryptionStatus;
admCtrlWpa_validity_t *pAdmCtrlWpa_validity=NULL;
TI_UINT8 *pWpaIe;
TI_UINT8 index;
*pAssocIeLen = 0;
if (pRsnData==NULL)
{
return TI_NOK;
}
pParam = (paramInfo_t *)os_memoryAlloc(pAdmCtrl->hOs, sizeof(paramInfo_t));
if (!pParam)
{
return TI_NOK;
}
if (pRsnData->pIe==NULL)
{
/* configure the MLME module with the 802.11 OPEN authentication suite,
THe MLME will configure later the authentication module */
pParam->paramType = MLME_LEGACY_TYPE_PARAM;
pParam->content.mlmeLegacyAuthType = AUTH_LEGACY_OPEN_SYSTEM;
status = mlme_setParam(pAdmCtrl->hMlme, pParam);
goto adm_ctrl_wpa_end;
}
#ifdef XCC_MODULE_INCLUDED
/* Check if Aironet IE exists */
admCtrlXCC_setExtendedParams(pAdmCtrl, pRsnData);
#endif /*XCC_MODULE_INCLUDED*/
/* Check if any-WPA mode is supported and WPA2 info elem is presented */
/* If yes - perform WPA2 set site procedure */
if(pAdmCtrl->WPAMixedModeEnable && pAdmCtrl->WPAPromoteFlags)
{
if((admCtrl_parseIe(pAdmCtrl, pRsnData, &pWpaIe, RSN_IE_ID)== TI_OK) &&
(pWpaIe != NULL))
{
status = admCtrlWpa2_setSite(pAdmCtrl, pRsnData, pAssocIe, pAssocIeLen);
if(status == TI_OK)
goto adm_ctrl_wpa_end;
}
}
status = admCtrl_parseIe(pAdmCtrl, pRsnData, &pWpaIe, WPA_IE_ID);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
status = admCtrlWpa_parseIe(pAdmCtrl, pWpaIe, &wpaData);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
if ((wpaData.unicastSuite[0]>=MAX_WPA_CIPHER_SUITE) ||
(wpaData.broadcastSuite>=MAX_WPA_CIPHER_SUITE) ||
(pAdmCtrl->unicastSuite>=MAX_WPA_CIPHER_SUITE))
{
status = TI_NOK;
goto adm_ctrl_wpa_end;
}
pAdmCtrl->encrInSw = wpaData.XCCKp;
pAdmCtrl->micInSw = wpaData.XCCMic;
/*Because ckip is a proprietary encryption for Cisco then a different validity check is needed */
if(wpaData.broadcastSuite == TWD_CIPHER_CKIP || wpaData.unicastSuite[0] == TWD_CIPHER_CKIP)
{
pAdmCtrl->getCipherSuite(pAdmCtrl, &encryptionStatus);
/*Funk supplicant can support CCKM only if it configures the driver to TKIP encryption. */
if (encryptionStatus != TWD_CIPHER_TKIP) {
status = TI_NOK;
goto adm_ctrl_wpa_end;
}
if (pAdmCtrl->encrInSw)
pAdmCtrl->XCCSupport = TI_TRUE;
}
else
{
/* Check validity of Group suite */
if (!broadcastCipherSuiteValidity[pAdmCtrl->networkMode][wpaData.broadcastSuite])
{ /* check Group suite validity */
status = TI_NOK;
goto adm_ctrl_wpa_end;
}
pAdmCtrl->getCipherSuite(pAdmCtrl, &encryptionStatus);
for (index=0; index<wpaData.unicastSuiteCnt; index++)
{
pAdmCtrlWpa_validity = &admCtrlWpa_validityTable[wpaData.unicastSuite[index]][wpaData.broadcastSuite][encryptionStatus];
if (pAdmCtrlWpa_validity->status ==TI_OK)
{
break;
}
}
if (pAdmCtrlWpa_validity->status != TI_OK)
{
status = pAdmCtrlWpa_validity->status;
goto adm_ctrl_wpa_end;
}
/* set cipher suites */
wpaData.unicastSuite[0] = pAdmCtrlWpa_validity->unicast ;/*wpaData.unicastSuite[0];*/
wpaData.broadcastSuite = pAdmCtrlWpa_validity->broadcast; /*wpaData.broadcastSuite;*/
}
/* set external auth mode according to the key Mng Suite */
switch (wpaData.KeyMngSuite[0])
{
case WPA_IE_KEY_MNG_NONE:
pAdmCtrl->externalAuthMode = RSN_EXT_AUTH_MODE_OPEN;
break;
case WPA_IE_KEY_MNG_801_1X:
#ifdef XCC_MODULE_INCLUDED
case WPA_IE_KEY_MNG_CCKM:
#endif
pAdmCtrl->externalAuthMode = RSN_EXT_AUTH_MODE_WPA;
break;
case WPA_IE_KEY_MNG_PSK_801_1X:
#if 0 /* code will remain here until the WSC spec will be closed*/
if ((wpaData.KeyMngSuiteCnt > 1) && (wpaData.KeyMngSuite[1] == WPA_IE_KEY_MNG_801_1X))
{
/*WLAN_OS_REPORT (("Overriding for simple-config - setting external auth to MODE WPA\n"));*/
/*pAdmCtrl->externalAuthMode = RSN_EXT_AUTH_MODE_WPA;*/
}
else
{
/*pAdmCtrl->externalAuthMode = RSN_EXT_AUTH_MODE_WPAPSK;*/
}
#endif
break;
default:
pAdmCtrl->externalAuthMode = RSN_EXT_AUTH_MODE_OPEN;
break;
}
#ifdef XCC_MODULE_INCLUDED
pParam->paramType = XCC_CCKM_EXISTS;
pParam->content.XCCCckmExists = (wpaData.KeyMngSuite[0]==WPA_IE_KEY_MNG_CCKM) ? TI_TRUE : TI_FALSE;
XCCMngr_setParam(pAdmCtrl->hXCCMngr, pParam);
#endif
/* set replay counter */
pAdmCtrl->replayCnt = wpaData.replayCounters;
*pAssocIeLen = pRsnData->ieLen;
if (pAssocIe != NULL)
{
os_memoryCopy(pAdmCtrl->hOs, pAssocIe, &wpaData, sizeof(wpaIeData_t));
}
/* Now we configure the MLME module with the 802.11 legacy authentication suite,
THe MLME will configure later the authentication module */
pParam->paramType = MLME_LEGACY_TYPE_PARAM;
#ifdef XCC_MODULE_INCLUDED
if (pAdmCtrl->networkEapMode!=OS_XCC_NETWORK_EAP_OFF)
{
pParam->content.mlmeLegacyAuthType = AUTH_LEGACY_RESERVED1;
}
else
#endif
{
pParam->content.mlmeLegacyAuthType = AUTH_LEGACY_OPEN_SYSTEM;
}
status = mlme_setParam(pAdmCtrl->hMlme, pParam);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
pParam->paramType = RX_DATA_EAPOL_DESTINATION_PARAM;
pParam->content.rxDataEapolDestination = OS_ABS_LAYER;
status = rxData_setParam(pAdmCtrl->hRx, pParam);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
/* Configure privacy status in HAL so that HW is prepared to recieve keys */
tTwdParam.paramType = TWD_RSN_SECURITY_MODE_PARAM_ID;
tTwdParam.content.rsnEncryptionStatus = (ECipherSuite)wpaData.unicastSuite[0];
status = TWD_SetParam(pAdmCtrl->pRsn->hTWD, &tTwdParam);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
#ifdef XCC_MODULE_INCLUDED
/* set MIC and KP in HAL */
tTwdParam.paramType = TWD_RSN_XCC_SW_ENC_ENABLE_PARAM_ID;
tTwdParam.content.rsnXCCSwEncFlag = wpaData.XCCKp;
status = TWD_SetParam(pAdmCtrl->pRsn->hTWD, &tTwdParam);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
tTwdParam.paramType = TWD_RSN_XCC_MIC_FIELD_ENABLE_PARAM_ID;
tTwdParam.content.rsnXCCMicFieldFlag = wpaData.XCCMic;
status = TWD_SetParam(pAdmCtrl->pRsn->hTWD, &tTwdParam);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
#endif /*XCC_MODULE_INCLUDED*/
/* re-config PAE */
status = admCtrlWpa_dynamicConfig(pAdmCtrl,&wpaData);
if (status != TI_OK)
{
goto adm_ctrl_wpa_end;
}
adm_ctrl_wpa_end:
os_memoryFree(pAdmCtrl->hOs, pParam, sizeof(paramInfo_t));
return status;
}
/**
*
* admCtrlWpa_evalSite - Evaluate site for registration.
*
* \b Description:
*
* evaluate site RSN capabilities against the station's cap.
* If the BSS type is infrastructure, the station matches the site only if it's WEP status is same as the site
* In IBSS, it does not matter
*
* \b ARGS:
*
* I - pAdmCtrl - Context \n
* I - pRsnData - site's RSN data \n
* O - pEvaluation - Result of evaluation \n
*
* \b RETURNS:
*
* TI_OK
*
* \sa
*/
TI_STATUS admCtrlWpa_evalSite(admCtrl_t *pAdmCtrl, TRsnData *pRsnData, TRsnSiteParams *pRsnSiteParams, TI_UINT32 *pEvaluation)
{
TI_STATUS status;
wpaIeData_t wpaData;
admCtrlWpa_validity_t admCtrlWpa_validity;
ECipherSuite encryptionStatus;
TIWLN_SIMPLE_CONFIG_MODE wscMode;
TI_UINT8 *pWpaIe;
TI_UINT8 index;
/* Get Simple-Config state */
status = siteMgr_getParamWSC(pAdmCtrl->pRsn->hSiteMgr, &wscMode); /* SITE_MGR_SIMPLE_CONFIG_MODE */
*pEvaluation = 0;
if (pRsnData==NULL)
{
return TI_NOK;
}
if ((pRsnData->pIe==NULL) && (wscMode == TIWLN_SIMPLE_CONFIG_OFF))
{
return TI_NOK;
}
if (pRsnSiteParams->bssType != BSS_INFRASTRUCTURE)
{
return TI_NOK;
}
/* Set initial values for admCtrlWpa_validity as none*/
admCtrlWpa_validity = admCtrlWpa_validityTable[TWD_CIPHER_NONE][TWD_CIPHER_NONE][TWD_CIPHER_NONE];
/* Check if WPA-any mode is supported and WPA2 info elem is presented */
/* If yes - perform WPA2 site evaluation */
if(pAdmCtrl->WPAMixedModeEnable && pAdmCtrl->WPAPromoteFlags)
{
if((admCtrl_parseIe(pAdmCtrl, pRsnData, &pWpaIe, RSN_IE_ID)== TI_OK) &&
(pWpaIe != NULL))
{
status = admCtrlWpa2_evalSite(pAdmCtrl, pRsnData, pRsnSiteParams, pEvaluation);
if(status == TI_OK)
return status;
}
}
status = admCtrl_parseIe(pAdmCtrl, pRsnData, &pWpaIe, WPA_IE_ID);
if ((status != TI_OK) && (wscMode == TIWLN_SIMPLE_CONFIG_OFF))
{
return status;
}
/* If found WPA Information Element */
if (pWpaIe != NULL)
{
status = admCtrlWpa_parseIe(pAdmCtrl, pWpaIe, &wpaData);
if (status != TI_OK)
{
return status;
}
/* check keyMngSuite validity */
switch (wpaData.KeyMngSuite[0])
{
case WPA_IE_KEY_MNG_NONE:
TRACE0(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "admCtrlWpa_evalSite: KeyMngSuite[0]=WPA_IE_KEY_MNG_NONE\n");
status = (pAdmCtrl->externalAuthMode <= RSN_EXT_AUTH_MODE_AUTO_SWITCH) ? TI_OK : TI_NOK;
break;
case WPA_IE_KEY_MNG_801_1X:
#ifdef XCC_MODULE_INCLUDED
case WPA_IE_KEY_MNG_CCKM:
/* CCKM is allowed only in 802.1x auth */
#endif
TRACE0(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "admCtrlWpa_evalSite: KeyMngSuite[0]=WPA_IE_KEY_MNG_801_1X\n");
status = (pAdmCtrl->externalAuthMode == RSN_EXT_AUTH_MODE_WPA) ? TI_OK : TI_NOK;
break;
case WPA_IE_KEY_MNG_PSK_801_1X:
TRACE0(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "admCtrlWpa_evalSite: KeyMngSuite[0]=WPA_IE_KEY_MNG_PSK_801_1X\n");
status = ((pAdmCtrl->externalAuthMode == RSN_EXT_AUTH_MODE_WPAPSK) ||
(wscMode && (pAdmCtrl->externalAuthMode == RSN_EXT_AUTH_MODE_WPA))) ? TI_OK : TI_NOK;
break;
default:
status = TI_NOK;
break;
}
TRACE2(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "admCtrlWpa_evalSite: pAdmCtrl->externalAuthMode = %d, Status = %d\n",pAdmCtrl->externalAuthMode,status);
if (status != TI_OK)
{
return status;
}
/*Because ckip is a proprietary encryption for Cisco then a different validity check is needed */
if(wpaData.broadcastSuite == TWD_CIPHER_CKIP || wpaData.unicastSuite[0] == TWD_CIPHER_CKIP)
{
pAdmCtrl->getCipherSuite(pAdmCtrl, &encryptionStatus);
if (encryptionStatus != TWD_CIPHER_TKIP)
return TI_NOK;
}
else
{
/* Check cipher suite validity */
pAdmCtrl->getCipherSuite(pAdmCtrl, &encryptionStatus);
for (index=0; index<wpaData.unicastSuiteCnt; index++)
{
admCtrlWpa_validity = admCtrlWpa_validityTable[wpaData.unicastSuite[index]][wpaData.broadcastSuite][encryptionStatus];
if (admCtrlWpa_validity.status ==TI_OK)
{
break;
}
}
if (admCtrlWpa_validity.status!=TI_OK)
{
return admCtrlWpa_validity.status;
}
wpaData.broadcastSuite = admCtrlWpa_validity.broadcast;
wpaData.unicastSuite[0] = admCtrlWpa_validity.unicast;
*pEvaluation = admCtrlWpa_validity.evaluation;
}
/* Check privacy bit if not in mixed mode */
if (!pAdmCtrl->mixedMode)
{ /* There's no mixed mode, so make sure that the privacy Bit matches the privacy mode*/
if (((pRsnData->privacy) && (wpaData.unicastSuite[0]==TWD_CIPHER_NONE)) ||
((!pRsnData->privacy) && (wpaData.unicastSuite[0]>TWD_CIPHER_NONE)))
{
*pEvaluation = 0;
}
}
}
else
{
TRACE0(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "didn't find WPA IE\n");
if (wscMode == TIWLN_SIMPLE_CONFIG_OFF)
return TI_NOK;
TRACE0(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "metric is 1\n");
*pEvaluation = 1;
pAdmCtrl->broadcastSuite = TWD_CIPHER_NONE;
pAdmCtrl->unicastSuite = TWD_CIPHER_NONE;
}
/* always return TI_OK */
return TI_OK;
}
/**
*
* admCtrlWpa_parseIe - Parse an WPA information element.
*
* \b Description:
*
* Parse an WPA information element.
* Builds a structure of the unicast adn broadcast cihper suites,
* the key management suite and the capabilities.
*
* \b ARGS:
*
* I - pAdmCtrl - pointer to admCtrl context
* I - pWpaIe - pointer to WPA IE buffer \n
* O - pWpaData - capabilities structure
*
*
* \b RETURNS:
*
* TI_OK on success, TI_NOK on failure.
*
* \sa
*/
TI_STATUS admCtrlWpa_parseIe(admCtrl_t *pAdmCtrl, TI_UINT8 *pWpaIe, wpaIeData_t *pWpaData)
{
wpaIePacket_t *wpaIePacket = (wpaIePacket_t*)pWpaIe;
TI_UINT8 *curWpaIe;
TI_UINT8 curLength = WPA_IE_MIN_LENGTH;
TRACE0(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_IE: DEBUG: admCtrlWpa_parseIe\n\n");
if ((pWpaData == NULL) || (pWpaIe == NULL))
{
return TI_NOK;
}
if ((wpaIePacket->length < WPA_IE_MIN_LENGTH) ||
(wpaIePacket->elementid != WPA_IE_ID) ||
(wpaIePacket->ouiType > WPA_OUI_MAX_TYPE) || (ENDIAN_HANDLE_WORD(wpaIePacket->version) > WPA_OUI_MAX_VERSION) ||
(os_memoryCompare(pAdmCtrl->hOs, (TI_UINT8*)wpaIePacket->oui, wpaIeOuiIe, 3)))
{
TRACE7(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_ParseIe Error: length=0x%x, elementid=0x%x, ouiType=0x%x, version=0x%x, oui=0x%x, 0x%x, 0x%x\n", wpaIePacket->length,wpaIePacket->elementid, wpaIePacket->ouiType, wpaIePacket->version, wpaIePacket->oui[0], wpaIePacket->oui[1],wpaIePacket->oui[2]);
return TI_NOK;
}
/* Set default values */
pWpaData->broadcastSuite = TWD_CIPHER_TKIP;
pWpaData->unicastSuiteCnt = 1;
pWpaData->unicastSuite[0] = TWD_CIPHER_TKIP;
pWpaData->KeyMngSuiteCnt = 1;
pWpaData->KeyMngSuite[0] = (ERsnKeyMngSuite)WPA_IE_KEY_MNG_801_1X;
pWpaData->bcastForUnicatst = 1;
pWpaData->replayCounters = 1;
pWpaData->XCCKp = TI_FALSE;
pWpaData->XCCMic = TI_FALSE;
/* Group Suite */
if (wpaIePacket->length >= WPA_IE_GROUP_SUITE_LENGTH)
{
pWpaData->broadcastSuite = (ECipherSuite)admCtrlWpa_parseSuiteVal(pAdmCtrl, (TI_UINT8 *)wpaIePacket->groupSuite,pWpaData,TWD_CIPHER_WEP104);
curLength = WPA_IE_GROUP_SUITE_LENGTH;
TRACE2(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_IE: GroupSuite%x, broadcast %x \n", wpaIePacket->groupSuite[3], pWpaData->broadcastSuite);
} else
{
return TI_OK;
}
/* Unicast Suite */
if (wpaIePacket->length >= WPA_IE_MIN_PAIRWISE_SUITE_LENGTH)
{
TI_UINT16 pairWiseSuiteCnt = ENDIAN_HANDLE_WORD(wpaIePacket->pairwiseSuiteCnt);
TI_BOOL cipherSuite[MAX_WPA_UNICAST_SUITES]={TI_FALSE, TI_FALSE, TI_FALSE, TI_FALSE, TI_FALSE, TI_FALSE , TI_FALSE};
TI_INT32 index, unicastSuiteIndex=0;
curWpaIe = (TI_UINT8*)&(wpaIePacket->pairwiseSuite);
for (index=0; (index<pairWiseSuiteCnt) && (wpaIePacket->length >= (WPA_IE_MIN_PAIRWISE_SUITE_LENGTH+(index+1)*4)); index++)
{
ECipherSuite curCipherSuite;
curCipherSuite = (ECipherSuite)admCtrlWpa_parseSuiteVal(pAdmCtrl, curWpaIe,pWpaData,TWD_CIPHER_WEP104);
TRACE2(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_IE: pairwiseSuite %x , unicast %x \n", curWpaIe[3], curCipherSuite);
if ((curCipherSuite!=TWD_CIPHER_UNKNOWN) && (curCipherSuite<MAX_WPA_UNICAST_SUITES))
{
cipherSuite[curCipherSuite] = TI_TRUE;
}
curWpaIe +=4;
}
for (index=MAX_WPA_UNICAST_SUITES-1; index>=0; index--)
{
if (cipherSuite[index])
{
pWpaData->unicastSuite[unicastSuiteIndex] = (ECipherSuite)index;
TRACE1(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_IE: unicast %x \n", pWpaData->unicastSuite[unicastSuiteIndex]);
unicastSuiteIndex++;
}
}
pWpaData->unicastSuiteCnt = unicastSuiteIndex;
curLength = WPA_IE_MIN_KEY_MNG_SUITE_LENGTH(pairWiseSuiteCnt);
} else
{
return TI_OK;
}
/* KeyMng Suite */
if (wpaIePacket->length >= curLength)
{
TI_UINT16 keyMngSuiteCnt = ENDIAN_HANDLE_WORD(*curWpaIe);
TI_UINT16 index;
ERsnKeyMngSuite maxKeyMngSuite = (ERsnKeyMngSuite)WPA_IE_KEY_MNG_NONE;
/* Include all AP key management supported suites in the wpaData structure */
pWpaData->KeyMngSuiteCnt = keyMngSuiteCnt;
curWpaIe +=2;
pAdmCtrl->wpaAkmExists = TI_FALSE;
for (index=0; (index<keyMngSuiteCnt) && (wpaIePacket->length >= (curLength+index*4)); index++)
{
ERsnKeyMngSuite curKeyMngSuite;
#ifdef XCC_MODULE_INCLUDED
curKeyMngSuite = (ERsnKeyMngSuite)admCtrlXCC_parseCckmSuiteVal(pAdmCtrl, curWpaIe);
if (curKeyMngSuite == WPA_IE_KEY_MNG_CCKM)
{ /* CCKM is the maximum AKM */
maxKeyMngSuite = curKeyMngSuite;
}
else
#endif
{
curKeyMngSuite = (ERsnKeyMngSuite)admCtrlWpa_parseSuiteVal(pAdmCtrl, curWpaIe,pWpaData,WPA_IE_KEY_MNG_PSK_801_1X);
}
TRACE2(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_IE: authKeyMng %x , keyMng %x \n", curWpaIe[3], curKeyMngSuite);
if ((curKeyMngSuite>maxKeyMngSuite) && (curKeyMngSuite!=WPA_IE_KEY_MNG_NA)
&& (curKeyMngSuite!=WPA_IE_KEY_MNG_CCKM))
{
maxKeyMngSuite = curKeyMngSuite;
}
if (curKeyMngSuite==WPA_IE_KEY_MNG_801_1X)
{ /* If 2 AKM exist, save also the second priority */
pAdmCtrl->wpaAkmExists = TI_TRUE;
}
curWpaIe +=4;
/* Include all AP key management supported suites in the wpaData structure */
if ((index+1) < MAX_WPA_KEY_MNG_SUITES)
pWpaData->KeyMngSuite[index+1] = curKeyMngSuite;
}
pWpaData->KeyMngSuite[0] = maxKeyMngSuite;
curLength += (index-1)*4;
TRACE1(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_IE: keyMng %x \n", pWpaData->KeyMngSuite[0]);
} else
{
return TI_OK;
}
/* Parse capabilities */
if (wpaIePacket->length >= (curLength+2))
{
TI_UINT16 capabilities = ENDIAN_HANDLE_WORD(*((TI_UINT16 *)curWpaIe));
pWpaData->bcastForUnicatst = (capabilities & WPA_GROUP_4_UNICAST_CAPABILITY_MASK) >> WPA_REPLAY_GROUP4UNI_CAPABILITY_SHIFT;
pWpaData->replayCounters = (capabilities & WPA_REPLAY_COUNTERS_CAPABILITY_MASK) >> WPA_REPLAY_COUNTERS_CAPABILITY_SHIFT;
switch (pWpaData->replayCounters)
{
case 0: pWpaData->replayCounters=1;
break;
case 1: pWpaData->replayCounters=2;
break;
case 2: pWpaData->replayCounters=4;
break;
case 3: pWpaData->replayCounters=16;
break;
default: pWpaData->replayCounters=0;
break;
}
TRACE3(pAdmCtrl->hReport, REPORT_SEVERITY_INFORMATION, "Wpa_IE: capabilities %x, bcastForUnicatst %x, replayCounters %x\n", capabilities, pWpaData->bcastForUnicatst, pWpaData->replayCounters);
}
return TI_OK;
}
TI_UINT16 admCtrlWpa_buildCapabilities(TI_UINT16 replayCnt)
{
TI_UINT16 capabilities=0;
/* Bit1: group key for unicast */
capabilities = 0;
capabilities = capabilities << WPA_REPLAY_GROUP4UNI_CAPABILITY_SHIFT;
/* Bits 2&3: Replay counter */
switch (replayCnt)
{
case 1: replayCnt=0;
break;
case 2: replayCnt=1;
break;
case 4: replayCnt=2;
break;
case 16: replayCnt=3;
break;
default: replayCnt=0;
break;
}
capabilities |= replayCnt << WPA_REPLAY_COUNTERS_CAPABILITY_SHIFT;
return capabilities;
}
TI_UINT32 admCtrlWpa_parseSuiteVal(admCtrl_t *pAdmCtrl, TI_UINT8* suiteVal, wpaIeData_t *pWpaData, TI_UINT32 maxVal)
{
TI_UINT32 suite;
if ((pAdmCtrl==NULL) || (suiteVal==NULL))
{
return TWD_CIPHER_UNKNOWN;
}
if (!os_memoryCompare(pAdmCtrl->hOs, suiteVal, wpaIeOuiIe, 3))
{
suite = (ECipherSuite)((suiteVal[3]<=maxVal) ? suiteVal[3] : TWD_CIPHER_UNKNOWN);
} else
{
#ifdef XCC_MODULE_INCLUDED
suite = admCtrlXCC_WpaParseSuiteVal(pAdmCtrl,suiteVal,pWpaData);
#else
suite = TWD_CIPHER_UNKNOWN;
#endif
}
return suite;
}
TI_STATUS admCtrlWpa_checkCipherSuiteValidity (ECipherSuite unicastSuite, ECipherSuite broadcastSuite, ECipherSuite encryptionStatus)
{
ECipherSuite maxCipher;
maxCipher = (unicastSuite>=broadcastSuite) ? unicastSuite : broadcastSuite ;
if (maxCipher != encryptionStatus)
{
return TI_NOK;
}
if ((unicastSuite != TWD_CIPHER_NONE) && (broadcastSuite>unicastSuite))
{
return TI_NOK;
}
return TI_OK;
}
static TI_STATUS admCtrlWpa_get802_1x_AkmExists (admCtrl_t *pAdmCtrl, TI_BOOL *wpa_802_1x_AkmExists)
{
*wpa_802_1x_AkmExists = pAdmCtrl->wpaAkmExists;
return TI_OK;
}
| jjm2473/AMLOGIC_M8 | drivers/net/wifi-fw-kk-amlogic/wgt7310/wl1271_m603/stad/src/Connection_Managment/admCtrlWpa.c | C | gpl-2.0 | 55,066 |
<?php
namespace net\authorize\api\contract\v1;
/**
* Class representing ARBUpdateSubscriptionResponse
*/
class ARBUpdateSubscriptionResponse extends ANetApiResponseType
{
}
| maninator/manimediaserver | www/gateways/anet/lib/net/authorize/api/contract/v1/ARBUpdateSubscriptionResponse.php | PHP | gpl-3.0 | 180 |
---------------------------------------------------
-- Snow Cloud
-- Deals Ice damage to targets in a fan-shaped area of effect. Additional effect: Paralyze
-- Range: 10' cone
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PARALYSIS;
MobStatusEffectMove(mob, target, typeEffect, 20, 0, 120);
local dmgmod = 1;
local accmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_ICE,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| bnetcc/darkstar | scripts/globals/mobskills/snow_cloud_custom.lua | Lua | gpl-3.0 | 920 |
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
from PyQt5 import QtCore, QtWidgets
from peacock.utils.TextSubWindow import TextSubWindow
from peacock.utils import WidgetUtils
class OutputWidgetBase(QtWidgets.QWidget):
"""
Plugin responsible for triggering the creation of png/pdf/py files and live script window.
"""
write = QtCore.pyqtSignal(str)
def __init__(self):
super(OutputWidgetBase, self).__init__()
self._icon_size = QtCore.QSize(32, 32)
self.MainLayout = QtWidgets.QHBoxLayout()
self.MainLayout.setContentsMargins(0, 0, 0, 0)
self.MainLayout.setSpacing(5)
self.PythonButton = QtWidgets.QPushButton()
self.PDFButton = QtWidgets.QPushButton()
self.PNGButton = QtWidgets.QPushButton()
self.LiveScriptButton = QtWidgets.QPushButton()
self.LiveScript = TextSubWindow()
self.setLayout(self.MainLayout)
self.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
self.MainLayout.addWidget(self.PythonButton)
self.MainLayout.addWidget(self.PDFButton)
self.MainLayout.addWidget(self.PNGButton)
self.MainLayout.addWidget(self.LiveScriptButton)
def updateLiveScriptText(self):
"""
Updates the live script view.
"""
if self.LiveScript.isVisible() and hasattr(self, "_plugin_manager"):
# don't reset the text if it is the same. This allows for easier select/copy
s = self._plugin_manager.repr()
if s != self.LiveScript.toPlainText():
self.LiveScript.setText(s)
def _setupPythonButton(self, qobject):
"""
Setup method for python script output button.
"""
qobject.clicked.connect(self._callbackPythonButton)
qobject.setIcon(WidgetUtils.createIcon('py.svg'))
qobject.setIconSize(self._icon_size)
qobject.setFixedSize(qobject.iconSize())
qobject.setToolTip("Create python script to reproduce this figure.")
qobject.setStyleSheet("QPushButton {border:none}")
def _callbackPythonButton(self):
"""
Open dialog and write script.
"""
dialog = QtWidgets.QFileDialog()
dialog.setWindowTitle('Write Python Script')
dialog.setNameFilter('Python Files (*.py)')
dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)
dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
filename = str(dialog.selectedFiles()[0])
self.write.emit(filename)
def _setupPDFButton(self, qobject):
"""
Setup method pdf image output.
"""
qobject.clicked.connect(self._callbackPDFButton)
qobject.setIcon(WidgetUtils.createIcon('pdf.svg'))
qobject.setIconSize(self._icon_size)
qobject.setFixedSize(qobject.iconSize())
qobject.setToolTip("Create a pdf file of the current figure.")
qobject.setStyleSheet("QPushButton {border:none}")
def _callbackPDFButton(self):
"""
Write a PDF file of figure.
"""
dialog = QtWidgets.QFileDialog()
dialog.setWindowTitle('Write *.pdf of figure')
dialog.setNameFilter('PDF files (*.pdf)')
dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)
dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
filename = str(dialog.selectedFiles()[0])
self.write.emit(filename)
def _setupPNGButton(self, qobject):
"""
Setup method png image output.
"""
qobject.clicked.connect(self._callbackPNGButton)
qobject.setIcon(WidgetUtils.createIcon('png.svg'))
qobject.setIconSize(self._icon_size)
qobject.setFixedSize(qobject.iconSize())
qobject.setToolTip("Create a png file of the current figure.")
qobject.setStyleSheet("QPushButton {border:none}")
def _callbackPNGButton(self):
"""
Write a png file of figure.
"""
dialog = QtWidgets.QFileDialog()
dialog.setWindowTitle('Write *.png of figure')
dialog.setNameFilter('PNG files (*.png)')
dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)
dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog)
dialog.setDefaultSuffix("png")
if dialog.exec_() == QtWidgets.QDialog.Accepted:
filename = str(dialog.selectedFiles()[0])
self.write.emit(filename)
def _setupLiveScriptButton(self, qobject):
"""
Setup method png image output.
"""
qobject.clicked.connect(self._callbackLiveScriptButton)
qobject.setIcon(WidgetUtils.createIcon('script.svg'))
qobject.setIconSize(self._icon_size)
qobject.setFixedSize(qobject.iconSize())
qobject.setToolTip("Show the current python script.")
qobject.setStyleSheet("QPushButton {border:none}")
def _callbackLiveScriptButton(self):
"""
Write a png file of figure.
"""
self.LiveScript.show()
self.updateLiveScriptText()
def _setupLiveScript(self, qobject):
"""
Setup for the script text window.
"""
self.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
qobject.setReadOnly(True)
| nuclear-wizard/moose | python/peacock/base/OutputWidgetBase.py | Python | lgpl-2.1 | 5,881 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Accord.Audition")]
[assembly: AssemblyDescription("Accord.NET - Computer Audition Library")]
[assembly: AssemblyConfiguration("")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(false)]
| eripahle/framework | Sources/Accord.Audition/Properties/AssemblyInfo.cs | C# | lgpl-2.1 | 599 |
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.singlejar;
import com.google.devtools.build.singlejar.OptionFileExpander.OptionFileProvider;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A simple virtual file system interface. It's much simpler than the Blaze
* virtual file system and only to be used inside this package.
*/
public interface SimpleFileSystem extends OptionFileProvider {
@Override
InputStream getInputStream(String filename) throws IOException;
/**
* Opens a file for output and returns an output stream. If a file of that
* name already exists, it is overwritten.
*/
OutputStream getOutputStream(String filename) throws IOException;
/**
* Returns the File object for this filename.
*/
File getFile(String filename) throws IOException;
/**
* Delete the file with the given name and return whether deleting it was
* successfull.
*/
boolean delete(String filename);
} | vt09/bazel | src/java_tools/singlejar/java/com/google/devtools/build/singlejar/SimpleFileSystem.java | Java | apache-2.0 | 1,594 |
/*
* Copyright (C) 2003 Sistina Software (UK) Limited.
* Copyright (C) 2004, 2010-2011 Red Hat, Inc. All rights reserved.
*
* This file is released under the GPL.
*/
#include <linux/device-mapper.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/bio.h>
#include <linux/slab.h>
#define DM_MSG_PREFIX "flakey"
#define all_corrupt_bio_flags_match(bio, fc) \
(((bio)->bi_rw & (fc)->corrupt_bio_flags) == (fc)->corrupt_bio_flags)
/*
* Flakey: Used for testing only, simulates intermittent,
* catastrophic device failure.
*/
struct flakey_c {
struct dm_dev *dev;
unsigned long start_time;
sector_t start;
unsigned up_interval;
unsigned down_interval;
unsigned long flags;
unsigned corrupt_bio_byte;
unsigned corrupt_bio_rw;
unsigned corrupt_bio_value;
unsigned corrupt_bio_flags;
};
enum feature_flag_bits {
DROP_WRITES
};
static int parse_features(struct dm_arg_set *as, struct flakey_c *fc,
struct dm_target *ti)
{
int r;
unsigned argc;
const char *arg_name;
static struct dm_arg _args[] = {
{0, 6, "Invalid number of feature args"},
{1, UINT_MAX, "Invalid corrupt bio byte"},
{0, 255, "Invalid corrupt value to write into bio byte (0-255)"},
{0, UINT_MAX, "Invalid corrupt bio flags mask"},
};
/* No feature arguments supplied. */
if (!as->argc)
return 0;
r = dm_read_arg_group(_args, as, &argc, &ti->error);
if (r)
return r;
while (argc) {
arg_name = dm_shift_arg(as);
argc--;
/*
* drop_writes
*/
if (!strcasecmp(arg_name, "drop_writes")) {
if (test_and_set_bit(DROP_WRITES, &fc->flags)) {
ti->error = "Feature drop_writes duplicated";
return -EINVAL;
}
continue;
}
/*
* corrupt_bio_byte <Nth_byte> <direction> <value> <bio_flags>
*/
if (!strcasecmp(arg_name, "corrupt_bio_byte")) {
if (!argc) {
ti->error = "Feature corrupt_bio_byte requires parameters";
return -EINVAL;
}
r = dm_read_arg(_args + 1, as, &fc->corrupt_bio_byte, &ti->error);
if (r)
return r;
argc--;
/*
* Direction r or w?
*/
arg_name = dm_shift_arg(as);
if (!strcasecmp(arg_name, "w"))
fc->corrupt_bio_rw = WRITE;
else if (!strcasecmp(arg_name, "r"))
fc->corrupt_bio_rw = READ;
else {
ti->error = "Invalid corrupt bio direction (r or w)";
return -EINVAL;
}
argc--;
/*
* Value of byte (0-255) to write in place of correct one.
*/
r = dm_read_arg(_args + 2, as, &fc->corrupt_bio_value, &ti->error);
if (r)
return r;
argc--;
/*
* Only corrupt bios with these flags set.
*/
r = dm_read_arg(_args + 3, as, &fc->corrupt_bio_flags, &ti->error);
if (r)
return r;
argc--;
continue;
}
ti->error = "Unrecognised flakey feature requested";
return -EINVAL;
}
if (test_bit(DROP_WRITES, &fc->flags) && (fc->corrupt_bio_rw == WRITE)) {
ti->error = "drop_writes is incompatible with corrupt_bio_byte with the WRITE flag set";
return -EINVAL;
}
return 0;
}
/*
* Construct a flakey mapping:
* <dev_path> <offset> <up interval> <down interval> [<#feature args> [<arg>]*]
*
* Feature args:
* [drop_writes]
* [corrupt_bio_byte <Nth_byte> <direction> <value> <bio_flags>]
*
* Nth_byte starts from 1 for the first byte.
* Direction is r for READ or w for WRITE.
* bio_flags is ignored if 0.
*/
static int flakey_ctr(struct dm_target *ti, unsigned int argc, char **argv)
{
static struct dm_arg _args[] = {
{0, UINT_MAX, "Invalid up interval"},
{0, UINT_MAX, "Invalid down interval"},
};
int r;
struct flakey_c *fc;
unsigned long long tmpll;
struct dm_arg_set as;
const char *devname;
as.argc = argc;
as.argv = argv;
if (argc < 4) {
ti->error = "Invalid argument count";
return -EINVAL;
}
fc = kzalloc(sizeof(*fc), GFP_KERNEL);
if (!fc) {
ti->error = "Cannot allocate linear context";
return -ENOMEM;
}
fc->start_time = jiffies;
devname = dm_shift_arg(&as);
if (sscanf(dm_shift_arg(&as), "%llu", &tmpll) != 1) {
ti->error = "Invalid device sector";
goto bad;
}
fc->start = tmpll;
r = dm_read_arg(_args, &as, &fc->up_interval, &ti->error);
if (r)
goto bad;
r = dm_read_arg(_args, &as, &fc->down_interval, &ti->error);
if (r)
goto bad;
if (!(fc->up_interval + fc->down_interval)) {
ti->error = "Total (up + down) interval is zero";
goto bad;
}
if (fc->up_interval + fc->down_interval < fc->up_interval) {
ti->error = "Interval overflow";
goto bad;
}
r = parse_features(&as, fc, ti);
if (r)
goto bad;
if (dm_get_device(ti, devname, dm_table_get_mode(ti->table), &fc->dev)) {
ti->error = "Device lookup failed";
goto bad;
}
ti->num_flush_requests = 1;
ti->num_discard_requests = 1;
ti->private = fc;
return 0;
bad:
kfree(fc);
return -EINVAL;
}
static void flakey_dtr(struct dm_target *ti)
{
struct flakey_c *fc = ti->private;
dm_put_device(ti, fc->dev);
kfree(fc);
}
static sector_t flakey_map_sector(struct dm_target *ti, sector_t bi_sector)
{
struct flakey_c *fc = ti->private;
return fc->start + dm_target_offset(ti, bi_sector);
}
static void flakey_map_bio(struct dm_target *ti, struct bio *bio)
{
struct flakey_c *fc = ti->private;
bio->bi_bdev = fc->dev->bdev;
if (bio_sectors(bio))
bio->bi_sector = flakey_map_sector(ti, bio->bi_sector);
}
static void corrupt_bio_data(struct bio *bio, struct flakey_c *fc)
{
unsigned bio_bytes = bio_cur_bytes(bio);
char *data = bio_data(bio);
/*
* Overwrite the Nth byte of the data returned.
*/
if (data && bio_bytes >= fc->corrupt_bio_byte) {
data[fc->corrupt_bio_byte - 1] = fc->corrupt_bio_value;
DMDEBUG("Corrupting data bio=%p by writing %u to byte %u "
"(rw=%c bi_rw=%lu bi_sector=%llu cur_bytes=%u)\n",
bio, fc->corrupt_bio_value, fc->corrupt_bio_byte,
(bio_data_dir(bio) == WRITE) ? 'w' : 'r',
bio->bi_rw, (unsigned long long)bio->bi_sector, bio_bytes);
}
}
static int flakey_map(struct dm_target *ti, struct bio *bio,
union map_info *map_context)
{
struct flakey_c *fc = ti->private;
unsigned elapsed;
/* Are we alive ? */
elapsed = (jiffies - fc->start_time) / HZ;
if (elapsed % (fc->up_interval + fc->down_interval) >= fc->up_interval) {
/*
* Flag this bio as submitted while down.
*/
map_context->ll = 1;
/*
* Map reads as normal.
*/
if (bio_data_dir(bio) == READ)
goto map_bio;
/*
* Drop writes?
*/
if (test_bit(DROP_WRITES, &fc->flags)) {
bio_endio(bio, 0);
return DM_MAPIO_SUBMITTED;
}
/*
* Corrupt matching writes.
*/
if (fc->corrupt_bio_byte && (fc->corrupt_bio_rw == WRITE)) {
if (all_corrupt_bio_flags_match(bio, fc))
corrupt_bio_data(bio, fc);
goto map_bio;
}
/*
* By default, error all I/O.
*/
return -EIO;
}
map_bio:
flakey_map_bio(ti, bio);
return DM_MAPIO_REMAPPED;
}
static int flakey_end_io(struct dm_target *ti, struct bio *bio,
int error, union map_info *map_context)
{
struct flakey_c *fc = ti->private;
unsigned bio_submitted_while_down = map_context->ll;
/*
* Corrupt successful READs while in down state.
* If flags were specified, only corrupt those that match.
*/
if (fc->corrupt_bio_byte && !error && bio_submitted_while_down &&
(bio_data_dir(bio) == READ) && (fc->corrupt_bio_rw == READ) &&
all_corrupt_bio_flags_match(bio, fc))
corrupt_bio_data(bio, fc);
return error;
}
static void flakey_status(struct dm_target *ti, status_type_t type,
char *result, unsigned maxlen)
{
unsigned sz = 0;
struct flakey_c *fc = ti->private;
unsigned drop_writes;
switch (type) {
case STATUSTYPE_INFO:
result[0] = '\0';
break;
case STATUSTYPE_TABLE:
DMEMIT("%s %llu %u %u ", fc->dev->name,
(unsigned long long)fc->start, fc->up_interval,
fc->down_interval);
drop_writes = test_bit(DROP_WRITES, &fc->flags);
DMEMIT("%u ", drop_writes + (fc->corrupt_bio_byte > 0) * 5);
if (drop_writes)
DMEMIT("drop_writes ");
if (fc->corrupt_bio_byte)
DMEMIT("corrupt_bio_byte %u %c %u %u ",
fc->corrupt_bio_byte,
(fc->corrupt_bio_rw == WRITE) ? 'w' : 'r',
fc->corrupt_bio_value, fc->corrupt_bio_flags);
break;
}
}
static int flakey_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg)
{
struct flakey_c *fc = ti->private;
struct dm_dev *dev = fc->dev;
int r = 0;
/*
* Only pass ioctls through if the device sizes match exactly.
*/
if (fc->start ||
ti->len != i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT)
r = scsi_verify_blk_ioctl(NULL, cmd);
return r ? : __blkdev_driver_ioctl(dev->bdev, dev->mode, cmd, arg);
}
static int flakey_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
struct bio_vec *biovec, int max_size)
{
struct flakey_c *fc = ti->private;
struct request_queue *q = bdev_get_queue(fc->dev->bdev);
if (!q->merge_bvec_fn)
return max_size;
bvm->bi_bdev = fc->dev->bdev;
bvm->bi_sector = flakey_map_sector(ti, bvm->bi_sector);
return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
}
static int flakey_iterate_devices(struct dm_target *ti, iterate_devices_callout_fn fn, void *data)
{
struct flakey_c *fc = ti->private;
return fn(ti, fc->dev, fc->start, ti->len, data);
}
static struct target_type flakey_target = {
.name = "flakey",
.version = {1, 2, 1},
.module = THIS_MODULE,
.ctr = flakey_ctr,
.dtr = flakey_dtr,
.map = flakey_map,
.end_io = flakey_end_io,
.status = flakey_status,
.ioctl = flakey_ioctl,
.merge = flakey_merge,
.iterate_devices = flakey_iterate_devices,
};
static int __init dm_flakey_init(void)
{
int r = dm_register_target(&flakey_target);
if (r < 0)
DMERR("register failed %d", r);
return r;
}
static void __exit dm_flakey_exit(void)
{
dm_unregister_target(&flakey_target);
}
/* Module hooks */
module_init(dm_flakey_init);
module_exit(dm_flakey_exit);
MODULE_DESCRIPTION(DM_NAME " flakey target");
MODULE_AUTHOR("Joe Thornber <[email protected]>");
MODULE_LICENSE("GPL");
| WhiteBearSolutions/WBSAirback | packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/drivers/md/dm-flakey.c | C | apache-2.0 | 9,957 |
/*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebDragClient.h"
#include "WebPage.h"
using namespace WebCore;
namespace WebKit {
void WebDragClient::willPerformDragDestinationAction(DragDestinationAction action, DragData*)
{
if (action == DragDestinationActionLoad)
m_page->willPerformLoadDragDestinationAction();
}
void WebDragClient::willPerformDragSourceAction(DragSourceAction, const IntPoint&, Clipboard*)
{
}
DragDestinationAction WebDragClient::actionMaskForDrag(DragData*)
{
return DragDestinationActionAny;
}
DragSourceAction WebDragClient::dragSourceActionMaskForPoint(const IntPoint& windowPoint)
{
return DragSourceActionAny;
}
#if !PLATFORM(MAC) && !PLATFORM(WIN)
void WebDragClient::startDrag(DragImageRef, const IntPoint&, const IntPoint&, Clipboard*, Frame*, bool)
{
}
#endif
void WebDragClient::dragControllerDestroyed()
{
delete this;
}
} // namespace WebKit
| mogoweb/webkit_for_android5.1 | webkit/Source/WebKit2/WebProcess/WebCoreSupport/WebDragClient.cpp | C++ | apache-2.0 | 2,250 |
<?php
include_once dirname(__FILE__) . '/../../../bootstrap/unit.php';
include_once dirname(__FILE__) . '/../../../bootstrap/database.php';
$t = new lime_test(16, new lime_output_color());
$table = Doctrine::getTable('MemberConfig');
$member1 = Doctrine::getTable('Member')->findOneByName('A');
$member2 = Doctrine::getTable('Member')->findOneByName('B');
//------------------------------------------------------------
$t->diag('MemberConfigTable');
$t->diag('MemberConfigTable::retrieveByNameAndMemberId()');
$result = $table->retrieveByNameAndMemberId('pc_address', 1);
$t->isa_ok($result, 'MemberConfig');
$result = $table->retrieveByNameAndMemberId('password', 1);
$t->isa_ok($result, 'MemberConfig');
//------------------------------------------------------------
$t->diag('MemberConfigTable::retrieveByNameAndValue()');
$result = $table->retrieveByNameAndValue('pc_address', '[email protected]');
$t->isa_ok($result, 'MemberConfig');
//------------------------------------------------------------
$t->diag('MemberConfigTable::retrievesByName()');
$result = $table->retrievesByName('pc_address');
$t->isa_ok($result, 'Doctrine_Collection');
//------------------------------------------------------------
$t->diag('MemberConfigTable::deleteDuplicatedPre()');
$memberConfig1 = $table->retrieveByNameAndMemberId('pc_address_pre', 2, true);
$memberConfig2 = $table->retrieveByNameAndMemberId('pc_address_pre', 3, true);
$t->isa_ok($memberConfig1, 'MemberConfig');
$t->isa_ok($memberConfig2, 'MemberConfig');
$table->deleteDuplicatedPre(2, 'pc_address', '[email protected]');
$memberConfig1 = $table->retrieveByNameAndMemberId('pc_address_pre', 2, true);
$memberConfig2 = $table->retrieveByNameAndMemberId('pc_address_pre', 3, true);
$t->ok(!$memberConfig1);
$t->ok(!$memberConfig2);
//------------------------------------------------------------
$t->diag('MemberConfigTable::setValue()');
$memberConfig1 = $table->retrieveByNameAndMemberId('test1', 1);
$t->ok(!$memberConfig1);
$table->setValue(1, 'test1', 'bar');
$memberConfig1 = $table->retrieveByNameAndMemberId('test1', 1);
$t->isa_ok($memberConfig1, 'MemberConfig');
$memberConfig2 = $table->retrieveByNameAndMemberId('test2', 1);
$t->ok(!$memberConfig2);
$table->setValue(1, 'test2', '1989-01-08', true);
$memberConfig2 = $table->retrieveByNameAndMemberId('test2', 1);
$t->isa_ok($memberConfig2, 'MemberConfig');
//------------------------------------------------------------
$t->diag('ACL Test');
$memberConfig = $table->retrieveByNameAndMemberId('pc_address', 1);
$t->ok($memberConfig->isAllowed($member1, 'view'));
$t->ok(!$memberConfig->isAllowed($member2, 'view'));
$t->ok($memberConfig->isAllowed($member1, 'edit'));
$t->ok(!$memberConfig->isAllowed($member2, 'edit'));
| cripure/openpne3 | test/unit/model/doctrine/MemberConfigTableTest.php | PHP | apache-2.0 | 2,742 |
/*
* Copyright 2013 MovingBlocks
*
* 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.terasology.utilities.gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import org.terasology.utilities.Assets;
import org.terasology.assets.Asset;
import java.lang.reflect.Type;
/**
*/
public class AssetTypeAdapter<V extends Asset> implements JsonDeserializer<V> {
private Class<V> type;
public AssetTypeAdapter(Class<V> type) {
this.type = type;
}
@Override
public V deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return type.cast(Assets.get(json.getAsString(), type).orElse(null));
}
}
| kaen/Terasology | engine/src/main/java/org/terasology/utilities/gson/AssetTypeAdapter.java | Java | apache-2.0 | 1,328 |
package org.zstack.core.cloudbus;
import com.rabbitmq.client.Connection;
import org.zstack.header.Component;
import org.zstack.header.Service;
public interface CloudBusIN extends CloudBus {
Connection getConnection();
void activeService(Service serv);
void activeService(String id);
void deActiveService(Service serv);
void deActiveService(String id);
}
| HeathHose/zstack | core/src/main/java/org/zstack/core/cloudbus/CloudBusIN.java | Java | apache-2.0 | 392 |
# 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.
from neutron.common import exceptions
class CallbackWrongResourceType(exceptions.NeutronException):
message = _('Callback for %(resource_type)s returned wrong resource type')
class CallbackNotFound(exceptions.NeutronException):
message = _('Callback for %(resource_type)s not found')
class CallbacksMaxLimitReached(exceptions.NeutronException):
message = _("Cannot add multiple callbacks for %(resource_type)s")
| barnsnake351/neutron | neutron/api/rpc/callbacks/exceptions.py | Python | apache-2.0 | 1,003 |
/*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2014 Broadleaf Commerce
* %%
* 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.
* #L%
*/
package org.broadleafcommerce.common.i18n.service.type;
import org.broadleafcommerce.common.BroadleafEnumerationType;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* An extensible enumeration of ISO Code Status Types.
* See {@link http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2}
*
* @author Elbert Bautista (elbertbautista)
*/
public class ISOCodeStatusType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, ISOCodeStatusType> TYPES = new LinkedHashMap<String, ISOCodeStatusType>();
public static final ISOCodeStatusType OFFICIALLY_ASSIGNED = new ISOCodeStatusType("OFFICIALLY_ASSIGNED", "Officially assigned: assigned to a country, territory, or area of geographical interest.");
public static final ISOCodeStatusType USER_ASSIGNED = new ISOCodeStatusType("USER_ASSIGNED", "User-assigned: free for assignment at the disposal of users.");
public static final ISOCodeStatusType EXCEPTIONALLY_RESERVED = new ISOCodeStatusType("EXCEPTIONALLY_RESERVED", "Exceptionally reserved: reserved on request for restricted use.");
public static final ISOCodeStatusType TRANSITIONALLY_RESERVED = new ISOCodeStatusType("TRANSITIONALLY_RESERVED", "Transitionally reserved: deleted from ISO 3166-1 but reserved transitionally.");
public static final ISOCodeStatusType INDETERMINATELY_RESERVED = new ISOCodeStatusType("INDETERMINATELY_RESERVED", "Indeterminately reserved: used in coding systems associated with ISO 3166-1.");
public static final ISOCodeStatusType NOT_USED = new ISOCodeStatusType("NOT_USED", "Not used: not used in ISO 3166-1 in deference to intergovernmental intellectual property organisation names.");
public static final ISOCodeStatusType UNASSIGNED = new ISOCodeStatusType("UNASSIGNED", "Unassigned: free for assignment by the ISO 3166/MA only.");
public static ISOCodeStatusType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public ISOCodeStatusType() {
//do nothing
}
public ISOCodeStatusType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!getClass().isAssignableFrom(obj.getClass()))
return false;
ISOCodeStatusType other = (ISOCodeStatusType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| liqianggao/BroadleafCommerce | common/src/main/java/org/broadleafcommerce/common/i18n/service/type/ISOCodeStatusType.java | Java | apache-2.0 | 3,971 |
// Copyright 2014 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 COMPONENTS_POLICY_CORE_COMMON_PROXY_POLICY_PROVIDER_H_
#define COMPONENTS_POLICY_CORE_COMMON_PROXY_POLICY_PROVIDER_H_
#include "base/macros.h"
#include "components/policy/core/common/configuration_policy_provider.h"
#include "components/policy/policy_export.h"
namespace policy {
// A policy provider implementation that acts as a proxy for another policy
// provider, swappable at any point.
//
// Note that ProxyPolicyProvider correctly forwards RefreshPolicies() calls to
// the delegate if present. If there is no delegate, the refresh results in an
// immediate (empty) policy update.
//
// Furthermore, IsInitializationComplete() is implemented trivially - it always
// returns true. Given that the delegate may be swapped at any point, there's no
// point in trying to carry over initialization status from the delegate.
//
// This policy provider implementation is used to inject browser-global policy
// originating from the user policy configured on the primary Chrome OS user
// (i.e. the user logging in from the login screen). This way, policy settings
// on the primary user propagate into g_browser_process->local_state_().
//
// The bizarre situation of user-scoped policy settings which are implemented
// browser-global wouldn't exist in an ideal world. However, for historic
// and technical reasons there are policy settings that are scoped to the user
// but are implemented to take effect for the entire browser instance. A good
// example for this are policies that affect the Chrome network stack in areas
// where there's no profile-specific context. The meta data in
// policy_templates.json allows to identify the policies in this bucket; they'll
// have per_profile set to False, supported_on including chrome_os, and
// dynamic_refresh set to True.
class POLICY_EXPORT ProxyPolicyProvider
: public ConfigurationPolicyProvider,
public ConfigurationPolicyProvider::Observer {
public:
ProxyPolicyProvider();
~ProxyPolicyProvider() override;
// Updates the provider this proxy delegates to.
void SetDelegate(ConfigurationPolicyProvider* delegate);
// ConfigurationPolicyProvider:
void Shutdown() override;
void RefreshPolicies() override;
// ConfigurationPolicyProvider::Observer:
void OnUpdatePolicy(ConfigurationPolicyProvider* provider) override;
private:
ConfigurationPolicyProvider* delegate_;
DISALLOW_COPY_AND_ASSIGN(ProxyPolicyProvider);
};
} // namespace policy
#endif // COMPONENTS_POLICY_CORE_COMMON_PROXY_POLICY_PROVIDER_H_
| ssaroha/node-webrtc | third_party/webrtc/include/chromium/src/components/policy/core/common/proxy_policy_provider.h | C | bsd-2-clause | 2,681 |
// Copyright 2014 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 COMPONENTS_NACL_RENDERER_NEXE_PROGRESS_EVENT_H_
#define COMPONENTS_NACL_RENDERER_NEXE_PROGRESS_EVENT_H_
#include <stdint.h>
#include <string>
#include "components/nacl/renderer/ppb_nacl_private.h"
#include "ppapi/c/pp_instance.h"
namespace nacl {
// See http://www.w3.org/TR/progress-events/ for more details on progress
// events.
struct ProgressEvent {
explicit ProgressEvent(PP_NaClEventType event_type_param)
: event_type(event_type_param),
length_is_computable(false),
loaded_bytes(0),
total_bytes(0) {
}
ProgressEvent(PP_NaClEventType event_type_param,
const std::string& resource_url_param,
bool length_is_computable_param,
uint64_t loaded_bytes_param,
uint64_t total_bytes_param)
: event_type(event_type_param),
resource_url(resource_url_param),
length_is_computable(length_is_computable_param),
loaded_bytes(loaded_bytes_param),
total_bytes(total_bytes_param) {
}
PP_NaClEventType event_type;
std::string resource_url;
bool length_is_computable;
uint64_t loaded_bytes;
uint64_t total_bytes;
};
// Dispatches a progress event to the DOM frame corresponding to the specified
// plugin instance.
// This posts a task to the main thread to perform the actual dispatch, since
// it's usually intended for progress events to be dispatched after all other
// state changes are handled.
void DispatchProgressEvent(PP_Instance instance, const ProgressEvent& event);
} // namespace nacl
#endif // COMPONENTS_NACL_RENDERER_NEXE_PROGRESS_EVENT_H_
| ssaroha/node-webrtc | third_party/webrtc/include/chromium/src/components/nacl/renderer/progress_event.h | C | bsd-2-clause | 1,780 |
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2009, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
namespace lithium\tests\mocks\data\model;
class MockDatabaseTag extends \lithium\tests\mocks\data\MockBase {
public static $connection = null;
public $hasMany = array('MockDatabaseTagging');
protected $_meta = array('connection' => false, 'key' => 'id');
protected $_schema = array(
'id' => array('type' => 'integer'),
'title' => array('type' => 'string'),
'created' => array('type' => 'datetime')
);
}
?> | qoqa/lithium | tests/mocks/data/model/MockDatabaseTag.php | PHP | bsd-3-clause | 633 |
#if !defined(__CINT__) || defined(__MAKECINT_)
#include "AliFemtoManager.h"
#include "AliFemtoEventReaderESDChain.h"
#include "AliFemtoEventReaderESDChainKine.h"
#include "AliFemtoEventReaderAODChain.h"
#include "AliFemtoSimpleAnalysis.h"
#include "AliFemtoBasicEventCut.h"
#include "AliFemtoESDTrackCut.h"
#include "AliFemtoCorrFctn.h"
#include "AliFemtoCutMonitorParticleYPt.h"
#include "AliFemtoCutMonitorParticleVertPos.h"
#include "AliFemtoCutMonitorParticleMomRes.h"
#include "AliFemtoCutMonitorParticlePID.h"
#include "AliFemtoCutMonitorEventMult.h"
#include "AliFemtoCutMonitorEventVertex.h"
#include "AliFemtoShareQualityTPCEntranceSepPairCut.h"
#include "AliFemtoPairCutAntiGamma.h"
#include "AliFemtoPairCutRadialDistance.h"
#include "AliFemtoQinvCorrFctn.h"
#include "AliFemtoCorrFctnNonIdDR.h"
#include "AliFemtoShareQualityCorrFctn.h"
#include "AliFemtoTPCInnerCorrFctn.h"
#include "AliFemtoVertexMultAnalysis.h"
#include "AliFemtoCorrFctn3DSpherical.h"
#include "AliFemtoChi2CorrFctn.h"
#include "AliFemtoCorrFctnTPCNcls.h"
#include "AliFemtoBPLCMS3DCorrFctn.h"
#include "AliFemtoCorrFctn3DLCMSSym.h"
#include "AliFemtoCorrFctnDirectYlm.h"
#include "AliFemtoCutMonitorParticlePtPDG.h"
#include "AliFemtoKTPairCut.h"
#include "AliFemtoPairCutPt.h"
#endif
#include <stdio.h>
#include <string.h>
//________________________________________________________________________
AliFemtoManager* ConfigFemtoAnalysis(const char* params) {
double PionMass = 0.13956995;
double KaonMass = 0.493677;
double ProtonMass = 0.938272013;
double LambdaMass = 1.115683;
double XiMass = 1.32171;
const int numOfMultBins = 5;
const int numOfChTypes = 28;
const int numOfkTbins = 5;
char *par = new char[strlen(params)+1];
strcpy(par,params);
char *parameter[21];
if(strlen(params)!=0)
{
parameter[0] = strtok(par, ","); // Splits spaces between words in params
cout<<"Parameter [0] (filterbit):"<<parameter[0]<<endl; // Writes first parameter
parameter[1] = strtok(NULL, ",");
cout<<"Parameter [1] (ktdep):"<<parameter[1]<<" "<<endl;
parameter[2] = strtok(NULL, ",");
cout<<"Parameter [2] (multdep):"<<parameter[2]<<" "<<endl;
parameter[3] = strtok(NULL, ",");
cout<<"Parameter [3]: (MinPlpContribSPD)"<<parameter[3]<<" "<<endl;
parameter[4] = strtok(NULL, ",");
cout<<"Parameter [4]: (multbino)"<<parameter[4]<<" "<<endl;
parameter[5] = strtok(NULL, ",");
cout<<"Parameter [5]: (zvertbino)"<<parameter[5]<<" "<<endl;
parameter[6] = strtok(NULL, ",");
cout<<"Parameter [6]: (ifGlobalTracks=true/false)"<<parameter[6]<<" "<<endl;
parameter[7] = strtok(NULL, ",");
cout<<"Parameter [7]: (shareQuality)"<<parameter[7]<<" "<<endl;
parameter[8] = strtok(NULL, ",");
cout<<"Parameter [8]: (shareFraction)"<<parameter[8]<<" "<<endl;
parameter[9] = strtok(NULL, ",");
cout<<"Parameter [9]: (ifElectronRejection)"<<parameter[9]<<" "<<endl;
parameter[10] = strtok(NULL, ",");
cout<<"Parameter [10]: (nSigma)"<<parameter[10]<<" "<<endl;
parameter[11] = strtok(NULL, ",");
cout<<"Parameter [12]: (etaMin)"<<parameter[11]<<" "<<endl;
parameter[12] = strtok(NULL, ",");
cout<<"Parameter [12]: (etaMax)"<<parameter[12]<<" "<<endl;
parameter[13] = strtok(NULL, ",");
cout<<"Parameter [13]: (ispileup)"<<parameter[13]<<" "<<endl;
parameter[14] = strtok(NULL, ",");
cout<<"Parameter [14]: (max pT)"<<parameter[14]<<" "<<endl;
parameter[15] = strtok(NULL, ",");
cout<<"Parameter [15]: (SetMostProbable 1)"<<parameter[15]<<" "<<endl;
parameter[16] = strtok(NULL, ",");
cout<<"Parameter [16]: (SetMostProbable 2)"<<parameter[16]<<" "<<endl;
parameter[17] = strtok(NULL, ",");
cout<<"Parameter [17]: (SetMostProbable 3)"<<parameter[17]<<" "<<endl;
parameter[18] = strtok(NULL, ",");
cout<<"Parameter [18]: (FILE no)"<<parameter[18]<<" "<<endl;
}
int filterbit = atoi(parameter[0]); //96 / 768 / 128
int runktdep = atoi(parameter[1]); //0
int runmultdep = atoi(parameter[2]); //0
int minPlpContribSPD = atoi(parameter[3]); //3
int multbino = atoi(parameter[4]); //30
int zvertbino = atoi(parameter[5]); //10
Bool_t ifGlobalTracks=kFALSE; if(atoi(parameter[6]))ifGlobalTracks=kTRUE;//kTRUE
double shareQuality = atof(parameter[7]); //0.00
double shareFraction = atof(parameter[8]); //0.05
bool ifElectronRejection = atoi(parameter[9]); //true
double nSigmaVal = atof(parameter[10]); //3.0
double nEtaMin = atof(parameter[11]); //-0.8
double nEtaMax = atof(parameter[12]); //0.8
bool ifIsPileUp = atoi(parameter[13]); //true
double maxPt = atof(parameter[14]); //4.0
int setMostProb1 = atoi(parameter[15]);
int setMostProb2 = atoi(parameter[16]);
int setMostProb3 = atoi(parameter[17]);
int fileNo = atoi(parameter[18]);
char* fileName[300];
//if(fileNo==0)
// strcpy(fileName,"alien:///alice/cern.ch/user/m/majanik/2014/DEtaDPhi/Trains/Corrections/Train7Light/1Dmap_FB96_MCOnly_DoubleCounting.root");
//cout<<"Filename: "<<Form("%s",fileName)<<endl;
printf("*** Connect to AliEn ***\n");
TGrid::Connect("alien://");
int runmults[numOfMultBins] = {0, 0, 0, 0, 1};
int multbins[numOfMultBins+1] = {2, 20, 50,150,2,15000};
int runch[numOfChTypes] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
const char *chrgs[numOfChTypes] = { "PP", "aPaP", "PaP", "KpKp", "KmKm", "KpKm", "PIpPIp", "PImPIm", "PIpPIm", "all", "plus", "minus", "mixed", "V0PL","V0PAL","V0APL","V0APAL","V0LL","V0ALAL","V0LAL","PXim","aPXim","PXip","aPXip","POmegam","POmegap","aPOmegam","aPOmegap" };
//int runktdep = 1;
double ktrng[numOfkTbins+1] = {0.0, 0, 0, 0, 0, 0};
double ktrngAll[numOfkTbins+1] = {0.0, 1.0, 2.0, 3.0, 4.0, 100.0};
double ktrngPion[numOfkTbins+1] = {0.0, 0.8, 1.2, 1.4, 2.5, 100.0};
double ktrngKaon[numOfkTbins+1] = {0.0, 1.5, 2.5, 3.5, 100.0, 0};
double ktrngProton[numOfkTbins+1] = {0.0, 2.75, 100, 0, 0, 0};
int runqinv = 1;
int runshlcms = 1;// 0:PRF(PAP), 1:LCMS(PP,APAP)
int runtype = 0; // Types 0 - global, 1 - ITS only, 2 - TPC Inner //global tracks ->mfit ITS+TPC
int owncuts = 1;
int owndca = 1;
int gammacut = 0; // cut na ee z gamma
double shqmax = 1.0;
int nbinssh = 100;
// AliFemtoEventReaderESDChain *Reader = new AliFemtoEventReaderESDChain();
// Reader->SetUseMultiplicity(AliFemtoEventReaderESDChain::kReferenceITSTPC);
//AliFemtoEventReaderAODChain *Reader = new AliFemtoEventReaderAODChain();
//Reader->SetFilterMask(96);
//Reader->SetDCAglobalTrack(kTRUE); //false for FB7, true for the rest //we do not use DCA at all
//Reader->SetUseMultiplicity(AliFemtoEventReaderAOD::kReference);
// Reader->SetMinPlpContribSPD(3);
// Reader->SetIsPileUpEvent(kTRUE);
//AliFemtoEventReaderKinematicsChain* Reader=new AliFemtoEventReaderKinematicsChain();
AliFemtoEventReaderAODKinematicsChain *Reader = new AliFemtoEventReaderAODKinematicsChain();
AliFemtoManager* Manager = new AliFemtoManager();
Manager->SetEventReader(Reader);
AliFemtoVertexMultAnalysis *anetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoBasicEventCut *mecetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorEventMult *cutPassEvMetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorEventMult *cutFailEvMetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorEventVertex *cutPassEvVetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorEventVertex *cutFailEvVetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoMCTrackCut *dtc1etaphitpc[numOfMultBins*numOfChTypes];
AliFemtoMCTrackCut *dtc2etaphitpc[numOfMultBins*numOfChTypes];
AliFemtoMCTrackCut *dtc3etaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticleYPt *cutPass1YPtetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticleYPt *cutFail1YPtetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticlePID *cutPass1PIDetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticlePID *cutFail1PIDetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticleYPt *cutPass2YPtetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticleYPt *cutFail2YPtetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticlePID *cutPass2PIDetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticlePID *cutFail2PIDetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticleYPt *cutPass3YPtetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticleYPt *cutFail3YPtetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticlePID *cutPass3PIDetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoCutMonitorParticlePID *cutFail3PIDetaphitpc[numOfMultBins*numOfChTypes];
// AliFemtoShareQualityTPCEntranceSepPairCut *sqpcetaphitpcsame[numOfMultBins*numOfChTypes];
//AliFemtoPairCutAntiGamma *sqpcetaphitpc[numOfMultBins*numOfChTypes];
//AliFemtoPairCutRadialDistance *sqpcetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoPairCutAntiGamma *sqpcetaphitpc[numOfMultBins*numOfChTypes];
// AliFemtoChi2CorrFctn *cchiqinvetaphitpc[numOfMultBins*numOfChTypes];
AliFemtoPairCutPt *ktpcuts[numOfMultBins*numOfChTypes*numOfkTbins];
AliFemtoQinvCorrFctn *cqinvkttpc[numOfMultBins*numOfChTypes*numOfkTbins];
AliFemtoQinvCorrFctn *cqinvtpc[numOfMultBins*numOfChTypes];
AliFemtoCorrFctnDEtaDPhi *cdedpetaphi[numOfMultBins*numOfChTypes];
AliFemtoCorrFctnDEtaDPhi *cdedpetaphiPt[numOfMultBins*numOfChTypes*numOfkTbins];
AliFemtoCorrFctnNonIdDR *cnonidtpc[numOfMultBins*numOfChTypes];
// *** Third QA task - HBT analysis with all pair cuts off, TPC only ***
// *** Begin pion-pion (positive) analysis ***
int aniter = 0;
for (int imult = 0; imult < numOfMultBins; imult++)
{
if (runmults[imult])
{
for (int ichg = 0; ichg < numOfChTypes; ichg++)
{
if (runch[ichg])
{
aniter = ichg * numOfMultBins + imult;
anetaphitpc[aniter] = new AliFemtoVertexMultAnalysis(zvertbino, -10.0, 10.0, multbino, multbins[imult], multbins[imult+1]);
anetaphitpc[aniter]->SetNumEventsToMix(10);
anetaphitpc[aniter]->SetMinSizePartCollection(1);
anetaphitpc[aniter]->SetVerboseMode(kFALSE);//~~~~~~~~~~~~~~~~
//*** Event cut ***
mecetaphitpc[aniter] = new AliFemtoBasicEventCut();
mecetaphitpc[aniter]->SetEventMult(0.001,100000);
mecetaphitpc[aniter]->SetVertZPos(-10,10);//cm
//****** event monitors **********
cutPassEvMetaphitpc[aniter] = new AliFemtoCutMonitorEventMult(Form("cutPass%stpcM%i", chrgs[ichg], imult));
cutFailEvMetaphitpc[aniter] = new AliFemtoCutMonitorEventMult(Form("cutFail%stpcM%i", chrgs[ichg], imult));
mecetaphitpc[aniter]->AddCutMonitor(cutPassEvMetaphitpc[aniter], cutFailEvMetaphitpc[aniter]);
//cutPassEvVetaphitpc[aniter] = new AliFemtoCutMonitorEventVertex(Form("cutPass%stpcM%i", chrgs[ichg], imult));
//cutFailEvVetaphitpc[aniter] = new AliFemtoCutMonitorEventVertex(Form("cutFail%stpcM%i", chrgs[ichg], imult));
//mecetaphitpc[aniter]->AddCutMonitor(cutPassEvVetaphitpc[aniter], cutFailEvVetaphitpc[aniter]);
// ***** single particle track cuts *********
dtc1etaphitpc[aniter] = new AliFemtoMCTrackCut();
dtc2etaphitpc[aniter] = new AliFemtoMCTrackCut();
dtc3etaphitpc[aniter] = new AliFemtoMCTrackCut();
dtc1etaphitpc[aniter]->SetCharge(1.0);
dtc2etaphitpc[aniter]->SetCharge(-1.0);
dtc1etaphitpc[aniter]->SetEta(nEtaMin,nEtaMax);
dtc2etaphitpc[aniter]->SetEta(nEtaMin,nEtaMax);
dtc3etaphitpc[aniter]->SetEta(nEtaMin,nEtaMax);
// dtc1etaphitpc[aniter]->SetElectronRejection(true);
// dtc2etaphitpc[aniter]->SetElectronRejection(true);
// dtc3etaphitpc[aniter]->SetElectronRejection(true);
if (ichg == 0 ||ichg == 1 ||ichg == 2)//protons 0-2
{
dtc1etaphitpc[aniter]->SetPt(0.5,maxPt);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt);
dtc1etaphitpc[aniter]->SetPDG(2212);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if (ichg == 3 ||ichg == 4 ||ichg == 5)//kaons 3-5
{
dtc1etaphitpc[aniter]->SetPt(0.3,maxPt);
dtc2etaphitpc[aniter]->SetPt(0.3,maxPt);
dtc1etaphitpc[aniter]->SetPDG(321);
dtc2etaphitpc[aniter]->SetPDG(321);
}
if (ichg == 6 ||ichg == 7 ||ichg == 8)//pions 6-8
{
dtc1etaphitpc[aniter]->SetPt(0.2,maxPt);
dtc2etaphitpc[aniter]->SetPt(0.2,maxPt);
dtc1etaphitpc[aniter]->SetPDG(211);
dtc2etaphitpc[aniter]->SetPDG(211);
}
if (ichg == 9)//all
{
dtc3etaphitpc[aniter]->SetPt(0.2,maxPt);
}
if (ichg == 10 ||ichg == 11 ||ichg == 12)//plus,minus,mixed
{
dtc1etaphitpc[aniter]->SetPt(0.2,maxPt);
dtc2etaphitpc[aniter]->SetPt(0.2,maxPt);
}
if(ichg >= 13 && ichg <=16){
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //lambda
dtc1etaphitpc[aniter]->SetCharge(0.0);
if(ichg == 14 || ichg ==16) dtc1etaphitpc[aniter]->SetPDG(-3122);
else dtc1etaphitpc[aniter]->SetPDG(3122);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt);//proton
dtc2etaphitpc[aniter]->SetPDG(2212);
if(ichg == 15 || ichg ==16) dtc2etaphitpc[aniter]->SetCharge(-1.0);
else dtc2etaphitpc[aniter]->SetCharge(1.0);
}
if (ichg == 17 ||ichg == 18 ||ichg == 19)//lambdas
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt);
dtc2etaphitpc[aniter]->SetPt(0.6,maxPt);
dtc1etaphitpc[aniter]->SetCharge(0.0);
dtc2etaphitpc[aniter]->SetCharge(0.0);
dtc1etaphitpc[aniter]->SetPDG(3122);
dtc2etaphitpc[aniter]->SetPDG(-3122);
}
if(ichg == 20) //PXim - nie dziala
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi-
dtc1etaphitpc[aniter]->SetCharge(-1.0);
dtc1etaphitpc[aniter]->SetPDG(3312);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //proton
dtc2etaphitpc[aniter]->SetCharge(1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if(ichg == 21) //aPXim
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi-
dtc1etaphitpc[aniter]->SetCharge(-1.0);
dtc1etaphitpc[aniter]->SetPDG(3312);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //anti-proton
dtc2etaphitpc[aniter]->SetCharge(-1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if(ichg == 22) //PXip
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi+
dtc1etaphitpc[aniter]->SetCharge(1.0);
dtc1etaphitpc[aniter]->SetPDG(-3312);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //proton
dtc2etaphitpc[aniter]->SetCharge(1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if(ichg == 23) //aPXip - nie dziala
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi+
dtc1etaphitpc[aniter]->SetCharge(1.0);
dtc1etaphitpc[aniter]->SetPDG(-3312);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //anti-proton
dtc2etaphitpc[aniter]->SetCharge(-1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if(ichg == 24) //POmegam
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi-
dtc1etaphitpc[aniter]->SetCharge(-1.0);
dtc1etaphitpc[aniter]->SetPDG(3334);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //proton
dtc2etaphitpc[aniter]->SetCharge(1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if(ichg == 25) //aPOmegam
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi-
dtc1etaphitpc[aniter]->SetCharge(-1.0);
dtc1etaphitpc[aniter]->SetPDG(3334);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //anti-proton
dtc2etaphitpc[aniter]->SetCharge(-1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if(ichg == 26) //POmegap
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi+
dtc1etaphitpc[aniter]->SetCharge(1.0);
dtc1etaphitpc[aniter]->SetPDG(-3334);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //proton
dtc2etaphitpc[aniter]->SetCharge(1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
if(ichg == 27) //aPOmegap
{
dtc1etaphitpc[aniter]->SetPt(0.6,maxPt); //Xi+
dtc1etaphitpc[aniter]->SetCharge(1.0);
dtc1etaphitpc[aniter]->SetPDG(-3334);
dtc2etaphitpc[aniter]->SetPt(0.5,maxPt); //anti-proton
dtc2etaphitpc[aniter]->SetCharge(-1.0);
dtc2etaphitpc[aniter]->SetPDG(2212);
}
//**************** track Monitors ***************
if(0)//ichg>8)
{
cutPass3YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutPass%stpcM%i", chrgs[ichg], imult),PionMass);
cutFail3YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutFail%stpcM%i", chrgs[ichg], imult),PionMass);
if(ichg==9) dtc3etaphitpc[aniter]->AddCutMonitor(cutPass3YPtetaphitpc[aniter], cutFail3YPtetaphitpc[aniter]);
if(ichg==0||ichg==3||ichg==6||ichg==10) dtc1etaphitpc[aniter]->AddCutMonitor(cutPass3YPtetaphitpc[aniter], cutFail3YPtetaphitpc[aniter]);
//if(ichg==1||ichg==4||ichg==7||ichg==11) dtc2etaphitpc[aniter]->AddCutMonitor(cutPass3YPtetaphitpc[aniter], cutFail3YPtetaphitpc[aniter]);
// cutPass1PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutPass%stpcM%i", chrgs[ichg], imult),0);
// cutFail1PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutFail%stpcM%i", chrgs[ichg], imult),0);
// if(ichg==0||ichg==3||ichg==6||ichg==10) dtc1etaphitpc[aniter]->AddCutMonitor(cutPass1PIDetaphitpc[aniter], cutFail1PIDetaphitpc[aniter]);
}
//******** Two - track cuts ************
sqpcetaphitpc[aniter] = new AliFemtoPairCutAntiGamma();
//sqpcetaphitpc[aniter] = new AliFemtoPairCutRadialDistance();
sqpcetaphitpc[aniter]->SetDataType(AliFemtoPairCut::kKine);
/*
sqpcetaphitpc[aniter]->SetShareQualityMax(0.0); // two track cuts on splitting and merging //1- wylaczany 0 -wlaczany
sqpcetaphitpc[aniter]->SetShareFractionMax(0.05); // ile moga miec wspolnych klastrow //1 - wylaczany, 0.05 - wlaczany
sqpcetaphitpc[aniter]->SetRemoveSameLabel(kFALSE);
sqpcetaphitpc[aniter]->SetMaximumRadius(0.82);
sqpcetaphitpc[aniter]->SetMinimumRadius(0.8);
sqpcetaphitpc[aniter]->SetPhiStarDifferenceMinimum(0.02);
sqpcetaphitpc[aniter]->SetEtaDifferenceMinimum(0.02);
if (gammacut == 0)
{
sqpcetaphitpc[aniter]->SetMaxEEMinv(0.0);
sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.0);
}
else if (gammacut == 1)
{
sqpcetaphitpc[aniter]->SetMaxEEMinv(0.002);
sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.008);
}
*/
// sqpcetaphitpc[aniter]->SetTPCEntranceSepMinimum(1.5);
// sqpcetaphitpc[aniter]->SetRadialDistanceMinimum(0.12, 0.03);
// sqpcetaphitpc[aniter]->SetEtaDifferenceMinimum(0.02);
//***** Setting cuts ***********
// setting event cut
anetaphitpc[aniter]->SetEventCut(mecetaphitpc[aniter]);
//setting single track cuts
if(ichg==0 || ichg==3 || ichg==6 || ichg==10 || ichg==17) //positive like-sign
{
anetaphitpc[aniter]->SetFirstParticleCut(dtc1etaphitpc[aniter]);
anetaphitpc[aniter]->SetSecondParticleCut(dtc1etaphitpc[aniter]);
}
if(ichg==1 || ichg==4 || ichg==7 || ichg==11 || ichg == 18)//negative like-sign
{
anetaphitpc[aniter]->SetFirstParticleCut(dtc2etaphitpc[aniter]);
anetaphitpc[aniter]->SetSecondParticleCut(dtc2etaphitpc[aniter]);
}
if(ichg==2 || ichg==5 || ichg==8 || ichg==12 || (ichg >= 13 && ichg <=16) || ichg >= 19)//unlike-sign + proton/lambda
{
anetaphitpc[aniter]->SetFirstParticleCut(dtc1etaphitpc[aniter]);
anetaphitpc[aniter]->SetSecondParticleCut(dtc2etaphitpc[aniter]);
}
if(ichg==9) //all
{
anetaphitpc[aniter]->SetFirstParticleCut(dtc3etaphitpc[aniter]);
anetaphitpc[aniter]->SetSecondParticleCut(dtc3etaphitpc[aniter]);
}
//setting two-track cuts
anetaphitpc[aniter]->SetPairCut(sqpcetaphitpc[aniter]);
//**** Correlation functions *******
if(ichg >= 13)
cdedpetaphi[aniter] = new AliFemtoCorrFctnDEtaDPhi(Form("cdedp%stpcM%i", chrgs[ichg], imult),23, 23);
else
cdedpetaphi[aniter] = new AliFemtoCorrFctnDEtaDPhi(Form("cdedp%stpcM%i", chrgs[ichg], imult),29, 29);
anetaphitpc[aniter]->AddCorrFctn(cdedpetaphi[aniter]);
/*
if(ichg==0 || ichg==1 || ichg==3 || ichg==4 || ichg==6 || ichg==7 || ichg==9 || ichg==10 || ichg==11 || ichg==12 || ichg==17 || ichg==18) //PP, aPaP, LL, ALAL
{
cqinvtpc[aniter] = new AliFemtoQinvCorrFctn(Form("cqinv%stpcM%i", chrgs[ichg], imult),nbinssh,0.0,shqmax); //femto qinv, for identical mass particles
anetaphitpc[aniter]->AddCorrFctn(cqinvtpc[aniter]);
}
else //PaP, PL, APL, PAL, APAL, LAL
{
cnonidtpc[aniter] = new AliFemtoCorrFctnNonIdDR(Form("cnonid%stpcM%i", chrgs[ichg], imult), nbinssh, 0.0,shqmax); //for non-identical partcles
anetaphitpc[aniter]->AddCorrFctn(cnonidtpc[aniter]);
}
*/
if (runktdep)
{
if(ichg<=2){
for(int kit=0;kit<=numOfkTbins;kit++)
ktrng[kit]=ktrngProton[kit];
}
else if(ichg>2&&ichg<6){
for(int kit=0;kit<=numOfkTbins;kit++)
ktrng[kit]=ktrngKaon[kit];
}
else if(ichg>=6&&ichg<=8){
for(int kit=0;kit<=numOfkTbins;kit++)
ktrng[kit]=ktrngPion[kit];
}
else if(ichg>=9){
for(int kit=0;kit<=numOfkTbins;kit++)
ktrng[kit]=ktrngAll[kit];
}
int ktm;
for (int ikt=0; ikt<numOfkTbins; ikt++)
{
if(ktrng[ikt+1]==0) continue;
ktm = aniter * numOfkTbins + ikt;
ktpcuts[ktm] = new AliFemtoPairCutPt(ktrng[ikt], ktrng[ikt+1]);
//cqinvkttpc[ktm] = new AliFemtoQinvCorrFctn(Form("cqinv%stpcM%ikT%i", chrgs[ichg], imult, ikt),nbinssh,0.0,(imult>6)?shqmax*2.5:shqmax);
//cqinvkttpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]);
//anetaphitpc[aniter]->AddCorrFctn(cqinvkttpc[ktm]);
cdedpetaphiPt[ktm] = new AliFemtoCorrFctnDEtaDPhi(Form("cdedp%stpcM%ipT%i", chrgs[ichg], imult,ikt),23, 23);
cdedpetaphiPt[ktm]->SetPairSelectionCut(ktpcuts[ktm]);
anetaphitpc[aniter]->AddCorrFctn(cdedpetaphiPt[ktm]);
}
}
Manager->AddAnalysis(anetaphitpc[aniter]);
}
}
}
}
return Manager;
}
| fcolamar/AliPhysics | PWGCF/FEMTOSCOPY/macros/Train/DEtaDPhi_GM/MCtruth/Xi/ConfigFemtoAnalysis.C | C++ | bsd-3-clause | 23,781 |
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Grid Layout Test: baseline context and self alignment</title>
<link rel="author" title="Oriol Brufau" href="mailto:[email protected]" />
<link rel="help" href="https://drafts.csswg.org/css-grid/#alignment">
<link rel="help" href="https://drafts.csswg.org/css-align-3/#baseline-align-self">
<link rel="help" href="https://drafts.csswg.org/css-align-3/#align-by-baseline">
<link rel="help" href="https://drafts.csswg.org/css-align-3/#align-items-property">
<link rel="help" href="https://drafts.csswg.org/css-align-3/#align-self-property">
<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1121761">
<link rel="match" href="grid-self-baseline-008-ref.html">
<link rel="stylesheet" href="/css/support/alignment.css">
<meta name="assert" content="Test baseline alignment with percentage track sizing functions and grid items being or containing replaced elements with aspect ratio and percentage sizes." />
<style>
.grid {
display: grid;
width: 400px;
grid-template-columns: 25% 25% 25% 25%;
line-height: 0;
}
.percent {
width: 100%;
}
canvas {
background: green;
}
</style>
<div class="grid alignItemsBaseline">
<canvas width="100" height="200"></canvas>
<canvas width="200" height="400" class="percent"></canvas>
<div>
<canvas width="100" height="100" class="percent"></canvas>
<canvas width="100" height="100" class="percent"></canvas>
</div>
<div class="percent">
<canvas width="100" height="100" class="percent"></canvas>
<canvas width="100" height="100" class="percent"></canvas>
</div>
</div>
| scheib/chromium | third_party/blink/web_tests/external/wpt/css/css-grid/alignment/self-baseline/grid-self-baseline-008.html | HTML | bsd-3-clause | 1,614 |
/*
###############################################################################
#
# Temboo Arduino library
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
###############################################################################
*/
#ifndef TEMBOOSESSIONCLASS_H_
#define TEMBOOSESSIONCLASS_H_
#include <stdint.h>
#include <Arduino.h>
#include <IPAddress.h>
#include <Client.h>
#include "TembooGlobal.h"
#ifndef TEMBOO_SEND_QUEUE_SIZE
// Some network interfaces (i.e. ethernet or WiFi shields) can only accept
// a limited amount of data. If you try to send more than the limit, the excess
// is just lost. However, sending one character at a time is very inefficient.
// To deal with this situation, we queue up TEMBOO_SEND_QUEUE_SIZE bytes to send
// to the network device at one time. This is a compromise between RAM usage
// and performance.
#define TEMBOO_SEND_QUEUE_SIZE (32)
#endif
class ChoreoInputSet;
class ChoreoOutputSet;
class ChoreoPreset;
class DataFormatter;
class TembooSession {
public:
//TembooSession constructor
//client: REQUIRED TCP/IP client object. Usually either an EthernetClient or a WiFiClient
//IPAddress: OPTIONAL IP address of the server to connect to. Usually only used for testing.
//port: OPTIONAL port number to use with the IPAddress. Usually only used for testing.
TembooSession(Client& client, IPAddress serverAddr=INADDR_NONE, uint16_t port=80);
//executeChoreo sends a choreo execution request to the Temboo system.
// Does not wait for a response (that's a job for whoever owns the Client.)
//accountName: the name of the user's account at Temboo.
//appKeyName: the name of an application key in the user's account to use
// for this execution (analogous to a user name).
//appKeyValue: the value of the application key named in appKeyName.
// Used to authenticate the user (analogous to a password)
//path: The full path to the choreo to be executed (relative to the root of the
// user's account.)
//inputSet: the set of inputs needed by the choreo.
// May be an empty ChoreoInputSet.
//outputSet: the set of output filters to be applied to the choreo results.
// May be an empty ChoreoOutputSet
//preset: the ChoreoPreset to be used with the choreo execution.
// May be an empty ChoreoPreset.
int executeChoreo(const char* accountName,
const char* appKeyName,
const char* appKeyValue,
const char* path,
const ChoreoInputSet& inputSet,
const ChoreoOutputSet& outputSet,
const ChoreoPreset& preset);
// setTime sets the current time in Unix timestamp format. Needed for execution request authentication.
// NOTE: This method is usually called by TembooChoreo.run() with the current time returned by
// an error response from the Temboo system, thus automatically setting the time. However, it
// MAY be called from user code if the particular board has a way of determining the current
// time in the proper format.
// currentTime: the number of seconds since 1970-01-01 00:00:00 UTC.
static void setTime(unsigned long currentTime);
//getTime returns the current time in Unix timestamp format (seconds since 1970-01-01 00:00:00 UTC).
// Only valid after setTime has been called.
static unsigned long getTime();
private:
static unsigned long s_timeOffset;
IPAddress m_addr;
uint16_t m_port;
Client& m_client;
char m_sendQueue[TEMBOO_SEND_QUEUE_SIZE];
size_t m_sendQueueDepth;
// calculate the authentication code value of the formatted request body
// using the salted application key value as the key.
// Returns the number of characters processed (i.e. the length of the request body)
uint16_t getAuth(DataFormatter& fmt, const char* appKeyValue, const char* salt, char* hexAuth) const;
// queue an entire nul-terminated char array
// from RAM followed by a newline.
void qsendln(const char* str);
// queue an entire nul-terminated char array
// from flash memory (PROGMEM) one byte at a time,
// followed by a newline.
void qsendlnProgmem(const char* str);
// queue an entire nul-terminated char array
// from RAM one byte at a time.
void qsend(const char*);
// queue an entire nul-terminated char array
// from flash memory (PROGMEM) one byte at a time.
void qsendProgmem(const char*);
// queue a single character to be sent when the queue is full.
void qsend(char);
// send the current contents of the send queue to the client.
void qflush();
};
#endif
| hvos234/raspberrypi.home | vendor/Arduino/libraries/Temboo/src/utility/TembooSession.h | C | bsd-3-clause | 5,615 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/renderer/aw_render_view_ext.h"
#include <string>
#include "android_webview/common/aw_hit_test_data.h"
#include "android_webview/common/render_view_messages.h"
#include "base/bind.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "content/public/common/url_constants.h"
#include "content/public/renderer/android_content_detection_prefixes.h"
#include "content/public/renderer/document_state.h"
#include "content/public/renderer/render_view.h"
#include "skia/ext/refptr.h"
#include "third_party/WebKit/public/platform/WebSize.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebVector.h"
#include "third_party/WebKit/public/web/WebDataSource.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebHitTestResult.h"
#include "third_party/WebKit/public/web/WebImageCache.h"
#include "third_party/WebKit/public/web/WebNode.h"
#include "third_party/WebKit/public/web/WebNodeList.h"
#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "url/url_canon.h"
#include "url/url_util.h"
namespace android_webview {
namespace {
bool AllowMixedContent(const WebKit::WebURL& url) {
// We treat non-standard schemes as "secure" in the WebView to allow them to
// be used for request interception.
// TODO(benm): Tighten this restriction by requiring embedders to register
// their custom schemes? See b/9420953.
GURL gurl(url);
return !gurl.IsStandard();
}
GURL GetAbsoluteUrl(const WebKit::WebNode& node, const string16& url_fragment) {
return GURL(node.document().completeURL(url_fragment));
}
string16 GetHref(const WebKit::WebElement& element) {
// Get the actual 'href' attribute, which might relative if valid or can
// possibly contain garbage otherwise, so not using absoluteLinkURL here.
return element.getAttribute("href");
}
GURL GetAbsoluteSrcUrl(const WebKit::WebElement& element) {
if (element.isNull())
return GURL();
return GetAbsoluteUrl(element, element.getAttribute("src"));
}
WebKit::WebNode GetImgChild(const WebKit::WebNode& node) {
// This implementation is incomplete (for example if is an area tag) but
// matches the original WebViewClassic implementation.
WebKit::WebNodeList list = node.getElementsByTagName("img");
if (list.length() > 0)
return list.item(0);
return WebKit::WebNode();
}
bool RemovePrefixAndAssignIfMatches(const base::StringPiece& prefix,
const GURL& url,
std::string* dest) {
const base::StringPiece spec(url.possibly_invalid_spec());
if (spec.starts_with(prefix)) {
url_canon::RawCanonOutputW<1024> output;
url_util::DecodeURLEscapeSequences(spec.data() + prefix.length(),
spec.length() - prefix.length(), &output);
std::string decoded_url = UTF16ToUTF8(
string16(output.data(), output.length()));
dest->assign(decoded_url.begin(), decoded_url.end());
return true;
}
return false;
}
void DistinguishAndAssignSrcLinkType(const GURL& url, AwHitTestData* data) {
if (RemovePrefixAndAssignIfMatches(
content::kAddressPrefix,
url,
&data->extra_data_for_type)) {
data->type = AwHitTestData::GEO_TYPE;
} else if (RemovePrefixAndAssignIfMatches(
content::kPhoneNumberPrefix,
url,
&data->extra_data_for_type)) {
data->type = AwHitTestData::PHONE_TYPE;
} else if (RemovePrefixAndAssignIfMatches(
content::kEmailPrefix,
url,
&data->extra_data_for_type)) {
data->type = AwHitTestData::EMAIL_TYPE;
} else {
data->type = AwHitTestData::SRC_LINK_TYPE;
data->extra_data_for_type = url.possibly_invalid_spec();
}
}
void PopulateHitTestData(const GURL& absolute_link_url,
const GURL& absolute_image_url,
bool is_editable,
AwHitTestData* data) {
// Note: Using GURL::is_empty instead of GURL:is_valid due to the
// WebViewClassic allowing any kind of protocol which GURL::is_valid
// disallows. Similar reasons for using GURL::possibly_invalid_spec instead of
// GURL::spec.
if (!absolute_image_url.is_empty())
data->img_src = absolute_image_url;
const bool is_javascript_scheme =
absolute_link_url.SchemeIs(chrome::kJavaScriptScheme);
const bool has_link_url = !absolute_link_url.is_empty();
const bool has_image_url = !absolute_image_url.is_empty();
if (has_link_url && !has_image_url && !is_javascript_scheme) {
DistinguishAndAssignSrcLinkType(absolute_link_url, data);
} else if (has_link_url && has_image_url && !is_javascript_scheme) {
data->type = AwHitTestData::SRC_IMAGE_LINK_TYPE;
data->extra_data_for_type = data->img_src.possibly_invalid_spec();
} else if (!has_link_url && has_image_url) {
data->type = AwHitTestData::IMAGE_TYPE;
data->extra_data_for_type = data->img_src.possibly_invalid_spec();
} else if (is_editable) {
data->type = AwHitTestData::EDIT_TEXT_TYPE;
DCHECK(data->extra_data_for_type.length() == 0);
}
}
} // namespace
AwRenderViewExt::AwRenderViewExt(content::RenderView* render_view)
: content::RenderViewObserver(render_view), page_scale_factor_(0.0f) {
render_view->GetWebView()->setPermissionClient(this);
}
AwRenderViewExt::~AwRenderViewExt() {
}
// static
void AwRenderViewExt::RenderViewCreated(content::RenderView* render_view) {
new AwRenderViewExt(render_view); // |render_view| takes ownership.
}
bool AwRenderViewExt::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(AwRenderViewExt, message)
IPC_MESSAGE_HANDLER(AwViewMsg_DocumentHasImages, OnDocumentHasImagesRequest)
IPC_MESSAGE_HANDLER(AwViewMsg_DoHitTest, OnDoHitTest)
IPC_MESSAGE_HANDLER(AwViewMsg_SetTextZoomLevel, OnSetTextZoomLevel)
IPC_MESSAGE_HANDLER(AwViewMsg_ResetScrollAndScaleState,
OnResetScrollAndScaleState)
IPC_MESSAGE_HANDLER(AwViewMsg_SetInitialPageScale, OnSetInitialPageScale)
IPC_MESSAGE_HANDLER(AwViewMsg_SetFixedLayoutSize,
OnSetFixedLayoutSize)
IPC_MESSAGE_HANDLER(AwViewMsg_SetBackgroundColor, OnSetBackgroundColor)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void AwRenderViewExt::OnDocumentHasImagesRequest(int id) {
bool hasImages = false;
if (render_view()) {
WebKit::WebView* webview = render_view()->GetWebView();
if (webview) {
WebKit::WebVector<WebKit::WebElement> images;
webview->mainFrame()->document().images(images);
hasImages = !images.isEmpty();
}
}
Send(new AwViewHostMsg_DocumentHasImagesResponse(routing_id(), id,
hasImages));
}
bool AwRenderViewExt::allowDisplayingInsecureContent(
WebKit::WebFrame* frame,
bool enabled_per_settings,
const WebKit::WebSecurityOrigin& origin,
const WebKit::WebURL& url) {
return enabled_per_settings ? true : AllowMixedContent(url);
}
bool AwRenderViewExt::allowRunningInsecureContent(
WebKit::WebFrame* frame,
bool enabled_per_settings,
const WebKit::WebSecurityOrigin& origin,
const WebKit::WebURL& url) {
return enabled_per_settings ? true : AllowMixedContent(url);
}
void AwRenderViewExt::DidCommitProvisionalLoad(WebKit::WebFrame* frame,
bool is_new_navigation) {
content::DocumentState* document_state =
content::DocumentState::FromDataSource(frame->dataSource());
if (document_state->can_load_local_resources()) {
WebKit::WebSecurityOrigin origin = frame->document().securityOrigin();
origin.grantLoadLocalResources();
}
}
void AwRenderViewExt::DidCommitCompositorFrame() {
UpdatePageScaleFactor();
}
void AwRenderViewExt::DidUpdateLayout() {
if (check_contents_size_timer_.IsRunning())
return;
check_contents_size_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(0), this,
&AwRenderViewExt::CheckContentsSize);
}
void AwRenderViewExt::UpdatePageScaleFactor() {
if (page_scale_factor_ != render_view()->GetWebView()->pageScaleFactor()) {
page_scale_factor_ = render_view()->GetWebView()->pageScaleFactor();
Send(new AwViewHostMsg_PageScaleFactorChanged(routing_id(),
page_scale_factor_));
}
}
void AwRenderViewExt::CheckContentsSize() {
if (!render_view()->GetWebView())
return;
gfx::Size contents_size;
WebKit::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
if (main_frame)
contents_size = main_frame->contentsSize();
// Fall back to contentsPreferredMinimumSize if the mainFrame is reporting a
// 0x0 size (this happens during initial load).
if (contents_size.IsEmpty()) {
contents_size = render_view()->GetWebView()->contentsPreferredMinimumSize();
}
if (contents_size == last_sent_contents_size_)
return;
last_sent_contents_size_ = contents_size;
Send(new AwViewHostMsg_OnContentsSizeChanged(routing_id(), contents_size));
}
void AwRenderViewExt::Navigate(const GURL& url) {
// Navigate is called only on NEW navigations, so WebImageCache won't be freed
// when the user just clicks on links, but only when a navigation is started,
// for instance via loadUrl. A better approach would be clearing the cache on
// cross-site boundaries, however this would require too many changes both on
// the browser side (in RenderViewHostManger), to the IPCmessages and to the
// RenderViewObserver. Thus, clearing decoding image cache on Navigate, seems
// a more acceptable compromise.
WebKit::WebImageCache::clear();
}
void AwRenderViewExt::FocusedNodeChanged(const WebKit::WebNode& node) {
if (node.isNull() || !node.isElementNode() || !render_view())
return;
// Note: element is not const due to innerText() is not const.
WebKit::WebElement element = node.toConst<WebKit::WebElement>();
AwHitTestData data;
data.href = GetHref(element);
data.anchor_text = element.innerText();
GURL absolute_link_url;
if (node.isLink())
absolute_link_url = GetAbsoluteUrl(node, data.href);
GURL absolute_image_url;
const WebKit::WebNode child_img = GetImgChild(node);
if (!child_img.isNull() && child_img.isElementNode()) {
absolute_image_url =
GetAbsoluteSrcUrl(child_img.toConst<WebKit::WebElement>());
}
PopulateHitTestData(absolute_link_url,
absolute_image_url,
render_view()->IsEditableNode(node),
&data);
Send(new AwViewHostMsg_UpdateHitTestData(routing_id(), data));
}
void AwRenderViewExt::OnDoHitTest(int view_x, int view_y) {
if (!render_view() || !render_view()->GetWebView())
return;
const WebKit::WebHitTestResult result =
render_view()->GetWebView()->hitTestResultAt(
WebKit::WebPoint(view_x, view_y));
AwHitTestData data;
if (!result.urlElement().isNull()) {
data.anchor_text = result.urlElement().innerText();
data.href = GetHref(result.urlElement());
}
PopulateHitTestData(result.absoluteLinkURL(),
result.absoluteImageURL(),
result.isContentEditable(),
&data);
Send(new AwViewHostMsg_UpdateHitTestData(routing_id(), data));
}
void AwRenderViewExt::OnSetTextZoomLevel(double zoom_level) {
if (!render_view() || !render_view()->GetWebView())
return;
// Hide selection and autofill popups.
render_view()->GetWebView()->hidePopups();
render_view()->GetWebView()->setZoomLevel(true, zoom_level);
}
void AwRenderViewExt::OnResetScrollAndScaleState() {
if (!render_view() || !render_view()->GetWebView())
return;
render_view()->GetWebView()->resetScrollAndScaleState();
}
void AwRenderViewExt::OnSetInitialPageScale(double page_scale_factor) {
if (!render_view() || !render_view()->GetWebView())
return;
render_view()->GetWebView()->setInitialPageScaleOverride(
page_scale_factor);
}
void AwRenderViewExt::OnSetFixedLayoutSize(const gfx::Size& size) {
if (!render_view() || !render_view()->GetWebView())
return;
DCHECK(render_view()->GetWebView()->isFixedLayoutModeEnabled());
render_view()->GetWebView()->setFixedLayoutSize(size);
}
void AwRenderViewExt::OnSetBackgroundColor(SkColor c) {
if (!render_view() || !render_view()->GetWebView())
return;
render_view()->GetWebView()->setBaseBackgroundColor(c);
}
} // namespace android_webview
| aospx-kitkat/platform_external_chromium_org | android_webview/renderer/aw_render_view_ext.cc | C++ | bsd-3-clause | 12,981 |
<?php
/**
* File containing the ezcDocumentWikiLiteralBlockNode struct
*
* 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 Document
* @version //autogen//
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
/**
* Struct for Wiki document literal block abstract syntax tree nodes
*
* @package Document
* @version //autogen//
*/
class ezcDocumentWikiLiteralBlockNode extends ezcDocumentWikiBlockLevelNode
{
/**
* Set state after var_export
*
* @param array $properties
* @return void
* @ignore
*/
public static function __set_state( $properties )
{
$nodeClass = __CLASS__;
$node = new $nodeClass( $properties['token'] );
$node->nodes = $properties['nodes'];
return $node;
}
}
?>
| Urbannet/cleanclean | yii2/vendor/zetacomponents/document/src/document/wiki/nodes/literal_block.php | PHP | bsd-3-clause | 1,568 |
/* include this file if the platform implements the dma_ DMA Mapping API
* and wants to provide the pci_ DMA Mapping API in terms of it */
#ifndef _ASM_GENERIC_PCI_DMA_COMPAT_H
#define _ASM_GENERIC_PCI_DMA_COMPAT_H
#include <linux/dma-mapping.h>
/* note pci_set_dma_mask isn't here, since it's a public function
* exported from drivers/pci, use dma_supported instead */
static inline int
pci_dma_supported(struct pci_dev *hwdev, u64 mask)
{
return dma_supported(hwdev == NULL ? NULL : &hwdev->dev, mask);
}
static inline void *
pci_alloc_consistent(struct pci_dev *hwdev, size_t size,
dma_addr_t *dma_handle)
{
return dma_alloc_coherent(hwdev == NULL ? NULL : &hwdev->dev, size, dma_handle, GFP_ATOMIC);
}
static inline void
pci_free_consistent(struct pci_dev *hwdev, size_t size,
void *vaddr, dma_addr_t dma_handle)
{
dma_free_coherent(hwdev == NULL ? NULL : &hwdev->dev, size, vaddr, dma_handle);
}
static inline dma_addr_t
pci_map_single(struct pci_dev *hwdev, void *ptr, size_t size, int direction)
{
return dma_map_single(hwdev == NULL ? NULL : &hwdev->dev, ptr, size, (enum dma_data_direction)direction);
}
static inline void
pci_unmap_single(struct pci_dev *hwdev, dma_addr_t dma_addr,
size_t size, int direction)
{
dma_unmap_single(hwdev == NULL ? NULL : &hwdev->dev, dma_addr, size, (enum dma_data_direction)direction);
}
static inline dma_addr_t
pci_map_page(struct pci_dev *hwdev, struct page *page,
unsigned long offset, size_t size, int direction)
{
return dma_map_page(hwdev == NULL ? NULL : &hwdev->dev, page, offset, size, (enum dma_data_direction)direction);
}
static inline void
pci_unmap_page(struct pci_dev *hwdev, dma_addr_t dma_address,
size_t size, int direction)
{
dma_unmap_page(hwdev == NULL ? NULL : &hwdev->dev, dma_address, size, (enum dma_data_direction)direction);
}
static inline int
pci_map_sg(struct pci_dev *hwdev, struct scatterlist *sg,
int nents, int direction)
{
return dma_map_sg(hwdev == NULL ? NULL : &hwdev->dev, sg, nents, (enum dma_data_direction)direction);
}
static inline void
pci_unmap_sg(struct pci_dev *hwdev, struct scatterlist *sg,
int nents, int direction)
{
dma_unmap_sg(hwdev == NULL ? NULL : &hwdev->dev, sg, nents, (enum dma_data_direction)direction);
}
static inline void
pci_dma_sync_single_for_cpu(struct pci_dev *hwdev, dma_addr_t dma_handle,
size_t size, int direction)
{
dma_sync_single_for_cpu(hwdev == NULL ? NULL : &hwdev->dev, dma_handle, size, (enum dma_data_direction)direction);
}
static inline void
pci_dma_sync_single_for_device(struct pci_dev *hwdev, dma_addr_t dma_handle,
size_t size, int direction)
{
dma_sync_single_for_device(hwdev == NULL ? NULL : &hwdev->dev, dma_handle, size, (enum dma_data_direction)direction);
}
static inline void
pci_dma_sync_sg_for_cpu(struct pci_dev *hwdev, struct scatterlist *sg,
int nelems, int direction)
{
dma_sync_sg_for_cpu(hwdev == NULL ? NULL : &hwdev->dev, sg, nelems, (enum dma_data_direction)direction);
}
static inline void
pci_dma_sync_sg_for_device(struct pci_dev *hwdev, struct scatterlist *sg,
int nelems, int direction)
{
dma_sync_sg_for_device(hwdev == NULL ? NULL : &hwdev->dev, sg, nelems, (enum dma_data_direction)direction);
}
static inline int
pci_dma_mapping_error(struct pci_dev *pdev, dma_addr_t dma_addr)
{
return dma_mapping_error(&pdev->dev, dma_addr);
}
#endif
| MicroTrustRepos/microkernel | src/l4/pkg/linux-26-headers/include/asm-generic/pci-dma-compat.h | C | gpl-2.0 | 3,388 |
html {
background: #eee;
}
body {
font: 11px Verdana, Arial, sans-serif;
color: #333;
}
.sf-exceptionreset, .sf-exceptionreset .block, .sf-exceptionreset #message {
margin: auto;
}
img {
border: 0;
}
.clear {
clear: both;
height: 0;
font-size: 0;
line-height: 0;
}
.clear_fix:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clear_fix {
display: inline-block;
}
* html .clear_fix {
height: 1%;
}
.clear_fix {
display: block;
}
.header {
padding: 30px 30px 20px 30px;
}
.header_logo {
float: left;
}
.search {
float: right;
padding-top: 20px;
}
.search label {
line-height: 28px;
vertical-align: middle;
}
.search input {
width: 188px;
margin-right: 10px;
font-size: 12px;
border: 1px solid #dadada;
background: #FFFFFF url(../images/input_bg.gif) repeat-x left top;
padding: 5px 6px;
color: #565656;
}
.search input[type="search"] {
-webkit-appearance: textfield;
}
.search button {
-webkit-appearance: button-bevel;
float: none;
padding: 0;
margin: 0;
overflow: visible;
width: auto;
text-decoration: none;
cursor: pointer;
white-space: nowrap;
display: inline-block;
text-align: center;
vertical-align: middle;
border: 0;
background: none;
}
.search button:-moz-focus-inner {
padding: 0;
border: none;
}
.search button:hover {
text-decoration: none;
}
.search button span span,
.search button span span span {
position: static;
}
.search button span {
position: relative;
text-decoration: none;
display: block;
height: 28px;
float: left;
padding: 0 0 0 8px;
background: transparent url(../images/border_l.png) no-repeat top left;
}
.search button span span {
padding: 0 8px 0 0;
background: transparent url(../images/border_r.png) right top no-repeat;
}
.search button span span span {
padding: 0 7px;
font: bold 11px Arial, Helvetica, sans-serif;
color: #6b6b6b;
line-height: 28px;
background: transparent url(../images/btn_bg.png) repeat-x top left;
}
#content {
width: 970px;
margin: 0 auto;
}
pre {
white-space: normal;
font-family: Arial, Helvetica, sans-serif;
}
| Night75/MMORPG-demo-website | www/bundles/framework/css/exception_layout.css | CSS | mit | 2,299 |
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview [Widget](http://ckeditor.com/addon/widget) plugin.
*/
'use strict';
( function() {
var DRAG_HANDLER_SIZE = 15;
CKEDITOR.plugins.add( 'widget', {
// jscs:disable maximumLineLength
lang: 'af,ar,az,bg,ca,cs,cy,da,de,de-ch,el,en,en-gb,eo,es,es-mx,eu,fa,fi,fr,gl,he,hr,hu,id,it,ja,km,ko,ku,lv,nb,nl,no,oc,pl,pt,pt-br,ru,sk,sl,sq,sv,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
// jscs:enable maximumLineLength
requires: 'lineutils,clipboard,widgetselection',
onLoad: function() {
CKEDITOR.addCss(
'.cke_widget_wrapper{' +
'position:relative;' +
'outline:none' +
'}' +
'.cke_widget_inline{' +
'display:inline-block' +
'}' +
'.cke_widget_wrapper:hover>.cke_widget_element{' +
'outline:2px solid yellow;' +
'cursor:default' +
'}' +
'.cke_widget_wrapper:hover .cke_widget_editable{' +
'outline:2px solid yellow' +
'}' +
'.cke_widget_wrapper.cke_widget_focused>.cke_widget_element,' +
// We need higher specificity than hover style.
'.cke_widget_wrapper .cke_widget_editable.cke_widget_editable_focused{' +
'outline:2px solid #ace' +
'}' +
'.cke_widget_editable{' +
'cursor:text' +
'}' +
'.cke_widget_drag_handler_container{' +
'position:absolute;' +
'width:' + DRAG_HANDLER_SIZE + 'px;' +
'height:0;' +
// Initially drag handler should not be visible, until its position will be
// calculated (http://dev.ckeditor.com/ticket/11177).
// We need to hide unpositined handlers, so they don't extend
// widget's outline far to the left (http://dev.ckeditor.com/ticket/12024).
'display:none;' +
'opacity:0.75;' +
'transition:height 0s 0.2s;' + // Delay hiding drag handler.
// Prevent drag handler from being misplaced (http://dev.ckeditor.com/ticket/11198).
'line-height:0' +
'}' +
'.cke_widget_wrapper:hover>.cke_widget_drag_handler_container{' +
'height:' + DRAG_HANDLER_SIZE + 'px;' +
'transition:none' +
'}' +
'.cke_widget_drag_handler_container:hover{' +
'opacity:1' +
'}' +
'img.cke_widget_drag_handler{' +
'cursor:move;' +
'width:' + DRAG_HANDLER_SIZE + 'px;' +
'height:' + DRAG_HANDLER_SIZE + 'px;' +
'display:inline-block' +
'}' +
'.cke_widget_mask{' +
'position:absolute;' +
'top:0;' +
'left:0;' +
'width:100%;' +
'height:100%;' +
'display:block' +
'}' +
'.cke_editable.cke_widget_dragging, .cke_editable.cke_widget_dragging *{' +
'cursor:move !important' +
'}'
);
},
beforeInit: function( editor ) {
/**
* An instance of widget repository. It contains all
* {@link CKEDITOR.plugins.widget.repository#registered registered widget definitions} and
* {@link CKEDITOR.plugins.widget.repository#instances initialized instances}.
*
* editor.widgets.add( 'someName', {
* // Widget definition...
* } );
*
* editor.widgets.registered.someName; // -> Widget definition
*
* @since 4.3
* @readonly
* @property {CKEDITOR.plugins.widget.repository} widgets
* @member CKEDITOR.editor
*/
editor.widgets = new Repository( editor );
},
afterInit: function( editor ) {
addWidgetButtons( editor );
setupContextMenu( editor );
}
} );
/**
* Widget repository. It keeps track of all {@link #registered registered widget definitions} and
* {@link #instances initialized instances}. An instance of the repository is available under
* the {@link CKEDITOR.editor#widgets} property.
*
* @class CKEDITOR.plugins.widget.repository
* @mixins CKEDITOR.event
* @constructor Creates a widget repository instance. Note that the widget plugin automatically
* creates a repository instance which is available under the {@link CKEDITOR.editor#widgets} property.
* @param {CKEDITOR.editor} editor The editor instance for which the repository will be created.
*/
function Repository( editor ) {
/**
* The editor instance for which this repository was created.
*
* @readonly
* @property {CKEDITOR.editor} editor
*/
this.editor = editor;
/**
* A hash of registered widget definitions (definition name => {@link CKEDITOR.plugins.widget.definition}).
*
* To register a definition use the {@link #add} method.
*
* @readonly
*/
this.registered = {};
/**
* An object containing initialized widget instances (widget id => {@link CKEDITOR.plugins.widget}).
*
* @readonly
*/
this.instances = {};
/**
* An array of selected widget instances.
*
* @readonly
* @property {CKEDITOR.plugins.widget[]} selected
*/
this.selected = [];
/**
* The focused widget instance. See also {@link CKEDITOR.plugins.widget#event-focus}
* and {@link CKEDITOR.plugins.widget#event-blur} events.
*
* editor.on( 'selectionChange', function() {
* if ( editor.widgets.focused ) {
* // Do something when a widget is focused...
* }
* } );
*
* @readonly
* @property {CKEDITOR.plugins.widget} focused
*/
this.focused = null;
/**
* The widget instance that contains the nested editable which is currently focused.
*
* @readonly
* @property {CKEDITOR.plugins.widget} widgetHoldingFocusedEditable
*/
this.widgetHoldingFocusedEditable = null;
this._ = {
nextId: 0,
upcasts: [],
upcastCallbacks: [],
filters: {}
};
setupWidgetsLifecycle( this );
setupSelectionObserver( this );
setupMouseObserver( this );
setupKeyboardObserver( this );
setupDragAndDrop( this );
setupNativeCutAndCopy( this );
}
Repository.prototype = {
/**
* Minimum interval between selection checks.
*
* @private
*/
MIN_SELECTION_CHECK_INTERVAL: 500,
/**
* Adds a widget definition to the repository. Fires the {@link CKEDITOR.editor#widgetDefinition} event
* which allows to modify the widget definition which is going to be registered.
*
* @param {String} name The name of the widget definition.
* @param {CKEDITOR.plugins.widget.definition} widgetDef Widget definition.
* @returns {CKEDITOR.plugins.widget.definition}
*/
add: function( name, widgetDef ) {
// Create prototyped copy of original widget definition, so we won't modify it.
widgetDef = CKEDITOR.tools.prototypedCopy( widgetDef );
widgetDef.name = name;
widgetDef._ = widgetDef._ || {};
this.editor.fire( 'widgetDefinition', widgetDef );
if ( widgetDef.template )
widgetDef.template = new CKEDITOR.template( widgetDef.template );
addWidgetCommand( this.editor, widgetDef );
addWidgetProcessors( this, widgetDef );
this.registered[ name ] = widgetDef;
return widgetDef;
},
/**
* Adds a callback for element upcasting. Each callback will be executed
* for every element which is later tested by upcast methods. If a callback
* returns `false`, the element will not be upcasted.
*
* // Images with the "banner" class will not be upcasted (e.g. to the image widget).
* editor.widgets.addUpcastCallback( function( element ) {
* if ( element.name == 'img' && element.hasClass( 'banner' ) )
* return false;
* } );
*
* @param {Function} callback
* @param {CKEDITOR.htmlParser.element} callback.element
*/
addUpcastCallback: function( callback ) {
this._.upcastCallbacks.push( callback );
},
/**
* Checks the selection to update widget states (selection and focus).
*
* This method is triggered by the {@link #event-checkSelection} event.
*/
checkSelection: function() {
var sel = this.editor.getSelection(),
selectedElement = sel.getSelectedElement(),
updater = stateUpdater( this ),
widget;
// Widget is focused so commit and finish checking.
if ( selectedElement && ( widget = this.getByElement( selectedElement, true ) ) )
return updater.focus( widget ).select( widget ).commit();
var range = sel.getRanges()[ 0 ];
// No ranges or collapsed range mean that nothing is selected, so commit and finish checking.
if ( !range || range.collapsed )
return updater.commit();
// Range is not empty, so create walker checking for wrappers.
var walker = new CKEDITOR.dom.walker( range ),
wrapper;
walker.evaluator = Widget.isDomWidgetWrapper;
while ( ( wrapper = walker.next() ) )
updater.select( this.getByElement( wrapper ) );
updater.commit();
},
/**
* Checks if all widget instances are still present in the DOM.
* Destroys those instances that are not present.
* Reinitializes widgets on widget wrappers for which widget instances
* cannot be found. Takes nested widgets into account, too.
*
* This method triggers the {@link #event-checkWidgets} event whose listeners
* can cancel the method's execution or modify its options.
*
* @param [options] The options object.
* @param {Boolean} [options.initOnlyNew] Initializes widgets only on newly wrapped
* widget elements (those which still have the `cke_widget_new` class). When this option is
* set to `true`, widgets which were invalidated (e.g. by replacing with a cloned DOM structure)
* will not be reinitialized. This makes the check faster.
* @param {Boolean} [options.focusInited] If only one widget is initialized by
* the method, it will be focused.
*/
checkWidgets: function( options ) {
this.fire( 'checkWidgets', CKEDITOR.tools.copy( options || {} ) );
},
/**
* Removes the widget from the editor and moves the selection to the closest
* editable position if the widget was focused before.
*
* @param {CKEDITOR.plugins.widget} widget The widget instance to be deleted.
*/
del: function( widget ) {
if ( this.focused === widget ) {
var editor = widget.editor,
range = editor.createRange(),
found;
// If haven't found place for caret on the default side,
// try to find it on the other side.
if ( !( found = range.moveToClosestEditablePosition( widget.wrapper, true ) ) )
found = range.moveToClosestEditablePosition( widget.wrapper, false );
if ( found )
editor.getSelection().selectRanges( [ range ] );
}
widget.wrapper.remove();
this.destroy( widget, true );
},
/**
* Destroys the widget instance and all its nested widgets (widgets inside its nested editables).
*
* @param {CKEDITOR.plugins.widget} widget The widget instance to be destroyed.
* @param {Boolean} [offline] Whether the widget is offline (detached from the DOM tree) —
* in this case the DOM (attributes, classes, etc.) will not be cleaned up.
*/
destroy: function( widget, offline ) {
if ( this.widgetHoldingFocusedEditable === widget )
setFocusedEditable( this, widget, null, offline );
widget.destroy( offline );
delete this.instances[ widget.id ];
this.fire( 'instanceDestroyed', widget );
},
/**
* Destroys all widget instances.
*
* @param {Boolean} [offline] Whether the widgets are offline (detached from the DOM tree) —
* in this case the DOM (attributes, classes, etc.) will not be cleaned up.
* @param {CKEDITOR.dom.element} [container] The container within widgets will be destroyed.
* This option will be ignored if the `offline` flag was set to `true`, because in such case
* it is not possible to find widgets within the passed block.
*/
destroyAll: function( offline, container ) {
var widget,
id,
instances = this.instances;
if ( container && !offline ) {
var wrappers = container.find( '.cke_widget_wrapper' ),
l = wrappers.count(),
i = 0;
// Length is constant, because this is not a live node list.
// Note: since querySelectorAll returns nodes in document order,
// outer widgets are always placed before their nested widgets and therefore
// are destroyed before them.
for ( ; i < l; ++i ) {
widget = this.getByElement( wrappers.getItem( i ), true );
// Widget might not be found, because it could be a nested widget,
// which would be destroyed when destroying its parent.
if ( widget )
this.destroy( widget );
}
return;
}
for ( id in instances ) {
widget = instances[ id ];
this.destroy( widget, offline );
}
},
/**
* Finalizes a process of widget creation. This includes:
*
* * inserting widget element into editor,
* * marking widget instance as ready (see {@link CKEDITOR.plugins.widget#event-ready}),
* * focusing widget instance.
*
* This method is used by the default widget's command and is called
* after widget's dialog (if set) is closed. It may also be used in a
* customized process of widget creation and insertion.
*
* widget.once( 'edit', function() {
* // Finalize creation only of not ready widgets.
* if ( widget.isReady() )
* return;
*
* // Cancel edit event to prevent automatic widget insertion.
* evt.cancel();
*
* CustomDialog.open( widget.data, function saveCallback( savedData ) {
* // Cache the container, because widget may be destroyed while saving data,
* // if this process will require some deep transformations.
* var container = widget.wrapper.getParent();
*
* widget.setData( savedData );
*
* // Widget will be retrieved from container and inserted into editor.
* editor.widgets.finalizeCreation( container );
* } );
* } );
*
* @param {CKEDITOR.dom.element/CKEDITOR.dom.documentFragment} container The element
* or document fragment which contains widget wrapper. The container is used, so before
* finalizing creation the widget can be freely transformed (even destroyed and reinitialized).
*/
finalizeCreation: function( container ) {
var wrapper = container.getFirst();
if ( wrapper && Widget.isDomWidgetWrapper( wrapper ) ) {
this.editor.insertElement( wrapper );
var widget = this.getByElement( wrapper );
// Fire postponed #ready event.
widget.ready = true;
widget.fire( 'ready' );
widget.focus();
}
},
/**
* Finds a widget instance which contains a given element. The element will be the {@link CKEDITOR.plugins.widget#wrapper wrapper}
* of the returned widget or a descendant of this {@link CKEDITOR.plugins.widget#wrapper wrapper}.
*
* editor.widgets.getByElement( someWidget.wrapper ); // -> someWidget
* editor.widgets.getByElement( someWidget.parts.caption ); // -> someWidget
*
* // Check wrapper only:
* editor.widgets.getByElement( someWidget.wrapper, true ); // -> someWidget
* editor.widgets.getByElement( someWidget.parts.caption, true ); // -> null
*
* @param {CKEDITOR.dom.element} element The element to be checked.
* @param {Boolean} [checkWrapperOnly] If set to `true`, the method will not check wrappers' descendants.
* @returns {CKEDITOR.plugins.widget} The widget instance or `null`.
*/
getByElement: ( function() {
var validWrapperElements = { div: 1, span: 1 };
function getWidgetId( element ) {
return element.is( validWrapperElements ) && element.data( 'cke-widget-id' );
}
return function( element, checkWrapperOnly ) {
if ( !element )
return null;
var id = getWidgetId( element );
// There's no need to check element parents if element is a wrapper.
if ( !checkWrapperOnly && !id ) {
var limit = this.editor.editable();
// Try to find a closest ascendant which is a widget wrapper.
do {
element = element.getParent();
} while ( element && !element.equals( limit ) && !( id = getWidgetId( element ) ) );
}
return this.instances[ id ] || null;
};
} )(),
/**
* Initializes a widget on a given element if the widget has not been initialized on it yet.
*
* @param {CKEDITOR.dom.element} element The future widget element.
* @param {String/CKEDITOR.plugins.widget.definition} [widgetDef] Name of a widget or a widget definition.
* The widget definition should be previously registered by using the
* {@link CKEDITOR.plugins.widget.repository#add} method.
* @param [startupData] Widget startup data (has precedence over default one).
* @returns {CKEDITOR.plugins.widget} The widget instance or `null` if a widget could not be initialized on
* a given element.
*/
initOn: function( element, widgetDef, startupData ) {
if ( !widgetDef )
widgetDef = this.registered[ element.data( 'widget' ) ];
else if ( typeof widgetDef == 'string' )
widgetDef = this.registered[ widgetDef ];
if ( !widgetDef )
return null;
// Wrap element if still wasn't wrapped (was added during runtime by method that skips dataProcessor).
var wrapper = this.wrapElement( element, widgetDef.name );
if ( wrapper ) {
// Check if widget wrapper is new (widget hasn't been initialized on it yet).
// This class will be removed by widget constructor to avoid locking snapshot twice.
if ( wrapper.hasClass( 'cke_widget_new' ) ) {
var widget = new Widget( this, this._.nextId++, element, widgetDef, startupData );
// Widget could be destroyed when initializing it.
if ( widget.isInited() ) {
this.instances[ widget.id ] = widget;
return widget;
} else {
return null;
}
}
// Widget already has been initialized, so try to get widget by element.
// Note - it may happen that other instance will returned than the one created above,
// if for example widget was destroyed and reinitialized.
return this.getByElement( element );
}
// No wrapper means that there's no widget for this element.
return null;
},
/**
* Initializes widgets on all elements which were wrapped by {@link #wrapElement} and
* have not been initialized yet.
*
* @param {CKEDITOR.dom.element} [container=editor.editable()] The container which will be checked for not
* initialized widgets. Defaults to editor's {@link CKEDITOR.editor#editable editable} element.
* @returns {CKEDITOR.plugins.widget[]} Array of widget instances which have been initialized.
* Note: Only first-level widgets are returned — without nested widgets.
*/
initOnAll: function( container ) {
var newWidgets = ( container || this.editor.editable() ).find( '.cke_widget_new' ),
newInstances = [],
instance;
for ( var i = newWidgets.count(); i--; ) {
instance = this.initOn( newWidgets.getItem( i ).getFirst( Widget.isDomWidgetElement ) );
if ( instance )
newInstances.push( instance );
}
return newInstances;
},
/**
* Allows to listen to events on specific types of widgets, even if they are not created yet.
*
* Please note that this method inherits parameters from the {@link CKEDITOR.event#method-on} method with one
* extra parameter at the beginning which is the widget name.
*
* editor.widgets.onWidget( 'image', 'action', function( evt ) {
* // Event `action` occurs on `image` widget.
* } );
*
* @since 4.5
* @param {String} widgetName
* @param {String} eventName
* @param {Function} listenerFunction
* @param {Object} [scopeObj]
* @param {Object} [listenerData]
* @param {Number} [priority=10]
*/
onWidget: function( widgetName ) {
var args = Array.prototype.slice.call( arguments );
args.shift();
for ( var i in this.instances ) {
var instance = this.instances[ i ];
if ( instance.name == widgetName ) {
instance.on.apply( instance, args );
}
}
this.on( 'instanceCreated', function( evt ) {
var widget = evt.data;
if ( widget.name == widgetName ) {
widget.on.apply( widget, args );
}
} );
},
/**
* Parses element classes string and returns an object
* whose keys contain class names. Skips all `cke_*` classes.
*
* This method is used by the {@link CKEDITOR.plugins.widget#getClasses} method and
* may be used when overriding that method.
*
* @since 4.4
* @param {String} classes String (value of `class` attribute).
* @returns {Object} Object containing classes or `null` if no classes found.
*/
parseElementClasses: function( classes ) {
if ( !classes )
return null;
classes = CKEDITOR.tools.trim( classes ).split( /\s+/ );
var cl,
obj = {},
hasClasses = 0;
while ( ( cl = classes.pop() ) ) {
if ( cl.indexOf( 'cke_' ) == -1 )
obj[ cl ] = hasClasses = 1;
}
return hasClasses ? obj : null;
},
/**
* Wraps an element with a widget's non-editable container.
*
* If this method is called on an {@link CKEDITOR.htmlParser.element}, then it will
* also take care of fixing the DOM after wrapping (the wrapper may not be allowed in element's parent).
*
* @param {CKEDITOR.dom.element/CKEDITOR.htmlParser.element} element The widget element to be wrapped.
* @param {String} [widgetName] The name of the widget definition. Defaults to element's `data-widget`
* attribute value.
* @returns {CKEDITOR.dom.element/CKEDITOR.htmlParser.element} The wrapper element or `null` if
* the widget definition of this name is not registered.
*/
wrapElement: function( element, widgetName ) {
var wrapper = null,
widgetDef,
isInline;
if ( element instanceof CKEDITOR.dom.element ) {
widgetName = widgetName || element.data( 'widget' );
widgetDef = this.registered[ widgetName ];
if ( !widgetDef )
return null;
// Do not wrap already wrapped element.
wrapper = element.getParent();
if ( wrapper && wrapper.type == CKEDITOR.NODE_ELEMENT && wrapper.data( 'cke-widget-wrapper' ) )
return wrapper;
// If attribute isn't already set (e.g. for pasted widget), set it.
if ( !element.hasAttribute( 'data-cke-widget-keep-attr' ) )
element.data( 'cke-widget-keep-attr', element.data( 'widget' ) ? 1 : 0 );
element.data( 'widget', widgetName );
isInline = isWidgetInline( widgetDef, element.getName() );
wrapper = new CKEDITOR.dom.element( isInline ? 'span' : 'div' );
wrapper.setAttributes( getWrapperAttributes( isInline, widgetName ) );
wrapper.data( 'cke-display-name', widgetDef.pathName ? widgetDef.pathName : element.getName() );
// Replace element unless it is a detached one.
if ( element.getParent( true ) )
wrapper.replace( element );
element.appendTo( wrapper );
}
else if ( element instanceof CKEDITOR.htmlParser.element ) {
widgetName = widgetName || element.attributes[ 'data-widget' ];
widgetDef = this.registered[ widgetName ];
if ( !widgetDef )
return null;
wrapper = element.parent;
if ( wrapper && wrapper.type == CKEDITOR.NODE_ELEMENT && wrapper.attributes[ 'data-cke-widget-wrapper' ] )
return wrapper;
// If attribute isn't already set (e.g. for pasted widget), set it.
if ( !( 'data-cke-widget-keep-attr' in element.attributes ) )
element.attributes[ 'data-cke-widget-keep-attr' ] = element.attributes[ 'data-widget' ] ? 1 : 0;
if ( widgetName )
element.attributes[ 'data-widget' ] = widgetName;
isInline = isWidgetInline( widgetDef, element.name );
wrapper = new CKEDITOR.htmlParser.element( isInline ? 'span' : 'div', getWrapperAttributes( isInline, widgetName ) );
wrapper.attributes[ 'data-cke-display-name' ] = widgetDef.pathName ? widgetDef.pathName : element.name;
var parent = element.parent,
index;
// Don't detach already detached element.
if ( parent ) {
index = element.getIndex();
element.remove();
}
wrapper.add( element );
// Insert wrapper fixing DOM (splitting parents if wrapper is not allowed inside them).
parent && insertElement( parent, index, wrapper );
}
return wrapper;
},
// Expose for tests.
_tests_createEditableFilter: createEditableFilter
};
CKEDITOR.event.implementOn( Repository.prototype );
/**
* An event fired when a widget instance is created, but before it is fully initialized.
*
* @event instanceCreated
* @param {CKEDITOR.plugins.widget} data The widget instance.
*/
/**
* An event fired when a widget instance was destroyed.
*
* See also {@link CKEDITOR.plugins.widget#event-destroy}.
*
* @event instanceDestroyed
* @param {CKEDITOR.plugins.widget} data The widget instance.
*/
/**
* An event fired to trigger the selection check.
*
* See the {@link #method-checkSelection} method.
*
* @event checkSelection
*/
/**
* An event fired by the the {@link #method-checkWidgets} method.
*
* It can be canceled in order to stop the {@link #method-checkWidgets}
* method execution or the event listener can modify the method's options.
*
* @event checkWidgets
* @param [data]
* @param {Boolean} [data.initOnlyNew] Initialize widgets only on newly wrapped
* widget elements (those which still have the `cke_widget_new` class). When this option is
* set to `true`, widgets which were invalidated (e.g. by replacing with a cloned DOM structure)
* will not be reinitialized. This makes the check faster.
* @param {Boolean} [data.focusInited] If only one widget is initialized by
* the method, it will be focused.
*/
/**
* An instance of a widget. Together with {@link CKEDITOR.plugins.widget.repository} these
* two classes constitute the core of the Widget System.
*
* Note that neither the repository nor the widget instances can be created by using their constructors.
* A repository instance is automatically set up by the Widget plugin and is accessible under
* {@link CKEDITOR.editor#widgets}, while widget instances are created and destroyed by the repository.
*
* To create a widget, first you need to {@link CKEDITOR.plugins.widget.repository#add register} its
* {@link CKEDITOR.plugins.widget.definition definition}:
*
* editor.widgets.add( 'simplebox', {
* upcast: function( element ) {
* // Defines which elements will become widgets.
* if ( element.hasClass( 'simplebox' ) )
* return true;
* },
* init: function() {
* // ...
* }
* } );
*
* Once the widget definition is registered, widgets will be automatically
* created when loading data:
*
* editor.setData( '<div class="simplebox">foo</div>', function() {
* console.log( editor.widgets.instances ); // -> An object containing one instance.
* } );
*
* It is also possible to create instances during runtime by using a command
* (if a {@link CKEDITOR.plugins.widget.definition#template} property was defined):
*
* // You can execute an automatically defined command to
* // insert a new simplebox widget or edit the one currently focused.
* editor.execCommand( 'simplebox' );
*
* Note: Since CKEditor 4.5 widget's `startupData` can be passed as the command argument:
*
* editor.execCommand( 'simplebox', {
* startupData: {
* align: 'left'
* }
* } );
*
* A widget can also be created in a completely custom way:
*
* var element = editor.document.createElement( 'div' );
* editor.insertElement( element );
* var widget = editor.widgets.initOn( element, 'simplebox' );
*
* @since 4.3
* @class CKEDITOR.plugins.widget
* @mixins CKEDITOR.event
* @extends CKEDITOR.plugins.widget.definition
* @constructor Creates an instance of the widget class. Do not use it directly, but instead initialize widgets
* by using the {@link CKEDITOR.plugins.widget.repository#initOn} method or by the upcasting system.
* @param {CKEDITOR.plugins.widget.repository} widgetsRepo
* @param {Number} id Unique ID of this widget instance.
* @param {CKEDITOR.dom.element} element The widget element.
* @param {CKEDITOR.plugins.widget.definition} widgetDef Widget's registered definition.
* @param [startupData] Initial widget data. This data object will overwrite the default data and
* the data loaded from the DOM.
*/
function Widget( widgetsRepo, id, element, widgetDef, startupData ) {
var editor = widgetsRepo.editor;
// Extend this widget with widgetDef-specific methods and properties.
CKEDITOR.tools.extend( this, widgetDef, {
/**
* The editor instance.
*
* @readonly
* @property {CKEDITOR.editor}
*/
editor: editor,
/**
* This widget's unique (per editor instance) ID.
*
* @readonly
* @property {Number}
*/
id: id,
/**
* Whether this widget is an inline widget (based on an inline element unless
* forced otherwise by {@link CKEDITOR.plugins.widget.definition#inline}).
*
* **Note:** This option does not allow to turn a block element into an inline widget.
* However, it makes it possible to turn an inline element into a block widget or to
* force a correct type in case when automatic recognition fails.
*
* @readonly
* @property {Boolean}
*/
inline: element.getParent().getName() == 'span',
/**
* The widget element — the element on which the widget was initialized.
*
* @readonly
* @property {CKEDITOR.dom.element} element
*/
element: element,
/**
* Widget's data object.
*
* The data can only be set by using the {@link #setData} method.
* Changes made to the data fire the {@link #event-data} event.
*
* @readonly
*/
data: CKEDITOR.tools.extend( {}, typeof widgetDef.defaults == 'function' ? widgetDef.defaults() : widgetDef.defaults ),
/**
* Indicates if a widget is data-ready. Set to `true` when data from all sources
* ({@link CKEDITOR.plugins.widget.definition#defaults}, set in the
* {@link #init} method, loaded from the widget's element and startup data coming from the constructor)
* are finally loaded. This is immediately followed by the first {@link #event-data}.
*
* @readonly
*/
dataReady: false,
/**
* Whether a widget instance was initialized. This means that:
*
* * An instance was created,
* * Its properties were set,
* * The `init` method was executed.
*
* **Note**: The first {@link #event-data} event could not be fired yet which
* means that the widget's DOM has not been set up yet. Wait for the {@link #event-ready}
* event to be notified when a widget is fully initialized and ready.
*
* **Note**: Use the {@link #isInited} method to check whether a widget is initialized and
* has not been destroyed.
*
* @readonly
*/
inited: false,
/**
* Whether a widget instance is ready. This means that the widget is {@link #inited} and
* that its DOM was finally set up.
*
* **Note:** Use the {@link #isReady} method to check whether a widget is ready and
* has not been destroyed.
*
* @readonly
*/
ready: false,
// Revert what widgetDef could override (automatic #edit listener).
edit: Widget.prototype.edit,
/**
* The nested editable element which is currently focused.
*
* @readonly
* @property {CKEDITOR.plugins.widget.nestedEditable}
*/
focusedEditable: null,
/**
* The widget definition from which this instance was created.
*
* @readonly
* @property {CKEDITOR.plugins.widget.definition} definition
*/
definition: widgetDef,
/**
* Link to the widget repository which created this instance.
*
* @readonly
* @property {CKEDITOR.plugins.widget.repository} repository
*/
repository: widgetsRepo,
draggable: widgetDef.draggable !== false,
// WAAARNING: Overwrite widgetDef's priv object, because otherwise violent unicorn's gonna visit you.
_: {
downcastFn: ( widgetDef.downcast && typeof widgetDef.downcast == 'string' ) ?
widgetDef.downcasts[ widgetDef.downcast ] : widgetDef.downcast
}
}, true );
/**
* An object of widget component elements.
*
* For every `partName => selector` pair in {@link CKEDITOR.plugins.widget.definition#parts},
* one `partName => element` pair is added to this object during the widget initialization.
*
* @readonly
* @property {Object} parts
*/
/**
* The template which will be used to create a new widget element (when the widget's command is executed).
* It will be populated with {@link #defaults default values}.
*
* @readonly
* @property {CKEDITOR.template} template
*/
/**
* The widget wrapper — a non-editable `div` or `span` element (depending on {@link #inline})
* which is a parent of the {@link #element} and widget compontents like the drag handler and the {@link #mask}.
* It is the outermost widget element.
*
* @readonly
* @property {CKEDITOR.dom.element} wrapper
*/
widgetsRepo.fire( 'instanceCreated', this );
setupWidget( this, widgetDef );
this.init && this.init();
// Finally mark widget as inited.
this.inited = true;
setupWidgetData( this, startupData );
// If at some point (e.g. in #data listener) widget hasn't been destroyed
// and widget is already attached to document then fire #ready.
if ( this.isInited() && editor.editable().contains( this.wrapper ) ) {
this.ready = true;
this.fire( 'ready' );
}
}
Widget.prototype = {
/**
* Adds a class to the widget element. This method is used by
* the {@link #applyStyle} method and should be overridden by widgets
* which should handle classes differently (e.g. add them to other elements).
*
* Since 4.6.0 this method also adds a corresponding class prefixed with {@link #WRAPPER_CLASS_PREFIX}
* to the widget wrapper element.
*
* **Note**: This method should not be used directly. Use the {@link #setData} method to
* set the `classes` property. Read more in the {@link #setData} documentation.
*
* See also: {@link #removeClass}, {@link #hasClass}, {@link #getClasses}.
*
* @since 4.4
* @param {String} className The class name to be added.
*/
addClass: function( className ) {
this.element.addClass( className );
this.wrapper.addClass( Widget.WRAPPER_CLASS_PREFIX + className );
},
/**
* Applies the specified style to the widget. It is highly recommended to use the
* {@link CKEDITOR.editor#applyStyle} or {@link CKEDITOR.style#apply} methods instead of
* using this method directly, because unlike editor's and style's methods, this one
* does not perform any checks.
*
* By default this method handles only classes defined in the style. It clones existing
* classes which are stored in the {@link #property-data widget data}'s `classes` property,
* adds new classes, and calls the {@link #setData} method if at least one new class was added.
* Then, using the {@link #event-data} event listener widget applies modifications passing
* new classes to the {@link #addClass} method.
*
* If you need to handle classes differently than in the default way, you can override the
* {@link #addClass} and related methods. You can also handle other style properties than `classes`
* by overriding this method.
*
* See also: {@link #checkStyleActive}, {@link #removeStyle}.
*
* @since 4.4
* @param {CKEDITOR.style} style The custom widget style to be applied.
*/
applyStyle: function( style ) {
applyRemoveStyle( this, style, 1 );
},
/**
* Checks if the specified style is applied to this widget. It is highly recommended to use the
* {@link CKEDITOR.style#checkActive} method instead of using this method directly,
* because unlike style's method, this one does not perform any checks.
*
* By default this method handles only classes defined in the style and passes
* them to the {@link #hasClass} method. You can override these methods to handle classes
* differently or to handle more of the style properties.
*
* See also: {@link #applyStyle}, {@link #removeStyle}.
*
* @since 4.4
* @param {CKEDITOR.style} style The custom widget style to be checked.
* @returns {Boolean} Whether the style is applied to this widget.
*/
checkStyleActive: function( style ) {
var classes = getStyleClasses( style ),
cl;
if ( !classes )
return false;
while ( ( cl = classes.pop() ) ) {
if ( !this.hasClass( cl ) )
return false;
}
return true;
},
/**
* Destroys this widget instance.
*
* Use {@link CKEDITOR.plugins.widget.repository#destroy} when possible instead of this method.
*
* This method fires the {#event-destroy} event.
*
* @param {Boolean} [offline] Whether a widget is offline (detached from the DOM tree) —
* in this case the DOM (attributes, classes, etc.) will not be cleaned up.
*/
destroy: function( offline ) {
this.fire( 'destroy' );
if ( this.editables ) {
for ( var name in this.editables )
this.destroyEditable( name, offline );
}
if ( !offline ) {
if ( this.element.data( 'cke-widget-keep-attr' ) == '0' )
this.element.removeAttribute( 'data-widget' );
this.element.removeAttributes( [ 'data-cke-widget-data', 'data-cke-widget-keep-attr' ] );
this.element.removeClass( 'cke_widget_element' );
this.element.replace( this.wrapper );
}
this.wrapper = null;
},
/**
* Destroys a nested editable and all nested widgets.
*
* @param {String} editableName Nested editable name.
* @param {Boolean} [offline] See {@link #method-destroy} method.
*/
destroyEditable: function( editableName, offline ) {
var editable = this.editables[ editableName ];
editable.removeListener( 'focus', onEditableFocus );
editable.removeListener( 'blur', onEditableBlur );
this.editor.focusManager.remove( editable );
if ( !offline ) {
this.repository.destroyAll( false, editable );
editable.removeClass( 'cke_widget_editable' );
editable.removeClass( 'cke_widget_editable_focused' );
editable.removeAttributes( [ 'contenteditable', 'data-cke-widget-editable', 'data-cke-enter-mode' ] );
}
delete this.editables[ editableName ];
},
/**
* Starts widget editing.
*
* This method fires the {@link CKEDITOR.plugins.widget#event-edit} event
* which may be canceled in order to prevent it from opening a dialog window.
*
* The dialog window name is obtained from the event's data `dialog` property or
* from {@link CKEDITOR.plugins.widget.definition#dialog}.
*
* @returns {Boolean} Returns `true` if a dialog window was opened.
*/
edit: function() {
var evtData = { dialog: this.dialog },
that = this;
// Edit event was blocked or there's no dialog to be automatically opened.
if ( this.fire( 'edit', evtData ) === false || !evtData.dialog )
return false;
this.editor.openDialog( evtData.dialog, function( dialog ) {
var showListener,
okListener;
// Allow to add a custom dialog handler.
if ( that.fire( 'dialog', dialog ) === false )
return;
showListener = dialog.on( 'show', function() {
dialog.setupContent( that );
} );
okListener = dialog.on( 'ok', function() {
// Commit dialog's fields, but prevent from
// firing data event for every field. Fire only one,
// bulk event at the end.
var dataChanged,
dataListener = that.on( 'data', function( evt ) {
dataChanged = 1;
evt.cancel();
}, null, null, 0 );
// Create snapshot preceeding snapshot with changed widget...
// TODO it should not be required, but it is and I found similar
// code in dialog#ok listener in dialog/plugin.js.
that.editor.fire( 'saveSnapshot' );
dialog.commitContent( that );
dataListener.removeListener();
if ( dataChanged ) {
that.fire( 'data', that.data );
that.editor.fire( 'saveSnapshot' );
}
} );
dialog.once( 'hide', function() {
showListener.removeListener();
okListener.removeListener();
} );
} );
return true;
},
/**
* Returns widget element classes parsed to an object. This method
* is used to populate the `classes` property of widget's {@link #property-data}.
*
* This method reuses {@link CKEDITOR.plugins.widget.repository#parseElementClasses}.
* It should be overriden if a widget should handle classes differently (e.g. on other elements).
*
* See also: {@link #removeClass}, {@link #addClass}, {@link #hasClass}.
*
* @since 4.4
* @returns {Object}
*/
getClasses: function() {
return this.repository.parseElementClasses( this.element.getAttribute( 'class' ) );
},
/**
* Checks if the widget element has specified class. This method is used by
* the {@link #checkStyleActive} method and should be overriden by widgets
* which should handle classes differently (e.g. on other elements).
*
* See also: {@link #removeClass}, {@link #addClass}, {@link #getClasses}.
*
* @since 4.4
* @param {String} className The class to be checked.
* @param {Boolean} Whether a widget has specified class.
*/
hasClass: function( className ) {
return this.element.hasClass( className );
},
/**
* Initializes a nested editable.
*
* **Note**: Only elements from {@link CKEDITOR.dtd#$editable} may become editables.
*
* @param {String} editableName The nested editable name.
* @param {CKEDITOR.plugins.widget.nestedEditable.definition} definition The definition of the nested editable.
* @returns {Boolean} Whether an editable was successfully initialized.
*/
initEditable: function( editableName, definition ) {
// Don't fetch just first element which matched selector but look for a correct one. (http://dev.ckeditor.com/ticket/13334)
var editable = this._findOneNotNested( definition.selector );
if ( editable && editable.is( CKEDITOR.dtd.$editable ) ) {
editable = new NestedEditable( this.editor, editable, {
filter: createEditableFilter.call( this.repository, this.name, editableName, definition )
} );
this.editables[ editableName ] = editable;
editable.setAttributes( {
contenteditable: 'true',
'data-cke-widget-editable': editableName,
'data-cke-enter-mode': editable.enterMode
} );
if ( editable.filter )
editable.data( 'cke-filter', editable.filter.id );
editable.addClass( 'cke_widget_editable' );
// This class may be left when d&ding widget which
// had focused editable. Clean this class here, not in
// cleanUpWidgetElement for performance and code size reasons.
editable.removeClass( 'cke_widget_editable_focused' );
if ( definition.pathName )
editable.data( 'cke-display-name', definition.pathName );
this.editor.focusManager.add( editable );
editable.on( 'focus', onEditableFocus, this );
CKEDITOR.env.ie && editable.on( 'blur', onEditableBlur, this );
// Finally, process editable's data. This data wasn't processed when loading
// editor's data, becuase they need to be processed separately, with its own filters and settings.
editable._.initialSetData = true;
editable.setData( editable.getHtml() );
return true;
}
return false;
},
/**
* Looks inside wrapper element to find a node that
* matches given selector and is not nested in other widget. (http://dev.ckeditor.com/ticket/13334)
*
* @since 4.5
* @private
* @param {String} selector Selector to match.
* @returns {CKEDITOR.dom.element} Matched element or `null` if a node has not been found.
*/
_findOneNotNested: function( selector ) {
var matchedElements = this.wrapper.find( selector ),
match,
closestWrapper;
for ( var i = 0; i < matchedElements.count(); i++ ) {
match = matchedElements.getItem( i );
closestWrapper = match.getAscendant( Widget.isDomWidgetWrapper );
// The closest ascendant-wrapper of this match defines to which widget
// this match belongs. If the ascendant is this widget's wrapper
// it means that the match is not nested in other widget.
if ( this.wrapper.equals( closestWrapper ) ) {
return match;
}
}
return null;
},
/**
* Checks if a widget has already been initialized and has not been destroyed yet.
*
* See {@link #inited} for more details.
*
* @returns {Boolean}
*/
isInited: function() {
return !!( this.wrapper && this.inited );
},
/**
* Checks if a widget is ready and has not been destroyed yet.
*
* See {@link #property-ready} for more details.
*
* @returns {Boolean}
*/
isReady: function() {
return this.isInited() && this.ready;
},
/**
* Focuses a widget by selecting it.
*/
focus: function() {
var sel = this.editor.getSelection();
// Fake the selection before focusing editor, to avoid unpreventable viewports scrolling
// on Webkit/Blink/IE which is done because there's no selection or selection was somewhere else than widget.
if ( sel ) {
var isDirty = this.editor.checkDirty();
sel.fake( this.wrapper );
!isDirty && this.editor.resetDirty();
}
// Always focus editor (not only when focusManger.hasFocus is false) (because of http://dev.ckeditor.com/ticket/10483).
this.editor.focus();
},
/**
* Removes a class from the widget element. This method is used by
* the {@link #removeStyle} method and should be overriden by widgets
* which should handle classes differently (e.g. on other elements).
*
* **Note**: This method should not be used directly. Use the {@link #setData} method to
* set the `classes` property. Read more in the {@link #setData} documentation.
*
* See also: {@link #hasClass}, {@link #addClass}.
*
* @since 4.4
* @param {String} className The class to be removed.
*/
removeClass: function( className ) {
this.element.removeClass( className );
this.wrapper.removeClass( Widget.WRAPPER_CLASS_PREFIX + className );
},
/**
* Removes the specified style from the widget. It is highly recommended to use the
* {@link CKEDITOR.editor#removeStyle} or {@link CKEDITOR.style#remove} methods instead of
* using this method directly, because unlike editor's and style's methods, this one
* does not perform any checks.
*
* Read more about how applying/removing styles works in the {@link #applyStyle} method documentation.
*
* See also {@link #checkStyleActive}, {@link #applyStyle}, {@link #getClasses}.
*
* @since 4.4
* @param {CKEDITOR.style} style The custom widget style to be removed.
*/
removeStyle: function( style ) {
applyRemoveStyle( this, style, 0 );
},
/**
* Sets widget value(s) in the {@link #property-data} object.
* If the given value(s) modifies current ones, the {@link #event-data} event is fired.
*
* this.setData( 'align', 'left' );
* this.data.align; // -> 'left'
*
* this.setData( { align: 'right', opened: false } );
* this.data.align; // -> 'right'
* this.data.opened; // -> false
*
* Set values are stored in {@link #element}'s attribute (`data-cke-widget-data`),
* in a JSON string, therefore {@link #property-data} should contain
* only serializable data.
*
* **Note:** A special data property, `classes`, exists. It contains an object with
* classes which were returned by the {@link #getClasses} method during the widget initialization.
* This property is then used by the {@link #applyStyle} and {@link #removeStyle} methods.
* When it is changed (the reference to object must be changed!), the widget updates its classes by
* using the {@link #addClass} and {@link #removeClass} methods.
*
* // Adding a new class.
* var classes = CKEDITOR.tools.clone( widget.data.classes );
* classes.newClass = 1;
* widget.setData( 'classes', classes );
*
* // Removing a class.
* var classes = CKEDITOR.tools.clone( widget.data.classes );
* delete classes.newClass;
* widget.setData( 'classes', classes );
*
* @param {String/Object} keyOrData
* @param {Object} value
* @chainable
*/
setData: function( key, value ) {
var data = this.data,
modified = 0;
if ( typeof key == 'string' ) {
if ( data[ key ] !== value ) {
data[ key ] = value;
modified = 1;
}
}
else {
var newData = key;
for ( key in newData ) {
if ( data[ key ] !== newData[ key ] ) {
modified = 1;
data[ key ] = newData[ key ];
}
}
}
// Block firing data event and overwriting data element before setupWidgetData is executed.
if ( modified && this.dataReady ) {
writeDataToElement( this );
this.fire( 'data', data );
}
return this;
},
/**
* Changes the widget's focus state. This method is executed automatically after
* a widget was focused by the {@link #method-focus} method or the selection was moved
* out of the widget.
*
* This is a low-level method which is not integrated with e.g. the undo manager.
* Use the {@link #method-focus} method instead.
*
* @param {Boolean} selected Whether to select or deselect this widget.
* @chainable
*/
setFocused: function( focused ) {
this.wrapper[ focused ? 'addClass' : 'removeClass' ]( 'cke_widget_focused' );
this.fire( focused ? 'focus' : 'blur' );
return this;
},
/**
* Changes the widget's select state. This method is executed automatically after
* a widget was selected by the {@link #method-focus} method or the selection
* was moved out of the widget.
*
* This is a low-level method which is not integrated with e.g. the undo manager.
* Use the {@link #method-focus} method instead or simply change the selection.
*
* @param {Boolean} selected Whether to select or deselect this widget.
* @chainable
*/
setSelected: function( selected ) {
this.wrapper[ selected ? 'addClass' : 'removeClass' ]( 'cke_widget_selected' );
this.fire( selected ? 'select' : 'deselect' );
return this;
},
/**
* Repositions drag handler according to the widget's element position. Should be called from events, like mouseover.
*/
updateDragHandlerPosition: function() {
var editor = this.editor,
domElement = this.element.$,
oldPos = this._.dragHandlerOffset,
newPos = {
x: domElement.offsetLeft,
y: domElement.offsetTop - DRAG_HANDLER_SIZE
};
if ( oldPos && newPos.x == oldPos.x && newPos.y == oldPos.y )
return;
// We need to make sure that dirty state is not changed (http://dev.ckeditor.com/ticket/11487).
var initialDirty = editor.checkDirty();
editor.fire( 'lockSnapshot' );
this.dragHandlerContainer.setStyles( {
top: newPos.y + 'px',
left: newPos.x + 'px',
display: 'block'
} );
editor.fire( 'unlockSnapshot' );
!initialDirty && editor.resetDirty();
this._.dragHandlerOffset = newPos;
}
};
CKEDITOR.event.implementOn( Widget.prototype );
/**
* Gets the {@link #isDomNestedEditable nested editable}
* (returned as a {@link CKEDITOR.dom.element}, not as a {@link CKEDITOR.plugins.widget.nestedEditable})
* closest to the `node` or the `node` if it is a nested editable itself.
*
* @since 4.5
* @static
* @param {CKEDITOR.dom.element} guard Stop ancestor search on this node (usually editor's editable).
* @param {CKEDITOR.dom.node} node Start the search from this node.
* @returns {CKEDITOR.dom.element/null} Element or `null` if not found.
*/
Widget.getNestedEditable = function( guard, node ) {
if ( !node || node.equals( guard ) )
return null;
if ( Widget.isDomNestedEditable( node ) )
return node;
return Widget.getNestedEditable( guard, node.getParent() );
};
/**
* Checks whether the `node` is a widget's drag handle element.
*
* @since 4.5
* @static
* @param {CKEDITOR.dom.node} node
* @returns {Boolean}
*/
Widget.isDomDragHandler = function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-cke-widget-drag-handler' );
};
/**
* Checks whether the `node` is a container of the widget's drag handle element.
*
* @since 4.5
* @static
* @param {CKEDITOR.dom.node} node
* @returns {Boolean}
*/
Widget.isDomDragHandlerContainer = function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT && node.hasClass( 'cke_widget_drag_handler_container' );
};
/**
* Checks whether the `node` is a {@link CKEDITOR.plugins.widget#editables nested editable}.
* Note that this function only checks whether it is the right element, not whether
* the passed `node` is an instance of {@link CKEDITOR.plugins.widget.nestedEditable}.
*
* @since 4.5
* @static
* @param {CKEDITOR.dom.node} node
* @returns {Boolean}
*/
Widget.isDomNestedEditable = function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-cke-widget-editable' );
};
/**
* Checks whether the `node` is a {@link CKEDITOR.plugins.widget#element widget element}.
*
* @since 4.5
* @static
* @param {CKEDITOR.dom.node} node
* @returns {Boolean}
*/
Widget.isDomWidgetElement = function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-widget' );
};
/**
* Checks whether the `node` is a {@link CKEDITOR.plugins.widget#wrapper widget wrapper}.
*
* @since 4.5
* @static
* @param {CKEDITOR.dom.element} node
* @returns {Boolean}
*/
Widget.isDomWidgetWrapper = function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-cke-widget-wrapper' );
};
/**
* Checks whether the `node` is a {@link CKEDITOR.plugins.widget#element widget element}.
*
* @since 4.5
* @static
* @param {CKEDITOR.htmlParser.node} node
* @returns {Boolean}
*/
Widget.isParserWidgetElement = function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT && !!node.attributes[ 'data-widget' ];
};
/**
* Checks whether the `node` is a {@link CKEDITOR.plugins.widget#wrapper widget wrapper}.
*
* @since 4.5
* @static
* @param {CKEDITOR.htmlParser.element} node
* @returns {Boolean}
*/
Widget.isParserWidgetWrapper = function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT && !!node.attributes[ 'data-cke-widget-wrapper' ];
};
/**
* Prefix added to wrapper classes. Each class added to the widget element by the {@link #addClass}
* method will also be added to the wrapper prefixed with it.
*
* @since 4.6.0
* @static
* @readonly
* @property {String} [='cke_widget_wrapper_']
*/
Widget.WRAPPER_CLASS_PREFIX = 'cke_widget_wrapper_';
/**
* An event fired when a widget is ready (fully initialized). This event is fired after:
*
* * {@link #init} is called,
* * The first {@link #event-data} event is fired,
* * A widget is attached to the document.
*
* Therefore, in case of widget creation with a command which opens a dialog window, this event
* will be delayed after the dialog window is closed and the widget is finally inserted into the document.
*
* **Note**: If your widget does not use automatic dialog window binding (i.e. you open the dialog window manually)
* or another situation in which the widget wrapper is not attached to document at the time when it is
* initialized occurs, you need to take care of firing {@link #event-ready} yourself.
*
* See also {@link #property-ready} and {@link #property-inited} properties, and
* {@link #isReady} and {@link #isInited} methods.
*
* @event ready
*/
/**
* An event fired when a widget is about to be destroyed, but before it is
* fully torn down.
*
* @event destroy
*/
/**
* An event fired when a widget is focused.
*
* Widget can be focused by executing {@link #method-focus}.
*
* @event focus
*/
/**
* An event fired when a widget is blurred.
*
* @event blur
*/
/**
* An event fired when a widget is selected.
*
* @event select
*/
/**
* An event fired when a widget is deselected.
*
* @event deselect
*/
/**
* An event fired by the {@link #method-edit} method. It can be canceled
* in order to stop the default action (opening a dialog window and/or
* {@link CKEDITOR.plugins.widget.repository#finalizeCreation finalizing widget creation}).
*
* @event edit
* @param data
* @param {String} data.dialog Defaults to {@link CKEDITOR.plugins.widget.definition#dialog}
* and can be changed or set by the listener.
*/
/**
* An event fired when a dialog window for widget editing is opened.
* This event can be canceled in order to handle the editing dialog in a custom manner.
*
* @event dialog
* @param {CKEDITOR.dialog} data The opened dialog window instance.
*/
/**
* An event fired when a key is pressed on a focused widget.
* This event is forwarded from the {@link CKEDITOR.editor#key} event and
* has the ability to block editor keystrokes if it is canceled.
*
* @event key
* @param data
* @param {Number} data.keyCode A number representing the key code (or combination).
*/
/**
* An event fired when a widget is double clicked.
*
* **Note:** If a default editing action is executed on double click (i.e. a widget has a
* {@link CKEDITOR.plugins.widget.definition#dialog dialog} defined and the {@link #event-doubleclick} event was not
* canceled), this event will be automatically canceled, so a listener added with the default priority (10)
* will not be executed. Use a listener with low priority (e.g. 5) to be sure that it will be executed.
*
* widget.on( 'doubleclick', function( evt ) {
* console.log( 'widget#doubleclick' );
* }, null, null, 5 );
*
* If your widget handles double click in a special way (so the default editing action is not executed),
* make sure you cancel this event, because otherwise it will be propagated to {@link CKEDITOR.editor#doubleclick}
* and another feature may step in (e.g. a Link dialog window may be opened if your widget was inside a link).
*
* @event doubleclick
* @param data
* @param {CKEDITOR.dom.element} data.element The double-clicked element.
*/
/**
* An event fired when the context menu is opened for a widget.
*
* @event contextMenu
* @param data The object containing context menu options to be added
* for this widget. See {@link CKEDITOR.plugins.contextMenu#addListener}.
*/
/**
* An event fired when the widget data changed. See the {@link #setData} method and the {@link #property-data} property.
*
* @event data
*/
/**
* The wrapper class for editable elements inside widgets.
*
* Do not use directly. Use {@link CKEDITOR.plugins.widget.definition#editables} or
* {@link CKEDITOR.plugins.widget#initEditable}.
*
* @class CKEDITOR.plugins.widget.nestedEditable
* @extends CKEDITOR.dom.element
* @constructor
* @param {CKEDITOR.editor} editor
* @param {CKEDITOR.dom.element} element
* @param config
* @param {CKEDITOR.filter} [config.filter]
*/
function NestedEditable( editor, element, config ) {
// Call the base constructor.
CKEDITOR.dom.element.call( this, element.$ );
this.editor = editor;
this._ = {};
var filter = this.filter = config.filter;
// If blockless editable - always use BR mode.
if ( !CKEDITOR.dtd[ this.getName() ].p )
this.enterMode = this.shiftEnterMode = CKEDITOR.ENTER_BR;
else {
this.enterMode = filter ? filter.getAllowedEnterMode( editor.enterMode ) : editor.enterMode;
this.shiftEnterMode = filter ? filter.getAllowedEnterMode( editor.shiftEnterMode, true ) : editor.shiftEnterMode;
}
}
NestedEditable.prototype = CKEDITOR.tools.extend( CKEDITOR.tools.prototypedCopy( CKEDITOR.dom.element.prototype ), {
/**
* Sets the editable data. The data will be passed through the {@link CKEDITOR.editor#dataProcessor}
* and the {@link CKEDITOR.editor#filter}. This ensures that the data was filtered and prepared to be
* edited like the {@link CKEDITOR.editor#method-setData editor data}.
*
* Before content is changed, all nested widgets are destroyed. Afterwards, after new content is loaded,
* all nested widgets are initialized.
*
* @param {String} data
*/
setData: function( data ) {
// For performance reasons don't call destroyAll when initializing a nested editable,
// because there are no widgets inside.
if ( !this._.initialSetData ) {
// Destroy all nested widgets before setting data.
this.editor.widgets.destroyAll( false, this );
}
this._.initialSetData = false;
data = this.editor.dataProcessor.toHtml( data, {
context: this.getName(),
filter: this.filter,
enterMode: this.enterMode
} );
this.setHtml( data );
this.editor.widgets.initOnAll( this );
},
/**
* Gets the editable data. Like {@link #setData}, this method will process and filter the data.
*
* @returns {String}
*/
getData: function() {
return this.editor.dataProcessor.toDataFormat( this.getHtml(), {
context: this.getName(),
filter: this.filter,
enterMode: this.enterMode
} );
}
} );
/**
* The editor instance.
*
* @readonly
* @property {CKEDITOR.editor} editor
*/
/**
* The filter instance if allowed content rules were defined.
*
* @readonly
* @property {CKEDITOR.filter} filter
*/
/**
* The enter mode active in this editable.
* It is determined from editable's name (whether it is a blockless editable),
* its allowed content rules (if defined) and the default editor's mode.
*
* @readonly
* @property {Number} enterMode
*/
/**
* The shift enter move active in this editable.
*
* @readonly
* @property {Number} shiftEnterMode
*/
//
// REPOSITORY helpers -----------------------------------------------------
//
function addWidgetButtons( editor ) {
var widgets = editor.widgets.registered,
widget,
widgetName,
widgetButton;
for ( widgetName in widgets ) {
widget = widgets[ widgetName ];
// Create button if defined.
widgetButton = widget.button;
if ( widgetButton && editor.ui.addButton ) {
editor.ui.addButton( CKEDITOR.tools.capitalize( widget.name, true ), {
label: widgetButton,
command: widget.name,
toolbar: 'insert,10'
} );
}
}
}
// Create a command creating and editing widget.
//
// @param editor
// @param {CKEDITOR.plugins.widget.definition} widgetDef
function addWidgetCommand( editor, widgetDef ) {
editor.addCommand( widgetDef.name, {
exec: function( editor, commandData ) {
var focused = editor.widgets.focused;
// If a widget of the same type is focused, start editing.
if ( focused && focused.name == widgetDef.name )
focused.edit();
// Otherwise...
// ... use insert method is was defined.
else if ( widgetDef.insert )
widgetDef.insert();
// ... or create a brand-new widget from template.
else if ( widgetDef.template ) {
var defaults = typeof widgetDef.defaults == 'function' ? widgetDef.defaults() : widgetDef.defaults,
element = CKEDITOR.dom.element.createFromHtml( widgetDef.template.output( defaults ) ),
instance,
wrapper = editor.widgets.wrapElement( element, widgetDef.name ),
temp = new CKEDITOR.dom.documentFragment( wrapper.getDocument() );
// Append wrapper to a temporary document. This will unify the environment
// in which #data listeners work when creating and editing widget.
temp.append( wrapper );
instance = editor.widgets.initOn( element, widgetDef, commandData && commandData.startupData );
// Instance could be destroyed during initialization.
// In this case finalize creation if some new widget
// was left in temporary document fragment.
if ( !instance ) {
finalizeCreation();
return;
}
// Listen on edit to finalize widget insertion.
//
// * If dialog was set, then insert widget after dialog was successfully saved or destroy this
// temporary instance.
// * If dialog wasn't set and edit wasn't canceled, insert widget.
var editListener = instance.once( 'edit', function( evt ) {
if ( evt.data.dialog ) {
instance.once( 'dialog', function( evt ) {
var dialog = evt.data,
okListener,
cancelListener;
// Finalize creation AFTER (20) new data was set.
okListener = dialog.once( 'ok', finalizeCreation, null, null, 20 );
cancelListener = dialog.once( 'cancel', function( evt ) {
if ( !( evt.data && evt.data.hide === false ) ) {
editor.widgets.destroy( instance, true );
}
} );
dialog.once( 'hide', function() {
okListener.removeListener();
cancelListener.removeListener();
} );
} );
} else {
// Dialog hasn't been set, so insert widget now.
finalizeCreation();
}
}, null, null, 999 );
instance.edit();
// Remove listener in case someone canceled it before this
// listener was executed.
editListener.removeListener();
}
function finalizeCreation() {
editor.widgets.finalizeCreation( temp );
}
},
allowedContent: widgetDef.allowedContent,
requiredContent: widgetDef.requiredContent,
contentForms: widgetDef.contentForms,
contentTransformations: widgetDef.contentTransformations
} );
}
function addWidgetProcessors( widgetsRepo, widgetDef ) {
var upcast = widgetDef.upcast,
upcasts,
priority = widgetDef.upcastPriority || 10;
if ( !upcast )
return;
// Multiple upcasts defined in string.
if ( typeof upcast == 'string' ) {
upcasts = upcast.split( ',' );
while ( upcasts.length ) {
addUpcast( widgetDef.upcasts[ upcasts.pop() ], widgetDef.name, priority );
}
}
// Single rule which is automatically activated.
else {
addUpcast( upcast, widgetDef.name, priority );
}
function addUpcast( upcast, name, priority ) {
// Find index of the first higher (in terms of value) priority upcast.
var index = CKEDITOR.tools.getIndex( widgetsRepo._.upcasts, function( element ) {
return element[ 2 ] > priority;
} );
// Add at the end if it is the highest priority so far.
if ( index < 0 ) {
index = widgetsRepo._.upcasts.length;
}
widgetsRepo._.upcasts.splice( index, 0, [ upcast, name, priority ] );
}
}
function blurWidget( widgetsRepo, widget ) {
widgetsRepo.focused = null;
if ( widget.isInited() ) {
var isDirty = widget.editor.checkDirty();
// Widget could be destroyed in the meantime - e.g. data could be set.
widgetsRepo.fire( 'widgetBlurred', { widget: widget } );
widget.setFocused( false );
!isDirty && widget.editor.resetDirty();
}
}
function checkWidgets( evt ) {
var options = evt.data;
if ( this.editor.mode != 'wysiwyg' )
return;
var editable = this.editor.editable(),
instances = this.instances,
newInstances, i, count, wrapper, notYetInitialized;
if ( !editable )
return;
// Remove widgets which have no corresponding elements in DOM.
for ( i in instances ) {
// http://dev.ckeditor.com/ticket/13410 Remove widgets that are ready. This prevents from destroying widgets that are during loading process.
if ( instances[ i ].isReady() && !editable.contains( instances[ i ].wrapper ) )
this.destroy( instances[ i ], true );
}
// Init on all (new) if initOnlyNew option was passed.
if ( options && options.initOnlyNew )
newInstances = this.initOnAll();
else {
var wrappers = editable.find( '.cke_widget_wrapper' );
newInstances = [];
// Create widgets on existing wrappers if they do not exists.
for ( i = 0, count = wrappers.count(); i < count; i++ ) {
wrapper = wrappers.getItem( i );
notYetInitialized = !this.getByElement( wrapper, true );
// Check if:
// * there's no instance for this widget
// * wrapper is not inside some temporary element like copybin (http://dev.ckeditor.com/ticket/11088)
// * it was a nested widget's wrapper which has been detached from DOM,
// when nested editable has been initialized (it overwrites its innerHTML
// and initializes nested widgets).
if ( notYetInitialized && !findParent( wrapper, isDomTemp ) && editable.contains( wrapper ) ) {
// Add cke_widget_new class because otherwise
// widget will not be created on such wrapper.
wrapper.addClass( 'cke_widget_new' );
newInstances.push( this.initOn( wrapper.getFirst( Widget.isDomWidgetElement ) ) );
}
}
}
// If only single widget was initialized and focusInited was passed, focus it.
if ( options && options.focusInited && newInstances.length == 1 )
newInstances[ 0 ].focus();
}
// Unwraps widget element and clean up element.
//
// This function is used to clean up pasted widgets.
// It should have similar result to widget#destroy plus
// some additional adjustments, specific for pasting.
//
// @param {CKEDITOR.htmlParser.element} el
function cleanUpWidgetElement( el ) {
var parent = el.parent;
if ( parent.type == CKEDITOR.NODE_ELEMENT && parent.attributes[ 'data-cke-widget-wrapper' ] )
parent.replaceWith( el );
}
// Similar to cleanUpWidgetElement, but works on DOM and finds
// widget elements by its own.
//
// Unlike cleanUpWidgetElement it will wrap element back.
//
// @param {CKEDITOR.dom.element} container
function cleanUpAllWidgetElements( widgetsRepo, container ) {
var wrappers = container.find( '.cke_widget_wrapper' ),
wrapper, element,
i = 0,
l = wrappers.count();
for ( ; i < l; ++i ) {
wrapper = wrappers.getItem( i );
element = wrapper.getFirst( Widget.isDomWidgetElement );
// If wrapper contains widget element - unwrap it and wrap again.
if ( element.type == CKEDITOR.NODE_ELEMENT && element.data( 'widget' ) ) {
element.replace( wrapper );
widgetsRepo.wrapElement( element );
} else {
// Otherwise - something is wrong... clean this up.
wrapper.remove();
}
}
}
// Creates {@link CKEDITOR.filter} instance for given widget, editable and rules.
//
// Once filter for widget-editable pair is created it is cached, so the same instance
// will be returned when method is executed again.
//
// @param {String} widgetName
// @param {String} editableName
// @param {CKEDITOR.plugins.widget.nestedEditableDefinition} editableDefinition The nested editable definition.
// @returns {CKEDITOR.filter} Filter instance or `null` if rules are not defined.
// @context CKEDITOR.plugins.widget.repository
function createEditableFilter( widgetName, editableName, editableDefinition ) {
if ( !editableDefinition.allowedContent )
return null;
var editables = this._.filters[ widgetName ];
if ( !editables )
this._.filters[ widgetName ] = editables = {};
var filter = editables[ editableName ];
if ( !filter )
editables[ editableName ] = filter = new CKEDITOR.filter( editableDefinition.allowedContent );
return filter;
}
// Creates an iterator function which when executed on all
// elements in DOM tree will gather elements that should be wrapped
// and initialized as widgets.
function createUpcastIterator( widgetsRepo ) {
var toBeWrapped = [],
upcasts = widgetsRepo._.upcasts,
upcastCallbacks = widgetsRepo._.upcastCallbacks;
return {
toBeWrapped: toBeWrapped,
iterator: function( element ) {
var upcast, upcasted,
data,
i,
upcastsLength,
upcastCallbacksLength;
// Wrapper found - find widget element, add it to be
// cleaned up (unwrapped) and wrapped and stop iterating in this branch.
if ( 'data-cke-widget-wrapper' in element.attributes ) {
element = element.getFirst( Widget.isParserWidgetElement );
if ( element )
toBeWrapped.push( [ element ] );
// Do not iterate over descendants.
return false;
}
// Widget element found - add it to be cleaned up (just in case)
// and wrapped and stop iterating in this branch.
else if ( 'data-widget' in element.attributes ) {
toBeWrapped.push( [ element ] );
// Do not iterate over descendants.
return false;
}
else if ( ( upcastsLength = upcasts.length ) ) {
// Ignore elements with data-cke-widget-upcasted to avoid multiple upcasts (http://dev.ckeditor.com/ticket/11533).
// Do not iterate over descendants.
if ( element.attributes[ 'data-cke-widget-upcasted' ] )
return false;
// Check element with upcast callbacks first.
// If any of them return false abort upcasting.
for ( i = 0, upcastCallbacksLength = upcastCallbacks.length; i < upcastCallbacksLength; ++i ) {
if ( upcastCallbacks[ i ]( element ) === false )
return;
// Return nothing in order to continue iterating over ascendants.
// See http://dev.ckeditor.com/ticket/11186#comment:6
}
for ( i = 0; i < upcastsLength; ++i ) {
upcast = upcasts[ i ];
data = {};
if ( ( upcasted = upcast[ 0 ]( element, data ) ) ) {
// If upcast function returned element, upcast this one.
// It can be e.g. a new element wrapping the original one.
if ( upcasted instanceof CKEDITOR.htmlParser.element )
element = upcasted;
// Set initial data attr with data from upcast method.
element.attributes[ 'data-cke-widget-data' ] = encodeURIComponent( JSON.stringify( data ) );
element.attributes[ 'data-cke-widget-upcasted' ] = 1;
toBeWrapped.push( [ element, upcast[ 1 ] ] );
// Do not iterate over descendants.
return false;
}
}
}
}
};
}
// Finds a first parent that matches query.
//
// @param {CKEDITOR.dom.element} element
// @param {Function} query
function findParent( element, query ) {
var parent = element;
while ( ( parent = parent.getParent() ) ) {
if ( query( parent ) )
return true;
}
return false;
}
function getWrapperAttributes( inlineWidget, name ) {
return {
// tabindex="-1" means that it can receive focus by code.
tabindex: -1,
contenteditable: 'false',
'data-cke-widget-wrapper': 1,
'data-cke-filter': 'off',
// Class cke_widget_new marks widgets which haven't been initialized yet.
'class': 'cke_widget_wrapper cke_widget_new cke_widget_' +
( inlineWidget ? 'inline' : 'block' ) +
( name ? ' cke_widget_' + name : '' )
};
}
// Inserts element at given index.
// It will check DTD and split ancestor elements up to the first
// that can contain this element.
//
// @param {CKEDITOR.htmlParser.element} parent
// @param {Number} index
// @param {CKEDITOR.htmlParser.element} element
function insertElement( parent, index, element ) {
// Do not split doc fragment...
if ( parent.type == CKEDITOR.NODE_ELEMENT ) {
var parentAllows = CKEDITOR.dtd[ parent.name ];
// Parent element is known (included in DTD) and cannot contain
// this element.
if ( parentAllows && !parentAllows[ element.name ] ) {
var parent2 = parent.split( index ),
parentParent = parent.parent;
// Element will now be inserted at right parent's index.
index = parent2.getIndex();
// If left part of split is empty - remove it.
if ( !parent.children.length ) {
index -= 1;
parent.remove();
}
// If right part of split is empty - remove it.
if ( !parent2.children.length )
parent2.remove();
// Try inserting as grandpas' children.
return insertElement( parentParent, index, element );
}
}
// Finally we can add this element.
parent.add( element, index );
}
// Checks whether for the given widget definition and element widget should be created in inline or block mode.
//
// See also: {@link CKEDITOR.plugins.widget.definition#inline} and {@link CKEDITOR.plugins.widget#element}.
//
// @param {CKEDITOR.plugins.widget.definition} widgetDef The widget definition.
// @param {String} elementName The name of the widget element.
// @returns {Boolean}
function isWidgetInline( widgetDef, elementName ) {
return typeof widgetDef.inline == 'boolean' ? widgetDef.inline : !!CKEDITOR.dtd.$inline[ elementName ];
}
// @param {CKEDITOR.dom.element}
// @returns {Boolean}
function isDomTemp( element ) {
return element.hasAttribute( 'data-cke-temp' );
}
function onEditableKey( widget, keyCode ) {
var focusedEditable = widget.focusedEditable,
range;
// CTRL+A.
if ( keyCode == CKEDITOR.CTRL + 65 ) {
var bogus = focusedEditable.getBogus();
range = widget.editor.createRange();
range.selectNodeContents( focusedEditable );
// Exclude bogus if exists.
if ( bogus )
range.setEndAt( bogus, CKEDITOR.POSITION_BEFORE_START );
range.select();
// Cancel event - block default.
return false;
}
// DEL or BACKSPACE.
else if ( keyCode == 8 || keyCode == 46 ) {
var ranges = widget.editor.getSelection().getRanges();
range = ranges[ 0 ];
// Block del or backspace if at editable's boundary.
return !( ranges.length == 1 && range.collapsed &&
range.checkBoundaryOfElement( focusedEditable, CKEDITOR[ keyCode == 8 ? 'START' : 'END' ] ) );
}
}
function setFocusedEditable( widgetsRepo, widget, editableElement, offline ) {
var editor = widgetsRepo.editor;
editor.fire( 'lockSnapshot' );
if ( editableElement ) {
var editableName = editableElement.data( 'cke-widget-editable' ),
editableInstance = widget.editables[ editableName ];
widgetsRepo.widgetHoldingFocusedEditable = widget;
widget.focusedEditable = editableInstance;
editableElement.addClass( 'cke_widget_editable_focused' );
if ( editableInstance.filter )
editor.setActiveFilter( editableInstance.filter );
editor.setActiveEnterMode( editableInstance.enterMode, editableInstance.shiftEnterMode );
} else {
if ( !offline )
widget.focusedEditable.removeClass( 'cke_widget_editable_focused' );
widget.focusedEditable = null;
widgetsRepo.widgetHoldingFocusedEditable = null;
editor.setActiveFilter( null );
editor.setActiveEnterMode( null, null );
}
editor.fire( 'unlockSnapshot' );
}
function setupContextMenu( editor ) {
if ( !editor.contextMenu )
return;
editor.contextMenu.addListener( function( element ) {
var widget = editor.widgets.getByElement( element, true );
if ( widget )
return widget.fire( 'contextMenu', {} );
} );
}
// And now we've got two problems - original problem and RegExp.
// Some softeners:
// * FF tends to copy all blocks up to the copybin container.
// * IE tends to copy only the copybin, without its container.
// * We use spans on IE and blockless editors, but divs in other cases.
var pasteReplaceRegex = new RegExp(
'^' +
'(?:<(?:div|span)(?: data-cke-temp="1")?(?: id="cke_copybin")?(?: data-cke-temp="1")?>)?' +
'(?:<(?:div|span)(?: style="[^"]+")?>)?' +
'<span [^>]*data-cke-copybin-start="1"[^>]*>.?</span>([\\s\\S]+)<span [^>]*data-cke-copybin-end="1"[^>]*>.?</span>' +
'(?:</(?:div|span)>)?' +
'(?:</(?:div|span)>)?' +
'$',
// IE8 prefers uppercase when browsers stick to lowercase HTML (http://dev.ckeditor.com/ticket/13460).
'i'
);
function pasteReplaceFn( match, wrapperHtml ) {
// Avoid polluting pasted data with any whitspaces,
// what's going to break check whether only one widget was pasted.
return CKEDITOR.tools.trim( wrapperHtml );
}
function setupDragAndDrop( widgetsRepo ) {
var editor = widgetsRepo.editor,
lineutils = CKEDITOR.plugins.lineutils;
// These listeners handle inline and block widgets drag and drop.
// The only thing we need to do to make block widgets custom drag and drop functionality
// is to fire those events with the right properties (like the target which must be the drag handle).
editor.on( 'dragstart', function( evt ) {
var target = evt.data.target;
if ( Widget.isDomDragHandler( target ) ) {
var widget = widgetsRepo.getByElement( target );
evt.data.dataTransfer.setData( 'cke/widget-id', widget.id );
// IE needs focus.
editor.focus();
// and widget need to be focused on drag start (http://dev.ckeditor.com/ticket/12172#comment:10).
widget.focus();
}
} );
editor.on( 'drop', function( evt ) {
var dataTransfer = evt.data.dataTransfer,
id = dataTransfer.getData( 'cke/widget-id' ),
transferType = dataTransfer.getTransferType( editor ),
dragRange = editor.createRange(),
sourceWidget;
// Disable cross-editor drag & drop for widgets - http://dev.ckeditor.com/ticket/13599.
if ( id !== '' && transferType === CKEDITOR.DATA_TRANSFER_CROSS_EDITORS ) {
evt.cancel();
return;
}
if ( id === '' || transferType != CKEDITOR.DATA_TRANSFER_INTERNAL ) {
return;
}
sourceWidget = widgetsRepo.instances[ id ];
if ( !sourceWidget ) {
return;
}
dragRange.setStartBefore( sourceWidget.wrapper );
dragRange.setEndAfter( sourceWidget.wrapper );
evt.data.dragRange = dragRange;
// [IE8-9] Reset state of the clipboard#fixSplitNodesAfterDrop fix because by setting evt.data.dragRange
// (see above) after drop happened we do not need it. That fix is needed only if dragRange was created
// before drop (before text node was split).
delete CKEDITOR.plugins.clipboard.dragStartContainerChildCount;
delete CKEDITOR.plugins.clipboard.dragEndContainerChildCount;
evt.data.dataTransfer.setData( 'text/html', editor.editable().getHtmlFromRange( dragRange ).getHtml() );
editor.widgets.destroy( sourceWidget, true );
} );
editor.on( 'contentDom', function() {
var editable = editor.editable();
// Register Lineutils's utilities as properties of repo.
CKEDITOR.tools.extend( widgetsRepo, {
finder: new lineutils.finder( editor, {
lookups: {
// Element is block but not list item and not in nested editable.
'default': function( el ) {
if ( el.is( CKEDITOR.dtd.$listItem ) )
return;
if ( !el.is( CKEDITOR.dtd.$block ) )
return;
// Allow drop line inside, but never before or after nested editable (http://dev.ckeditor.com/ticket/12006).
if ( Widget.isDomNestedEditable( el ) )
return;
// Do not allow droping inside the widget being dragged (http://dev.ckeditor.com/ticket/13397).
if ( widgetsRepo._.draggedWidget.wrapper.contains( el ) ) {
return;
}
// If element is nested editable, make sure widget can be dropped there (http://dev.ckeditor.com/ticket/12006).
var nestedEditable = Widget.getNestedEditable( editable, el );
if ( nestedEditable ) {
var draggedWidget = widgetsRepo._.draggedWidget;
// Don't let the widget to be dropped into its own nested editable.
if ( widgetsRepo.getByElement( nestedEditable ) == draggedWidget )
return;
var filter = CKEDITOR.filter.instances[ nestedEditable.data( 'cke-filter' ) ],
draggedRequiredContent = draggedWidget.requiredContent;
// There will be no relation if the filter of nested editable does not allow
// requiredContent of dragged widget.
if ( filter && draggedRequiredContent && !filter.check( draggedRequiredContent ) )
return;
}
return CKEDITOR.LINEUTILS_BEFORE | CKEDITOR.LINEUTILS_AFTER;
}
}
} ),
locator: new lineutils.locator( editor ),
liner: new lineutils.liner( editor, {
lineStyle: {
cursor: 'move !important',
'border-top-color': '#666'
},
tipLeftStyle: {
'border-left-color': '#666'
},
tipRightStyle: {
'border-right-color': '#666'
}
} )
}, true );
} );
}
// Setup mouse observer which will trigger:
// * widget focus on widget click,
// * widget#doubleclick forwarded from editor#doubleclick.
function setupMouseObserver( widgetsRepo ) {
var editor = widgetsRepo.editor;
editor.on( 'contentDom', function() {
var editable = editor.editable(),
evtRoot = editable.isInline() ? editable : editor.document,
widget,
mouseDownOnDragHandler;
editable.attachListener( evtRoot, 'mousedown', function( evt ) {
var target = evt.data.getTarget();
// http://dev.ckeditor.com/ticket/10887 Clicking scrollbar in IE8 will invoke event with empty target object.
if ( !target.type )
return false;
widget = widgetsRepo.getByElement( target );
mouseDownOnDragHandler = 0; // Reset.
// Widget was clicked, but not editable nested in it.
if ( widget ) {
// Ignore mousedown on drag and drop handler if the widget is inline.
// Block widgets are handled by Lineutils.
if ( widget.inline && target.type == CKEDITOR.NODE_ELEMENT && target.hasAttribute( 'data-cke-widget-drag-handler' ) ) {
mouseDownOnDragHandler = 1;
// When drag handler is pressed we have to clear current selection if it wasn't already on this widget.
// Otherwise, the selection may be in a fillingChar, which prevents dragging a widget. (http://dev.ckeditor.com/ticket/13284, see comment 8 and 9.)
if ( widgetsRepo.focused != widget )
editor.getSelection().removeAllRanges();
return;
}
if ( !Widget.getNestedEditable( widget.wrapper, target ) ) {
evt.data.preventDefault();
if ( !CKEDITOR.env.ie )
widget.focus();
} else {
// Reset widget so mouseup listener is not confused.
widget = null;
}
}
} );
// Focus widget on mouseup if mousedown was fired on drag handler.
// Note: mouseup won't be fired at all if widget was dragged and dropped, so
// this code will be executed only when drag handler was clicked.
editable.attachListener( evtRoot, 'mouseup', function() {
// Check if widget is not destroyed (if widget is destroyed the wrapper will be null).
if ( mouseDownOnDragHandler && widget && widget.wrapper ) {
mouseDownOnDragHandler = 0;
widget.focus();
}
} );
// On IE it is not enough to block mousedown. If widget wrapper (element with
// contenteditable=false attribute) is clicked directly (it is a target),
// then after mouseup/click IE will select that element.
// It is not possible to prevent that default action,
// so we force fake selection after everything happened.
if ( CKEDITOR.env.ie ) {
editable.attachListener( evtRoot, 'mouseup', function() {
setTimeout( function() {
// Check if widget is not destroyed (if widget is destroyed the wrapper will be null) and
// in editable contains widget (it could be dragged and removed).
if ( widget && widget.wrapper && editable.contains( widget.wrapper ) ) {
widget.focus();
widget = null;
}
} );
} );
}
} );
editor.on( 'doubleclick', function( evt ) {
var widget = widgetsRepo.getByElement( evt.data.element );
// Not in widget or in nested editable.
if ( !widget || Widget.getNestedEditable( widget.wrapper, evt.data.element ) )
return;
return widget.fire( 'doubleclick', { element: evt.data.element } );
}, null, null, 1 );
}
// Setup editor#key observer which will forward it
// to focused widget.
function setupKeyboardObserver( widgetsRepo ) {
var editor = widgetsRepo.editor;
editor.on( 'key', function( evt ) {
var focused = widgetsRepo.focused,
widgetHoldingFocusedEditable = widgetsRepo.widgetHoldingFocusedEditable,
ret;
if ( focused )
ret = focused.fire( 'key', { keyCode: evt.data.keyCode } );
else if ( widgetHoldingFocusedEditable )
ret = onEditableKey( widgetHoldingFocusedEditable, evt.data.keyCode );
return ret;
}, null, null, 1 );
}
// Setup copybin on native copy and cut events in order to handle copy and cut commands
// if user accepted security alert on IEs.
// Note: when copying or cutting using keystroke, copySingleWidget will be first executed
// by the keydown listener. Conflict between two calls will be resolved by copy_bin existence check.
function setupNativeCutAndCopy( widgetsRepo ) {
var editor = widgetsRepo.editor;
editor.on( 'contentDom', function() {
var editable = editor.editable();
editable.attachListener( editable, 'copy', eventListener );
editable.attachListener( editable, 'cut', eventListener );
} );
function eventListener( evt ) {
if ( widgetsRepo.focused )
copySingleWidget( widgetsRepo.focused, evt.name == 'cut' );
}
}
// Setup selection observer which will trigger:
// * widget select & focus on selection change,
// * nested editable focus (related properites and classes) on selection change,
// * deselecting and blurring all widgets on data,
// * blurring widget on editor blur.
function setupSelectionObserver( widgetsRepo ) {
var editor = widgetsRepo.editor;
editor.on( 'selectionCheck', function() {
widgetsRepo.fire( 'checkSelection' );
} );
widgetsRepo.on( 'checkSelection', widgetsRepo.checkSelection, widgetsRepo );
editor.on( 'selectionChange', function( evt ) {
var nestedEditable = Widget.getNestedEditable( editor.editable(), evt.data.selection.getStartElement() ),
newWidget = nestedEditable && widgetsRepo.getByElement( nestedEditable ),
oldWidget = widgetsRepo.widgetHoldingFocusedEditable;
if ( oldWidget ) {
if ( oldWidget !== newWidget || !oldWidget.focusedEditable.equals( nestedEditable ) ) {
setFocusedEditable( widgetsRepo, oldWidget, null );
if ( newWidget && nestedEditable )
setFocusedEditable( widgetsRepo, newWidget, nestedEditable );
}
}
// It may happen that there's no widget even if editable was found -
// e.g. if selection was automatically set in editable although widget wasn't initialized yet.
else if ( newWidget && nestedEditable ) {
setFocusedEditable( widgetsRepo, newWidget, nestedEditable );
}
} );
// Invalidate old widgets early - immediately on dataReady.
editor.on( 'dataReady', function() {
// Deselect and blur all widgets.
stateUpdater( widgetsRepo ).commit();
} );
editor.on( 'blur', function() {
var widget;
if ( ( widget = widgetsRepo.focused ) )
blurWidget( widgetsRepo, widget );
if ( ( widget = widgetsRepo.widgetHoldingFocusedEditable ) )
setFocusedEditable( widgetsRepo, widget, null );
} );
}
// Set up actions like:
// * processing in toHtml/toDataFormat,
// * pasting handling,
// * insertion handling,
// * editable reload handling (setData, mode switch, undo/redo),
// * DOM invalidation handling,
// * widgets checks.
function setupWidgetsLifecycle( widgetsRepo ) {
setupWidgetsLifecycleStart( widgetsRepo );
setupWidgetsLifecycleEnd( widgetsRepo );
widgetsRepo.on( 'checkWidgets', checkWidgets );
widgetsRepo.editor.on( 'contentDomInvalidated', widgetsRepo.checkWidgets, widgetsRepo );
}
function setupWidgetsLifecycleEnd( widgetsRepo ) {
var editor = widgetsRepo.editor,
downcastingSessions = {};
// Listen before htmlDP#htmlFilter is applied to cache all widgets, because we'll
// loose data-cke-* attributes.
editor.on( 'toDataFormat', function( evt ) {
// To avoid conflicts between htmlDP#toDF calls done at the same time
// (e.g. nestedEditable#getData called during downcasting some widget)
// mark every toDataFormat event chain with the downcasting session id.
var id = CKEDITOR.tools.getNextNumber(),
toBeDowncasted = [];
evt.data.downcastingSessionId = id;
downcastingSessions[ id ] = toBeDowncasted;
evt.data.dataValue.forEach( function( element ) {
var attrs = element.attributes,
widget, widgetElement;
// Wrapper.
// Perform first part of downcasting (cleanup) and cache widgets,
// because after applying DP's filter all data-cke-* attributes will be gone.
if ( 'data-cke-widget-id' in attrs ) {
widget = widgetsRepo.instances[ attrs[ 'data-cke-widget-id' ] ];
if ( widget ) {
widgetElement = element.getFirst( Widget.isParserWidgetElement );
toBeDowncasted.push( {
wrapper: element,
element: widgetElement,
widget: widget,
editables: {}
} );
// If widget did not have data-cke-widget attribute before upcasting remove it.
if ( widgetElement.attributes[ 'data-cke-widget-keep-attr' ] != '1' )
delete widgetElement.attributes[ 'data-widget' ];
}
}
// Nested editable.
else if ( 'data-cke-widget-editable' in attrs ) {
// Save the reference to this nested editable in the closest widget to be downcasted.
// Nested editables are downcasted in the successive toDataFormat to create an opportunity
// for dataFilter's "excludeNestedEditable" option to do its job (that option relies on
// contenteditable="true" attribute) (http://dev.ckeditor.com/ticket/11372).
toBeDowncasted[ toBeDowncasted.length - 1 ].editables[ attrs[ 'data-cke-widget-editable' ] ] = element;
// Don't check children - there won't be next wrapper or nested editable which we
// should process in this session.
return false;
}
}, CKEDITOR.NODE_ELEMENT, true );
}, null, null, 8 );
// Listen after dataProcessor.htmlFilter and ACF were applied
// so wrappers securing widgets' contents are removed after all filtering was done.
editor.on( 'toDataFormat', function( evt ) {
// Ignore some unmarked sessions.
if ( !evt.data.downcastingSessionId )
return;
var toBeDowncasted = downcastingSessions[ evt.data.downcastingSessionId ],
toBe, widget, widgetElement, retElement, editableElement, e;
while ( ( toBe = toBeDowncasted.shift() ) ) {
widget = toBe.widget;
widgetElement = toBe.element;
retElement = widget._.downcastFn && widget._.downcastFn.call( widget, widgetElement );
// Replace nested editables' content with their output data.
for ( e in toBe.editables ) {
editableElement = toBe.editables[ e ];
delete editableElement.attributes.contenteditable;
editableElement.setHtml( widget.editables[ e ].getData() );
}
// Returned element always defaults to widgetElement.
if ( !retElement )
retElement = widgetElement;
toBe.wrapper.replaceWith( retElement );
}
}, null, null, 13 );
editor.on( 'contentDomUnload', function() {
widgetsRepo.destroyAll( true );
} );
}
function setupWidgetsLifecycleStart( widgetsRepo ) {
var editor = widgetsRepo.editor,
processedWidgetOnly,
snapshotLoaded;
// Listen after ACF (so data are filtered),
// but before dataProcessor.dataFilter was applied (so we can secure widgets' internals).
editor.on( 'toHtml', function( evt ) {
var upcastIterator = createUpcastIterator( widgetsRepo ),
toBeWrapped;
evt.data.dataValue.forEach( upcastIterator.iterator, CKEDITOR.NODE_ELEMENT, true );
// Clean up and wrap all queued elements.
while ( ( toBeWrapped = upcastIterator.toBeWrapped.pop() ) ) {
cleanUpWidgetElement( toBeWrapped[ 0 ] );
widgetsRepo.wrapElement( toBeWrapped[ 0 ], toBeWrapped[ 1 ] );
}
// Used to determine whether only widget was pasted.
if ( evt.data.protectedWhitespaces ) {
// Whitespaces are protected by wrapping content with spans. Take the middle node only.
processedWidgetOnly = evt.data.dataValue.children.length == 3 &&
Widget.isParserWidgetWrapper( evt.data.dataValue.children[ 1 ] );
} else {
processedWidgetOnly = evt.data.dataValue.children.length == 1 &&
Widget.isParserWidgetWrapper( evt.data.dataValue.children[ 0 ] );
}
}, null, null, 8 );
editor.on( 'dataReady', function() {
// Clean up all widgets loaded from snapshot.
if ( snapshotLoaded )
cleanUpAllWidgetElements( widgetsRepo, editor.editable() );
snapshotLoaded = 0;
// Some widgets were destroyed on contentDomUnload,
// some on loadSnapshot, but that does not include
// e.g. setHtml on inline editor or widgets removed just
// before setting data.
widgetsRepo.destroyAll( true );
widgetsRepo.initOnAll();
} );
// Set flag so dataReady will know that additional
// cleanup is needed, because snapshot containing widgets was loaded.
editor.on( 'loadSnapshot', function( evt ) {
// Primitive but sufficient check which will prevent from executing
// heavier cleanUpAllWidgetElements if not needed.
if ( ( /data-cke-widget/ ).test( evt.data ) )
snapshotLoaded = 1;
widgetsRepo.destroyAll( true );
}, null, null, 9 );
// Handle pasted single widget.
editor.on( 'paste', function( evt ) {
var data = evt.data;
data.dataValue = data.dataValue.replace( pasteReplaceRegex, pasteReplaceFn );
// If drag'n'drop kind of paste into nested editable (data.range), selection is set AFTER
// data is pasted, which means editor has no chance to change activeFilter's context.
// As a result, pasted data is filtered with default editor's filter instead of NE's and
// funny things get inserted. Changing the filter by analysis of the paste range below (http://dev.ckeditor.com/ticket/13186).
if ( data.range ) {
// Check if pasting into nested editable.
var nestedEditable = Widget.getNestedEditable( editor.editable(), data.range.startContainer );
if ( nestedEditable ) {
// Retrieve the filter from NE's data and set it active before editor.insertHtml is done
// in clipboard plugin.
var filter = CKEDITOR.filter.instances[ nestedEditable.data( 'cke-filter' ) ];
if ( filter ) {
editor.setActiveFilter( filter );
}
}
}
} );
// Listen with high priority to check widgets after data was inserted.
editor.on( 'afterInsertHtml', function( evt ) {
if ( evt.data.intoRange ) {
widgetsRepo.checkWidgets( { initOnlyNew: true } );
} else {
editor.fire( 'lockSnapshot' );
// Init only new for performance reason.
// Focus inited if only widget was processed.
widgetsRepo.checkWidgets( { initOnlyNew: true, focusInited: processedWidgetOnly } );
editor.fire( 'unlockSnapshot' );
}
} );
}
// Helper for coordinating which widgets should be
// selected/deselected and which one should be focused/blurred.
function stateUpdater( widgetsRepo ) {
var currentlySelected = widgetsRepo.selected,
toBeSelected = [],
toBeDeselected = currentlySelected.slice( 0 ),
focused = null;
return {
select: function( widget ) {
if ( CKEDITOR.tools.indexOf( currentlySelected, widget ) < 0 )
toBeSelected.push( widget );
var index = CKEDITOR.tools.indexOf( toBeDeselected, widget );
if ( index >= 0 )
toBeDeselected.splice( index, 1 );
return this;
},
focus: function( widget ) {
focused = widget;
return this;
},
commit: function() {
var focusedChanged = widgetsRepo.focused !== focused,
widget, isDirty;
widgetsRepo.editor.fire( 'lockSnapshot' );
if ( focusedChanged && ( widget = widgetsRepo.focused ) )
blurWidget( widgetsRepo, widget );
while ( ( widget = toBeDeselected.pop() ) ) {
currentlySelected.splice( CKEDITOR.tools.indexOf( currentlySelected, widget ), 1 );
// Widget could be destroyed in the meantime - e.g. data could be set.
if ( widget.isInited() ) {
isDirty = widget.editor.checkDirty();
widget.setSelected( false );
!isDirty && widget.editor.resetDirty();
}
}
if ( focusedChanged && focused ) {
isDirty = widgetsRepo.editor.checkDirty();
widgetsRepo.focused = focused;
widgetsRepo.fire( 'widgetFocused', { widget: focused } );
focused.setFocused( true );
!isDirty && widgetsRepo.editor.resetDirty();
}
while ( ( widget = toBeSelected.pop() ) ) {
currentlySelected.push( widget );
widget.setSelected( true );
}
widgetsRepo.editor.fire( 'unlockSnapshot' );
}
};
}
//
// WIDGET helpers ---------------------------------------------------------
//
// LEFT, RIGHT, UP, DOWN, DEL, BACKSPACE - unblock default fake sel handlers.
var keystrokesNotBlockedByWidget = { 37: 1, 38: 1, 39: 1, 40: 1, 8: 1, 46: 1 };
// Applies or removes style's classes from widget.
// @param {CKEDITOR.style} style Custom widget style.
// @param {Boolean} apply Whether to apply or remove style.
function applyRemoveStyle( widget, style, apply ) {
var changed = 0,
classes = getStyleClasses( style ),
updatedClasses = widget.data.classes || {},
cl;
// Ee... Something is wrong with this style.
if ( !classes )
return;
// Clone, because we need to break reference.
updatedClasses = CKEDITOR.tools.clone( updatedClasses );
while ( ( cl = classes.pop() ) ) {
if ( apply ) {
if ( !updatedClasses[ cl ] )
changed = updatedClasses[ cl ] = 1;
} else {
if ( updatedClasses[ cl ] ) {
delete updatedClasses[ cl ];
changed = 1;
}
}
}
if ( changed )
widget.setData( 'classes', updatedClasses );
}
function cancel( evt ) {
evt.cancel();
}
function copySingleWidget( widget, isCut ) {
var editor = widget.editor,
doc = editor.document;
// We're still handling previous copy/cut.
// When keystroke is used to copy/cut this will also prevent
// conflict with copySingleWidget called again for native copy/cut event.
if ( doc.getById( 'cke_copybin' ) )
return;
// [IE] Use span for copybin and its container to avoid bug with expanding editable height by
// absolutely positioned element.
var copybinName = ( editor.blockless || CKEDITOR.env.ie ) ? 'span' : 'div',
copybin = doc.createElement( copybinName ),
copybinContainer = doc.createElement( copybinName ),
// IE8 always jumps to the end of document.
needsScrollHack = CKEDITOR.env.ie && CKEDITOR.env.version < 9;
copybinContainer.setAttributes( {
id: 'cke_copybin',
'data-cke-temp': '1'
} );
// Position copybin element outside current viewport.
copybin.setStyles( {
position: 'absolute',
width: '1px',
height: '1px',
overflow: 'hidden'
} );
copybin.setStyle( editor.config.contentsLangDirection == 'ltr' ? 'left' : 'right', '-5000px' );
var range = editor.createRange();
range.setStartBefore( widget.wrapper );
range.setEndAfter( widget.wrapper );
copybin.setHtml(
'<span data-cke-copybin-start="1">\u200b</span>' +
editor.editable().getHtmlFromRange( range ).getHtml() +
'<span data-cke-copybin-end="1">\u200b</span>' );
// Save snapshot with the current state.
editor.fire( 'saveSnapshot' );
// Ignore copybin.
editor.fire( 'lockSnapshot' );
copybinContainer.append( copybin );
editor.editable().append( copybinContainer );
var listener1 = editor.on( 'selectionChange', cancel, null, null, 0 ),
listener2 = widget.repository.on( 'checkSelection', cancel, null, null, 0 );
if ( needsScrollHack ) {
var docElement = doc.getDocumentElement().$,
scrollTop = docElement.scrollTop;
}
// Once the clone of the widget is inside of copybin, select
// the entire contents. This selection will be copied by the
// native browser's clipboard system.
range = editor.createRange();
range.selectNodeContents( copybin );
range.select();
if ( needsScrollHack )
docElement.scrollTop = scrollTop;
setTimeout( function() {
// [IE] Focus widget before removing copybin to avoid scroll jump.
if ( !isCut )
widget.focus();
copybinContainer.remove();
listener1.removeListener();
listener2.removeListener();
editor.fire( 'unlockSnapshot' );
if ( isCut ) {
widget.repository.del( widget );
editor.fire( 'saveSnapshot' );
}
}, 100 ); // Use 100ms, so Chrome (@Mac) will be able to grab the content.
}
// Extracts classes array from style instance.
function getStyleClasses( style ) {
var attrs = style.getDefinition().attributes,
classes = attrs && attrs[ 'class' ];
return classes ? classes.split( /\s+/ ) : null;
}
// [IE] Force keeping focus because IE sometimes forgets to fire focus on main editable
// when blurring nested editable.
// @context widget
function onEditableBlur() {
var active = CKEDITOR.document.getActive(),
editor = this.editor,
editable = editor.editable();
// If focus stays within editor override blur and set currentActive because it should be
// automatically changed to editable on editable#focus but it is not fired.
if ( ( editable.isInline() ? editable : editor.document.getWindow().getFrame() ).equals( active ) )
editor.focusManager.focus( editable );
}
// Force selectionChange when editable was focused.
// Similar to hack in selection.js#~620.
// @context widget
function onEditableFocus() {
// Gecko does not support 'DOMFocusIn' event on which we unlock selection
// in selection.js to prevent selection locking when entering nested editables.
if ( CKEDITOR.env.gecko )
this.editor.unlockSelection();
// We don't need to force selectionCheck on Webkit, because on Webkit
// we do that on DOMFocusIn in selection.js.
if ( !CKEDITOR.env.webkit ) {
this.editor.forceNextSelectionCheck();
this.editor.selectionChange( 1 );
}
}
// Setup listener on widget#data which will update (remove/add) classes
// by comparing newly set classes with the old ones.
function setupDataClassesListener( widget ) {
// Note: previousClasses and newClasses may be null!
// Tip: for ( cl in null ) is correct.
var previousClasses = null;
widget.on( 'data', function() {
var newClasses = this.data.classes,
cl;
// When setting new classes one need to remember
// that he must break reference.
if ( previousClasses == newClasses )
return;
for ( cl in previousClasses ) {
// Avoid removing and adding classes again.
if ( !( newClasses && newClasses[ cl ] ) )
this.removeClass( cl );
}
for ( cl in newClasses )
this.addClass( cl );
previousClasses = newClasses;
} );
}
// Add a listener to data event that will set/change widget's label (http://dev.ckeditor.com/ticket/14539).
function setupA11yListener( widget ) {
// Note, the function gets executed in a context of widget instance.
function getLabelDefault() {
return this.editor.lang.widget.label.replace( /%1/, this.pathName || this.element.getName() );
}
// Setting a listener on data is enough, there's no need to perform it on widget initialization, as
// setupWidgetData fires this event anyway.
widget.on( 'data', function() {
// In some cases widget might get destroyed in an earlier data listener. For instance, image2 plugin, does
// so when changing its internal state.
if ( !widget.wrapper ) {
return;
}
var label = this.getLabel ? this.getLabel() : getLabelDefault.call( this );
widget.wrapper.setAttribute( 'role', 'region' );
widget.wrapper.setAttribute( 'aria-label', label );
}, null, null, 9999 );
}
function setupDragHandler( widget ) {
if ( !widget.draggable )
return;
var editor = widget.editor,
// Use getLast to find wrapper's direct descendant (http://dev.ckeditor.com/ticket/12022).
container = widget.wrapper.getLast( Widget.isDomDragHandlerContainer ),
img;
// Reuse drag handler if already exists (http://dev.ckeditor.com/ticket/11281).
if ( container )
img = container.findOne( 'img' );
else {
container = new CKEDITOR.dom.element( 'span', editor.document );
container.setAttributes( {
'class': 'cke_reset cke_widget_drag_handler_container',
// Split background and background-image for IE8 which will break on rgba().
style: 'background:rgba(220,220,220,0.5);background-image:url(' + editor.plugins.widget.path + 'images/handle.png)'
} );
img = new CKEDITOR.dom.element( 'img', editor.document );
img.setAttributes( {
'class': 'cke_reset cke_widget_drag_handler',
'data-cke-widget-drag-handler': '1',
src: CKEDITOR.tools.transparentImageData,
width: DRAG_HANDLER_SIZE,
title: editor.lang.widget.move,
height: DRAG_HANDLER_SIZE,
role: 'presentation'
} );
widget.inline && img.setAttribute( 'draggable', 'true' );
container.append( img );
widget.wrapper.append( container );
}
// Preventing page reload when dropped content on widget wrapper (http://dev.ckeditor.com/ticket/13015).
// Widget is not editable so by default drop on it isn't allowed what means that
// browser handles it (there's no editable#drop event). If there's no drop event we cannot block
// the drop, so page is reloaded. This listener enables drop on widget wrappers.
widget.wrapper.on( 'dragover', function( evt ) {
evt.data.preventDefault();
} );
widget.wrapper.on( 'mouseenter', widget.updateDragHandlerPosition, widget );
setTimeout( function() {
widget.on( 'data', widget.updateDragHandlerPosition, widget );
}, 50 );
if ( !widget.inline ) {
img.on( 'mousedown', onBlockWidgetDrag, widget );
// On IE8 'dragstart' is propagated to editable, so editor#dragstart is fired twice on block widgets.
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 ) {
img.on( 'dragstart', function( evt ) {
evt.data.preventDefault( true );
} );
}
}
widget.dragHandlerContainer = container;
}
function onBlockWidgetDrag( evt ) {
var finder = this.repository.finder,
locator = this.repository.locator,
liner = this.repository.liner,
editor = this.editor,
editable = editor.editable(),
listeners = [],
sorted = [],
locations,
y;
// Mark dragged widget for repository#finder.
this.repository._.draggedWidget = this;
// Harvest all possible relations and display some closest.
var relations = finder.greedySearch(),
buffer = CKEDITOR.tools.eventsBuffer( 50, function() {
locations = locator.locate( relations );
// There's only a single line displayed for D&D.
sorted = locator.sort( y, 1 );
if ( sorted.length ) {
liner.prepare( relations, locations );
liner.placeLine( sorted[ 0 ] );
liner.cleanup();
}
} );
// Let's have the "dragging cursor" over entire editable.
editable.addClass( 'cke_widget_dragging' );
// Cache mouse position so it is re-used in events buffer.
listeners.push( editable.on( 'mousemove', function( evt ) {
y = evt.data.$.clientY;
buffer.input();
} ) );
// Fire drag start as it happens during the native D&D.
editor.fire( 'dragstart', { target: evt.sender } );
function onMouseUp() {
var l;
buffer.reset();
// Stop observing events.
while ( ( l = listeners.pop() ) )
l.removeListener();
onBlockWidgetDrop.call( this, sorted, evt.sender );
}
// Mouseup means "drop". This is when the widget is being detached
// from DOM and placed at range determined by the line (location).
listeners.push( editor.document.once( 'mouseup', onMouseUp, this ) );
// Prevent calling 'onBlockWidgetDrop' twice in the inline editor.
// `removeListener` does not work if it is called at the same time event is fired.
if ( !editable.isInline() ) {
// Mouseup may occur when user hovers the line, which belongs to
// the outer document. This is, of course, a valid listener too.
listeners.push( CKEDITOR.document.once( 'mouseup', onMouseUp, this ) );
}
}
function onBlockWidgetDrop( sorted, dragTarget ) {
var finder = this.repository.finder,
liner = this.repository.liner,
editor = this.editor,
editable = this.editor.editable();
if ( !CKEDITOR.tools.isEmpty( liner.visible ) ) {
// Retrieve range for the closest location.
var dropRange = finder.getRange( sorted[ 0 ] );
// Focus widget (it could lost focus after mousedown+mouseup)
// and save this state as the one where we want to be taken back when undoing.
this.focus();
// Drag range will be set in the drop listener.
editor.fire( 'drop', {
dropRange: dropRange,
target: dropRange.startContainer
} );
}
// Clean-up custom cursor for editable.
editable.removeClass( 'cke_widget_dragging' );
// Clean-up all remaining lines.
liner.hideVisible();
// Clean-up drag & drop.
editor.fire( 'dragend', { target: dragTarget } );
}
function setupEditables( widget ) {
var editableName,
editableDef,
definedEditables = widget.editables;
widget.editables = {};
if ( !widget.editables )
return;
for ( editableName in definedEditables ) {
editableDef = definedEditables[ editableName ];
widget.initEditable( editableName, typeof editableDef == 'string' ? { selector: editableDef } : editableDef );
}
}
function setupMask( widget ) {
if ( !widget.mask )
return;
// Reuse mask if already exists (http://dev.ckeditor.com/ticket/11281).
var img = widget.wrapper.findOne( '.cke_widget_mask' );
if ( !img ) {
img = new CKEDITOR.dom.element( 'img', widget.editor.document );
img.setAttributes( {
src: CKEDITOR.tools.transparentImageData,
'class': 'cke_reset cke_widget_mask'
} );
widget.wrapper.append( img );
}
widget.mask = img;
}
// Replace parts object containing:
// partName => selector pairs
// with:
// partName => element pairs
function setupParts( widget ) {
if ( widget.parts ) {
var parts = {},
el, partName;
for ( partName in widget.parts ) {
el = widget.wrapper.findOne( widget.parts[ partName ] );
parts[ partName ] = el;
}
widget.parts = parts;
}
}
function setupWidget( widget, widgetDef ) {
setupWrapper( widget );
setupParts( widget );
setupEditables( widget );
setupMask( widget );
setupDragHandler( widget );
setupDataClassesListener( widget );
setupA11yListener( widget );
// http://dev.ckeditor.com/ticket/11145: [IE8] Non-editable content of widget is draggable.
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 ) {
widget.wrapper.on( 'dragstart', function( evt ) {
var target = evt.data.getTarget();
// Allow text dragging inside nested editables or dragging inline widget's drag handler.
if ( !Widget.getNestedEditable( widget, target ) && !( widget.inline && Widget.isDomDragHandler( target ) ) )
evt.data.preventDefault();
} );
}
widget.wrapper.removeClass( 'cke_widget_new' );
widget.element.addClass( 'cke_widget_element' );
widget.on( 'key', function( evt ) {
var keyCode = evt.data.keyCode;
// ENTER.
if ( keyCode == 13 ) {
widget.edit();
// CTRL+C or CTRL+X.
} else if ( keyCode == CKEDITOR.CTRL + 67 || keyCode == CKEDITOR.CTRL + 88 ) {
copySingleWidget( widget, keyCode == CKEDITOR.CTRL + 88 );
return; // Do not preventDefault.
} else if ( keyCode in keystrokesNotBlockedByWidget || ( CKEDITOR.CTRL & keyCode ) || ( CKEDITOR.ALT & keyCode ) ) {
// Pass chosen keystrokes to other plugins or default fake sel handlers.
// Pass all CTRL/ALT keystrokes.
return;
}
return false;
}, null, null, 999 );
// Listen with high priority so it's possible
// to overwrite this callback.
widget.on( 'doubleclick', function( evt ) {
if ( widget.edit() ) {
// We have to cancel event if edit method opens a dialog, otherwise
// link plugin may open extra dialog (http://dev.ckeditor.com/ticket/12140).
evt.cancel();
}
} );
if ( widgetDef.data )
widget.on( 'data', widgetDef.data );
if ( widgetDef.edit )
widget.on( 'edit', widgetDef.edit );
}
function setupWidgetData( widget, startupData ) {
var widgetDataAttr = widget.element.data( 'cke-widget-data' );
if ( widgetDataAttr )
widget.setData( JSON.parse( decodeURIComponent( widgetDataAttr ) ) );
if ( startupData )
widget.setData( startupData );
// Populate classes if they are not preset.
if ( !widget.data.classes )
widget.setData( 'classes', widget.getClasses() );
// Unblock data and...
widget.dataReady = true;
// Write data to element because this was blocked when data wasn't ready.
writeDataToElement( widget );
// Fire data event first time, because this was blocked when data wasn't ready.
widget.fire( 'data', widget.data );
}
function setupWrapper( widget ) {
// Retrieve widget wrapper. Assign an id to it.
var wrapper = widget.wrapper = widget.element.getParent();
wrapper.setAttribute( 'data-cke-widget-id', widget.id );
}
function writeDataToElement( widget ) {
widget.element.data( 'cke-widget-data', encodeURIComponent( JSON.stringify( widget.data ) ) );
}
//
// WIDGET STYLE HANDLER ---------------------------------------------------
//
( function() {
// Styles categorized by group. It is used to prevent applying styles for the same group being used together.
var styleGroups = {};
/**
* The class representing a widget style. It is an {@link CKEDITOR#STYLE_OBJECT object} like
* the styles handler for widgets.
*
* **Note:** This custom style handler does not support all methods of the {@link CKEDITOR.style} class.
* Not supported methods: {@link #applyToRange}, {@link #removeFromRange}, {@link #applyToObject}.
*
* @since 4.4
* @class CKEDITOR.style.customHandlers.widget
* @extends CKEDITOR.style
*/
CKEDITOR.style.addCustomHandler( {
type: 'widget',
setup: function( styleDefinition ) {
/**
* The name of widget to which this style can be applied.
* It is extracted from style definition's `widget` property.
*
* @property {String} widget
*/
this.widget = styleDefinition.widget;
/**
* An array of groups that this style belongs to.
* Styles assigned to the same group cannot be combined.
*
* @since 4.6.2
* @property {Array} group
*/
this.group = typeof styleDefinition.group == 'string' ? [ styleDefinition.group ] : styleDefinition.group;
// Store style categorized by its group.
// It is used to prevent enabling two styles from same group.
if ( this.group ) {
saveStyleGroup( this );
}
},
apply: function( editor ) {
var widget;
// Before CKEditor 4.4 wasn't a required argument, so we need to
// handle a case when it wasn't provided.
if ( !( editor instanceof CKEDITOR.editor ) )
return;
// Theoretically we could bypass checkApplicable, get widget from
// widgets.focused and check its name, what would be faster, but then
// this custom style would work differently than the default style
// which checks if it's applicable before applying or removing itself.
if ( this.checkApplicable( editor.elementPath(), editor ) ) {
widget = editor.widgets.focused;
// Remove other styles from the same group.
if ( this.group ) {
this.removeStylesFromSameGroup( editor );
}
widget.applyStyle( this );
}
},
remove: function( editor ) {
// Before CKEditor 4.4 wasn't a required argument, so we need to
// handle a case when it wasn't provided.
if ( !( editor instanceof CKEDITOR.editor ) )
return;
if ( this.checkApplicable( editor.elementPath(), editor ) )
editor.widgets.focused.removeStyle( this );
},
/**
* Removes all styles that belong to the same group as this style. This method will neither add nor remove
* the current style.
* Returns `true` if any style was removed, otherwise returns `false`.
*
* @since 4.6.2
* @param {CKEDITOR.editor} editor
* @returns {Boolean}
*/
removeStylesFromSameGroup: function( editor ) {
var stylesFromSameGroup,
path,
removed = false;
// Before CKEditor 4.4 wasn't a required argument, so we need to
// handle a case when it wasn't provided.
if ( !( editor instanceof CKEDITOR.editor ) )
return false;
path = editor.elementPath();
if ( this.checkApplicable( path, editor ) ) {
// Iterate over each group.
for ( var i = 0, l = this.group.length; i < l; i++ ) {
stylesFromSameGroup = styleGroups[ this.widget ][ this.group[ i ] ];
// Iterate over each style from group.
for ( var j = 0; j < stylesFromSameGroup.length; j++ ) {
if ( stylesFromSameGroup[ j ] !== this && stylesFromSameGroup[ j ].checkActive( path, editor ) ) {
editor.widgets.focused.removeStyle( stylesFromSameGroup[ j ] );
removed = true;
}
}
}
}
return removed;
},
checkActive: function( elementPath, editor ) {
return this.checkElementMatch( elementPath.lastElement, 0, editor );
},
checkApplicable: function( elementPath, editor ) {
// Before CKEditor 4.4 wasn't a required argument, so we need to
// handle a case when it wasn't provided.
if ( !( editor instanceof CKEDITOR.editor ) )
return false;
return this.checkElement( elementPath.lastElement );
},
checkElementMatch: checkElementMatch,
checkElementRemovable: checkElementMatch,
/**
* Checks if an element is a {@link CKEDITOR.plugins.widget#wrapper wrapper} of a
* widget whose name matches the {@link #widget widget name} specified in the style definition.
*
* @param {CKEDITOR.dom.element} element
* @returns {Boolean}
*/
checkElement: function( element ) {
if ( !Widget.isDomWidgetWrapper( element ) )
return false;
var widgetElement = element.getFirst( Widget.isDomWidgetElement );
return widgetElement && widgetElement.data( 'widget' ) == this.widget;
},
buildPreview: function( label ) {
return label || this._.definition.name;
},
/**
* Returns allowed content rules which should be registered for this style.
* Uses widget's {@link CKEDITOR.plugins.widget.definition#styleableElements} to make a rule
* allowing classes on specified elements or use widget's
* {@link CKEDITOR.plugins.widget.definition#styleToAllowedContentRules} method to transform a style
* into allowed content rules.
*
* @param {CKEDITOR.editor} The editor instance.
* @returns {CKEDITOR.filter.allowedContentRules}
*/
toAllowedContentRules: function( editor ) {
if ( !editor )
return null;
var widgetDef = editor.widgets.registered[ this.widget ],
classes,
rule = {};
if ( !widgetDef )
return null;
if ( widgetDef.styleableElements ) {
classes = this.getClassesArray();
if ( !classes )
return null;
rule[ widgetDef.styleableElements ] = {
classes: classes,
propertiesOnly: true
};
return rule;
}
if ( widgetDef.styleToAllowedContentRules )
return widgetDef.styleToAllowedContentRules( this );
return null;
},
/**
* Returns classes defined in the style in form of an array.
*
* @returns {String[]}
*/
getClassesArray: function() {
var classes = this._.definition.attributes && this._.definition.attributes[ 'class' ];
return classes ? CKEDITOR.tools.trim( classes ).split( /\s+/ ) : null;
},
/**
* Not implemented.
*
* @method applyToRange
*/
applyToRange: notImplemented,
/**
* Not implemented.
*
* @method removeFromRange
*/
removeFromRange: notImplemented,
/**
* Not implemented.
*
* @method applyToObject
*/
applyToObject: notImplemented
} );
function notImplemented() {}
// @context style
function checkElementMatch( element, fullMatch, editor ) {
// Before CKEditor 4.4 wasn't a required argument, so we need to
// handle a case when it wasn't provided.
if ( !editor )
return false;
if ( !this.checkElement( element ) )
return false;
var widget = editor.widgets.getByElement( element, true );
return widget && widget.checkStyleActive( this );
}
// Save and categorize style by its group.
function saveStyleGroup( style ) {
var widgetName = style.widget,
group;
if ( !styleGroups[ widgetName ] ) {
styleGroups[ widgetName ] = {};
}
for ( var i = 0, l = style.group.length; i < l; i++ ) {
group = style.group[ i ];
if ( !styleGroups[ widgetName ][ group ] ) {
styleGroups[ widgetName ][ group ] = [];
}
styleGroups[ widgetName ][ group ].push( style );
}
}
} )();
//
// EXPOSE PUBLIC API ------------------------------------------------------
//
CKEDITOR.plugins.widget = Widget;
Widget.repository = Repository;
Widget.nestedEditable = NestedEditable;
} )();
/**
* An event fired when a widget definition is registered by the {@link CKEDITOR.plugins.widget.repository#add} method.
* It is possible to modify the definition being registered.
*
* @event widgetDefinition
* @member CKEDITOR.editor
* @param {CKEDITOR.plugins.widget.definition} data Widget definition.
*/
/**
* This is an abstract class that describes the definition of a widget.
* It is a type of {@link CKEDITOR.plugins.widget.repository#add} method's second argument.
*
* Widget instances inherit from registered widget definitions, although not in a prototypal way.
* They are simply extended with corresponding widget definitions. Note that not all properties of
* the widget definition become properties of a widget. Some, like {@link #data} or {@link #edit}, become
* widget's events listeners.
*
* @class CKEDITOR.plugins.widget.definition
* @abstract
* @mixins CKEDITOR.feature
*/
/**
* Widget definition name. It is automatically set when the definition is
* {@link CKEDITOR.plugins.widget.repository#add registered}.
*
* @property {String} name
*/
/**
* The method executed while initializing a widget, after a widget instance
* is created, but before it is ready. It is executed before the first
* {@link CKEDITOR.plugins.widget#event-data} is fired so it is common to
* use the `init` method to populate widget data with information loaded from
* the DOM, like for exmaple:
*
* init: function() {
* this.setData( 'width', this.element.getStyle( 'width' ) );
*
* if ( this.parts.caption.getStyle( 'display' ) != 'none' )
* this.setData( 'showCaption', true );
* }
*
* @property {Function} init
*/
/**
* The function to be used to upcast an element to this widget or a
* comma-separated list of upcast methods from the {@link #upcasts} object.
*
* The upcast function **is not** executed in the widget context (because the widget
* does not exist yet) and two arguments are passed:
*
* * `element` ({@link CKEDITOR.htmlParser.element}) – The element to be checked.
* * `data` (`Object`) – The object which can be extended with data which will then be passed to the widget.
*
* An element will be upcasted if a function returned `true` or an instance of
* a {@link CKEDITOR.htmlParser.element} if upcasting meant DOM structure changes
* (in this case the widget will be initialized on the returned element).
*
* @property {String/Function} upcast
*/
/**
* The object containing functions which can be used to upcast this widget.
* Only those pointed by the {@link #upcast} property will be used.
*
* In most cases it is appropriate to use {@link #upcast} directly,
* because majority of widgets need just one method.
* However, in some cases the widget author may want to expose more than one variant
* and then this property may be used.
*
* upcasts: {
* // This function may upcast only figure elements.
* figure: function() {
* // ...
* },
* // This function may upcast only image elements.
* image: function() {
* // ...
* },
* // More variants...
* }
*
* // Then, widget user may choose which upcast methods will be enabled.
* editor.on( 'widgetDefinition', function( evt ) {
* if ( evt.data.name == 'image' )
* evt.data.upcast = 'figure,image'; // Use both methods.
* } );
*
* @property {Object} upcasts
*/
/**
* The {@link #upcast} method(s) priority. The upcast with a lower priority number will be called before
* the one with a higher number. The default priority is `10`.
*
* @since 4.5
* @property {Number} [upcastPriority=10]
*/
/**
* The function to be used to downcast this widget or
* a name of the downcast option from the {@link #downcasts} object.
*
* The downcast funciton will be executed in the {@link CKEDITOR.plugins.widget} context
* and with `widgetElement` ({@link CKEDITOR.htmlParser.element}) argument which is
* the widget's main element.
*
* The function may return an instance of the {@link CKEDITOR.htmlParser.node} class if the widget
* needs to be downcasted to a different node than the widget's main element.
*
* @property {String/Function} downcast
*/
/**
* The object containing functions which can be used to downcast this widget.
* Only the one pointed by the {@link #downcast} property will be used.
*
* In most cases it is appropriate to use {@link #downcast} directly,
* because majority of widgets have just one variant of downcasting (or none at all).
* However, in some cases the widget author may want to expose more than one variant
* and then this property may be used.
*
* downcasts: {
* // This downcast may transform the widget into the figure element.
* figure: function() {
* // ...
* },
* // This downcast may transform the widget into the image element with data-* attributes.
* image: function() {
* // ...
* }
* }
*
* // Then, the widget user may choose one of the downcast options when setting up his editor.
* editor.on( 'widgetDefinition', function( evt ) {
* if ( evt.data.name == 'image' )
* evt.data.downcast = 'figure';
* } );
*
* @property downcasts
*/
/**
* If set, it will be added as the {@link CKEDITOR.plugins.widget#event-edit} event listener.
* This means that it will be executed when a widget is being edited.
* See the {@link CKEDITOR.plugins.widget#method-edit} method.
*
* @property {Function} edit
*/
/**
* If set, it will be added as the {@link CKEDITOR.plugins.widget#event-data} event listener.
* This means that it will be executed every time the {@link CKEDITOR.plugins.widget#property-data widget data} changes.
*
* @property {Function} data
*/
/**
* The method to be executed when the widget's command is executed in order to insert a new widget
* (widget of this type is not focused). If not defined, then the default action will be
* performed which means that:
*
* * An instance of the widget will be created in a detached {@link CKEDITOR.dom.documentFragment document fragment},
* * The {@link CKEDITOR.plugins.widget#method-edit} method will be called to trigger widget editing,
* * The widget element will be inserted into DOM.
*
* @property {Function} insert
*/
/**
* The name of a dialog window which will be opened on {@link CKEDITOR.plugins.widget#method-edit}.
* If not defined, then the {@link CKEDITOR.plugins.widget#method-edit} method will not perform any action and
* widget's command will insert a new widget without opening a dialog window first.
*
* @property {String} dialog
*/
/**
* The template which will be used to create a new widget element (when the widget's command is executed).
* This string is populated with {@link #defaults default values} by using the {@link CKEDITOR.template} format.
* Therefore it has to be a valid {@link CKEDITOR.template} argument.
*
* @property {String} template
*/
/**
* The data object which will be used to populate the data of a newly created widget.
* See {@link CKEDITOR.plugins.widget#property-data}.
*
* defaults: {
* showCaption: true,
* align: 'none'
* }
*
* @property defaults
*/
/**
* An object containing definitions of widget components (part name => CSS selector).
*
* parts: {
* image: 'img',
* caption: 'div.caption'
* }
*
* @property parts
*/
/**
* An object containing definitions of nested editables (editable name => {@link CKEDITOR.plugins.widget.nestedEditable.definition}).
* Note that editables *have to* be defined in the same order as they are in DOM / {@link CKEDITOR.plugins.widget.definition#template template}.
* Otherwise errors will occur when nesting widgets inside each other.
*
* editables: {
* header: 'h1',
* content: {
* selector: 'div.content',
* allowedContent: 'p strong em; a[!href]'
* }
* }
*
* @property editables
*/
/**
* The function used to obtain an accessibility label for the widget. It might be used to make
* the widget labels as precise as possible, since it has access to the widget instance.
*
* If not specified, the default implementation will use the {@link #pathName} or the main
* {@link CKEDITOR.plugins.widget#element element} tag name.
*
* @property {Function} getLabel
*/
/**
* The widget name displayed in the elements path.
*
* @property {String} pathName
*/
/**
* If set to `true`, the widget's element will be covered with a transparent mask.
* This will prevent its content from being clickable, which matters in case
* of special elements like embedded Flash or iframes that generate a separate "context".
*
* @property {Boolean} mask
*/
/**
* If set to `true/false`, it will force the widget to be either an inline or a block widget.
* If not set, the widget type will be determined from the widget element.
*
* Widget type influences whether a block (`div`) or an inline (`span`) element is used
* for the wrapper.
*
* @property {Boolean} inline
*/
/**
* The label for the widget toolbar button.
*
* editor.widgets.add( 'simplebox', {
* button: 'Create a simple box'
* } );
*
* editor.widgets.add( 'simplebox', {
* button: editor.lang.simplebox.title
* } );
*
* @property {String} button
*/
/**
* Whether widget should be draggable. Defaults to `true`.
* If set to `false` drag handler will not be displayed when hovering widget.
*
* @property {Boolean} draggable
*/
/**
* Names of element(s) (separated by spaces) for which the {@link CKEDITOR.filter} should allow classes
* defined in the widget styles. For example if your widget is upcasted from a simple `<div>`
* element, then in order to make it styleable you can set:
*
* editor.widgets.add( 'customWidget', {
* upcast: function( element ) {
* return element.name == 'div';
* },
*
* // ...
*
* styleableElements: 'div'
* } );
*
* Then, when the following style is defined:
*
* {
* name: 'Thick border', type: 'widget', widget: 'customWidget',
* attributes: { 'class': 'thickBorder' }
* }
*
* a rule allowing the `thickBorder` class for `div` elements will be registered in the {@link CKEDITOR.filter}.
*
* If you need to have more freedom when transforming widget style to allowed content rules,
* you can use the {@link #styleToAllowedContentRules} callback.
*
* @since 4.4
* @property {String} styleableElements
*/
/**
* Function transforming custom widget's {@link CKEDITOR.style} instance into
* {@link CKEDITOR.filter.allowedContentRules}. It may be used when a static
* {@link #styleableElements} property is not enough to inform the {@link CKEDITOR.filter}
* what HTML features should be enabled when allowing the given style.
*
* In most cases, when style's classes just have to be added to element name(s) used by
* the widget element, it is recommended to use simpler {@link #styleableElements} property.
*
* In order to get parsed classes from the style definition you can use
* {@link CKEDITOR.style.customHandlers.widget#getClassesArray}.
*
* For example, if you want to use the [object format of allowed content rules](#!/guide/dev_allowed_content_rules-section-object-format),
* to specify `match` validator, your implementation could look like this:
*
* editor.widgets.add( 'customWidget', {
* // ...
*
* styleToAllowedContentRules: funciton( style ) {
* // Retrieve classes defined in the style.
* var classes = style.getClassesArray();
*
* // Do something crazy - for example return allowed content rules in object format,
* // with custom match property and propertiesOnly flag.
* return {
* h1: {
* match: isWidgetElement,
* propertiesOnly: true,
* classes: classes
* }
* };
* }
* } );
*
* @since 4.4
* @property {Function} styleToAllowedContentRules
* @param {CKEDITOR.style.customHandlers.widget} style The style to be transformed.
* @returns {CKEDITOR.filter.allowedContentRules}
*/
/**
* This is an abstract class that describes the definition of a widget's nested editable.
* It is a type of values in the {@link CKEDITOR.plugins.widget.definition#editables} object.
*
* In the simplest case the definition is a string which is a CSS selector used to
* find an element that will become a nested editable inside the widget. Note that
* the widget element can be a nested editable, too.
*
* In the more advanced case a definition is an object with a required `selector` property.
*
* editables: {
* header: 'h1',
* content: {
* selector: 'div.content',
* allowedContent: 'p strong em; a[!href]'
* }
* }
*
* @class CKEDITOR.plugins.widget.nestedEditable.definition
* @abstract
*/
/**
* The CSS selector used to find an element which will become a nested editable.
*
* @property {String} selector
*/
/**
* The [Advanced Content Filter](#!/guide/dev_advanced_content_filter) rules
* which will be used to limit the content allowed in this nested editable.
* This option is similar to {@link CKEDITOR.config#allowedContent} and one can
* use it to limit the editor features available in the nested editable.
*
* @property {CKEDITOR.filter.allowedContentRules} allowedContent
*/
/**
* Nested editable name displayed in elements path.
*
* @property {String} pathName
*/
| bachnxhedspi/web_tieng_anh_1 | xcrud/editors/ckeditor/plugins/widget/plugin.js | JavaScript | mit | 136,992 |
# Author: Julien Goret <[email protected]>
# URL: https://github.com/Kyah/Sick-Beard
#
# This file is part of Sick Beard.
#
# Sick Beard 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.
#
# Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>.
from xml.dom.minidom import parseString
from sickbeard import classes, show_name_helpers, logger
from sickbeard.common import Quality
from sickbeard import helpers
from sickbeard import logger
from sickbeard import tvcache
import generic
import cookielib
import sickbeard
import urllib
import urllib2
class GksProvider(generic.TorrentProvider):
def __init__(self):
generic.TorrentProvider.__init__(self, "gks")
self.supportsBacklog = True
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
self.url = "https://gks.gs/"
def isEnabled(self):
return sickbeard.GKS
def imageName(self):
return 'gks.png'
def getSearchParams(self, searchString, audio_lang, season=None):
results = []
if season:
results.append( urllib.urlencode( {'q': searchString, 'category' : 10, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
else:
if audio_lang == "en":
results.append( urllib.urlencode( {'q': searchString, 'category' : 22, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
results.append( urllib.urlencode( {'q': searchString, 'category' : 21, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
if sickbeard.USE_SUBTITLES :
results.append( urllib.urlencode( {'q': searchString, 'category' : 11, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
results.append( urllib.urlencode( {'q': searchString, 'category' : 13, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
elif audio_lang == "fr":
results.append( urllib.urlencode( {'q': searchString, 'category' : 12, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
results.append( urllib.urlencode( {'q': searchString, 'category' : 14, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
results.append( urllib.urlencode( {'q': searchString, 'category' : 21, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
else:
results.append( urllib.urlencode( {'q': searchString, 'ak' : sickbeard.GKS_KEY} ) + "&order=desc&sort=normal&exact" )
return results
def _get_season_search_strings(self, show, season):
showNam = show_name_helpers.allPossibleShowNames(show)
showNames = list(set(showNam))
results = []
for showName in showNames:
for result in self.getSearchParams(showName + "+S%02d" % season, show.audio_lang, season) :
results.append(result)
for result in self.getSearchParams(showName + "+saison+%02d" % season, show.audio_lang, season):
results.append(result)
return results
def _get_episode_search_strings(self, ep_obj, french=None):
showNam = show_name_helpers.allPossibleShowNames(ep_obj.show)
showNames = list(set(showNam))
results = []
for showName in showNames:
if french:
lang='fr'
else:
lang=ep_obj.show.audio_lang
for result in self.getSearchParams( "%s S%02dE%02d" % ( showName, ep_obj.scene_season, ep_obj.scene_episode), lang) :
results.append(result)
return results
def _doSearch(self, searchString, show=None, season=None, french=None):
results = []
searchUrl = self.url+'rdirect.php?type=search&'+searchString.replace('!','')
logger.log(u"Search URL: " + searchUrl, logger.DEBUG)
data = self.getURL(searchUrl)
if "bad key" in str(data).lower() :
logger.log(u"GKS key invalid, check your config", logger.ERROR)
return []
parsedXML = parseString(data)
channel = parsedXML.getElementsByTagName('channel')[0]
description = channel.getElementsByTagName('description')[0]
description_text = helpers.get_xml_text(description).lower()
if "user can't be found" in description_text:
logger.log(u"GKS invalid digest, check your config", logger.ERROR)
return []
elif "invalid hash" in description_text:
logger.log(u"GKS invalid hash, check your config", logger.ERROR)
return []
else :
items = channel.getElementsByTagName('item')
for item in items:
title = helpers.get_xml_text(item.getElementsByTagName('title')[0])
if "aucun resultat" in title.lower() :
logger.log(u"No results found in " + searchUrl, logger.DEBUG)
return []
count=1
if season:
count=0
if show:
if show.audio_lang=='fr' or french:
for frword in['french', 'truefrench', 'multi']:
if frword in title.lower():
count+=1
else:
count +=1
else:
count +=1
if count==0:
continue
else :
downloadURL = helpers.get_xml_text(item.getElementsByTagName('link')[0])
quality = Quality.nameQuality(title)
if quality==Quality.UNKNOWN and title:
if '720p' not in title.lower() and '1080p' not in title.lower():
quality=Quality.SDTV
if show and french==None:
results.append( GksSearchResult( self.opener, title, downloadURL, quality, str(show.audio_lang) ) )
elif show and french:
results.append( GksSearchResult( self.opener, title, downloadURL, quality, 'fr' ) )
else:
results.append( GksSearchResult( self.opener, title, downloadURL, quality ) )
return results
def getResult(self, episodes):
"""
Returns a result of the correct type for this provider
"""
result = classes.TorrentDataSearchResult(episodes)
result.provider = self
return result
def _get_title_and_url(self, item):
return (item.title, item.url)
class GksSearchResult:
def __init__(self, opener, title, url, quality, audio_langs=None):
self.opener = opener
self.title = title
self.url = url
self.quality = quality
self.audio_langs=audio_langs
def getNZB(self):
return self.opener.open( self.url , 'wb').read()
def getQuality(self):
return self.quality
provider = GksProvider()
| Branlala/docker-sickbeardfr | sickbeard/sickbeard/providers/gks.py | Python | mit | 7,682 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
if (n === 1) return 1;
return 5;
}
export default [
'ha-NE', [['AM', 'PM'], u, u], u,
[
['L', 'L', 'T', 'L', 'A', 'J', 'A'], ['Lah', 'Lit', 'Tal', 'Lar', 'Alh', 'Jum', 'Asa'],
['Lahadi', 'Litinin', 'Talata', 'Laraba', 'Alhamis', 'Jummaʼa', 'Asabar'],
['Lh', 'Li', 'Ta', 'Lr', 'Al', 'Ju', 'As']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'Y', 'Y', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Fab', 'Mar', 'Afi', 'May', 'Yun', 'Yul', 'Agu', 'Sat', 'Okt', 'Nuw', 'Dis'],
[
'Janairu', 'Faburairu', 'Maris', 'Afirilu', 'Mayu', 'Yuni', 'Yuli', 'Agusta', 'Satumba',
'Oktoba', 'Nuwamba', 'Disamba'
]
],
u, [['KHAI', 'BHAI'], u, ['Kafin haihuwar annab', 'Bayan haihuwar annab']], 1, [6, 0],
['d/M/yy', 'd MMM, y', 'd MMMM, y', 'EEEE, d MMMM, y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'CFA', 'Kuɗin Sefa na Afirka Ta Yamma',
{'JPY': ['JP¥', '¥'], 'NGN': ['₦'], 'USD': ['US$', '$']}, plural
];
| mgol/angular | packages/common/locales/ha-NE.ts | TypeScript | mit | 1,450 |
Test Shell for Interactive Environments
=========================================
This document describes how to use the `TestShell` submodule in the functional
test suite.
The `TestShell` submodule extends the `BitcoinTestFramework` functionality to
external interactive environments for prototyping and educational purposes. Just
like `BitcoinTestFramework`, the `TestShell` allows the user to:
* Manage regtest bitcoind subprocesses.
* Access RPC interfaces of the underlying bitcoind instances.
* Log events to the functional test logging utility.
The `TestShell` can be useful in interactive environments where it is necessary
to extend the object lifetime of the underlying `BitcoinTestFramework` between
user inputs. Such environments include the Python3 command line interpreter or
[Jupyter](https://jupyter.org/) notebooks running a Python3 kernel.
## 1. Requirements
* Python3
* `bitcoind` built in the same repository as the `TestShell`.
## 2. Importing `TestShell` from the Bitcoin Core repository
We can import the `TestShell` by adding the path of the Bitcoin Core
`test_framework` module to the beginning of the PATH variable, and then
importing the `TestShell` class from the `test_shell` sub-package.
```
>>> import sys
>>> sys.path.insert(0, "/path/to/bitcoin/test/functional")
>>> from test_framework.test_shell import TestShell
```
The following `TestShell` methods manage the lifetime of the underlying bitcoind
processes and logging utilities.
* `TestShell.setup()`
* `TestShell.shutdown()`
The `TestShell` inherits all `BitcoinTestFramework` members and methods, such
as:
* `TestShell.nodes[index].rpc_method()`
* `TestShell.log.info("Custom log message")`
The following sections demonstrate how to initialize, run, and shut down a
`TestShell` object.
## 3. Initializing a `TestShell` object
```
>>> test = TestShell().setup(num_nodes=2, setup_clean_chain=True)
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework (INFO): Initializing test directory /path/to/bitcoin_func_test_XXXXXXX
```
The `TestShell` forwards all functional test parameters of the parent
`BitcoinTestFramework` object. The full set of argument keywords which can be
used to initialize the `TestShell` can be found in [section
#6](#custom-testshell-parameters) of this document.
**Note: Running multiple instances of `TestShell` is not allowed.** Running a
single process also ensures that logging remains consolidated in the same
temporary folder. If you need more bitcoind nodes than set by default (1),
simply increase the `num_nodes` parameter during setup.
```
>>> test2 = TestShell().setup()
TestShell is already running!
```
## 4. Interacting with the `TestShell`
Unlike the `BitcoinTestFramework` class, the `TestShell` keeps the underlying
Bitcoind subprocesses (nodes) and logging utilities running until the user
explicitly shuts down the `TestShell` object.
During the time between the `setup` and `shutdown` calls, all `bitcoind` node
processes and `BitcoinTestFramework` convenience methods can be accessed
interactively.
**Example: Mining a regtest chain**
By default, the `TestShell` nodes are initialized with a clean chain. This means
that each node of the `TestShell` is initialized with a block height of 0.
```
>>> test.nodes[0].getblockchaininfo()["blocks"]
0
```
We now let the first node generate 101 regtest blocks, and direct the coinbase
rewards to a wallet address owned by the mining node.
```
>>> address = test.nodes[0].getnewaddress()
>>> test.self.generatetoaddress(nodes[0], 101, address)
['2b98dd0044aae6f1cca7f88a0acf366a4bfe053c7f7b00da3c0d115f03d67efb', ...
```
Since the two nodes are both initialized by default to establish an outbound
connection to each other during `setup`, the second node's chain will include
the mined blocks as soon as they propagate.
```
>>> test.nodes[1].getblockchaininfo()["blocks"]
101
```
The block rewards from the first block are now spendable by the wallet of the
first node.
```
>>> test.nodes[0].getbalance()
Decimal('50.00000000')
```
We can also log custom events to the logger.
```
>>> test.nodes[0].log.info("Successfully mined regtest chain!")
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework.node0 (INFO): Successfully mined regtest chain!
```
**Note: Please also consider the functional test
[readme](../test/functional/README.md), which provides an overview of the
test-framework**. Modules such as
[key.py](../test/functional/test_framework/key.py),
[script.py](../test/functional/test_framework/script.py) and
[messages.py](../test/functional/test_framework/messages.py) are particularly
useful in constructing objects which can be passed to the bitcoind nodes managed
by a running `TestShell` object.
## 5. Shutting the `TestShell` down
Shutting down the `TestShell` will safely tear down all running bitcoind
instances and remove all temporary data and logging directories.
```
>>> test.shutdown()
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework (INFO): Stopping nodes
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework (INFO): Cleaning up /path/to/bitcoin_func_test_XXXXXXX on exit
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework (INFO): Tests successful
```
To prevent the logs from being removed after a shutdown, simply set the
`TestShell.options.nocleanup` member to `True`.
```
>>> test.options.nocleanup = True
>>> test.shutdown()
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework (INFO): Stopping nodes
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework (INFO): Not cleaning up dir /path/to/bitcoin_func_test_XXXXXXX on exit
20XX-XX-XXTXX:XX:XX.XXXXXXX TestFramework (INFO): Tests successful
```
The following utility consolidates logs from the bitcoind nodes and the
underlying `BitcoinTestFramework`:
* `/path/to/bitcoin/test/functional/combine_logs.py
'/path/to/bitcoin_func_test_XXXXXXX'`
## 6. Custom `TestShell` parameters
The `TestShell` object initializes with the default settings inherited from the
`BitcoinTestFramework` class. The user can override these in
`TestShell.setup(key=value)`.
**Note:** `TestShell.reset()` will reset test parameters to default values and
can be called after the TestShell is shut down.
| Test parameter key | Default Value | Description |
|---|---|---|
| `bind_to_localhost_only` | `True` | Binds bitcoind RPC services to `127.0.0.1` if set to `True`.|
| `cachedir` | `"/path/to/bitcoin/test/cache"` | Sets the bitcoind datadir directory. |
| `chain` | `"regtest"` | Sets the chain-type for the underlying test bitcoind processes. |
| `configfile` | `"/path/to/bitcoin/test/config.ini"` | Sets the location of the test framework config file. |
| `coveragedir` | `None` | Records bitcoind RPC test coverage into this directory if set. |
| `loglevel` | `INFO` | Logs events at this level and higher. Can be set to `DEBUG`, `INFO`, `WARNING`, `ERROR` or `CRITICAL`. |
| `nocleanup` | `False` | Cleans up temporary test directory if set to `True` during `shutdown`. |
| `noshutdown` | `False` | Does not stop bitcoind instances after `shutdown` if set to `True`. |
| `num_nodes` | `1` | Sets the number of initialized bitcoind processes. |
| `perf` | False | Profiles running nodes with `perf` for the duration of the test if set to `True`. |
| `rpc_timeout` | `60` | Sets the RPC server timeout for the underlying bitcoind processes. |
| `setup_clean_chain` | `False` | A 200-block-long chain is initialized from cache by default. Instead, `setup_clean_chain` initializes an empty blockchain if set to `True`. |
| `randomseed` | Random Integer | `TestShell.options.randomseed` is a member of `TestShell` which can be accessed during a test to seed a random generator. User can override default with a constant value for reproducible test runs. |
| `supports_cli` | `False` | Whether the bitcoin-cli utility is compiled and available for the test. |
| `tmpdir` | `"/var/folders/.../"` | Sets directory for test logs. Will be deleted upon a successful test run unless `nocleanup` is set to `True` |
| `trace_rpc` | `False` | Logs all RPC calls if set to `True`. |
| `usecli` | `False` | Uses the bitcoin-cli interface for all bitcoind commands instead of directly calling the RPC server. Requires `supports_cli`. |
| particl/particl-core | test/functional/test-shell.md | Markdown | mit | 8,126 |
import storageHelper, { setItem, getItem, removeItem, clear, showStorageLogger } from 'storage-helper';
storageHelper.setItem('foo', 'bar');
storageHelper.setItem('foo', 'baz', true);
storageHelper.setItem('foo', 'bas', false);
storageHelper.getItem('foo'); // $ExpectType string | null
storageHelper.getItem('foo', false); // $ExpectType string | null
storageHelper.getItem('foo', undefined); // $ExpectType string | null
storageHelper.getItem('foo', false, Boolean() ? 1 : undefined); // $ExpectType string | number | null
storageHelper.getItem('foo', false, 1); // $ExpectType string | number | null
storageHelper.getItem('foo', false, undefined); // $ExpectType string | null
storageHelper.getItem('foo', true); // $ExpectType any
storageHelper.getItem('foo', true, 1); // $ExpectType any
storageHelper.getItem('foo', Boolean()); // $ExpectType any
storageHelper.removeItem('foo');
storageHelper.clear();
showStorageLogger(true);
setItem('foo', 'bar');
getItem('foo');
removeItem('foo');
clear();
| borisyankov/DefinitelyTyped | types/storage-helper/storage-helper-tests.ts | TypeScript | mit | 1,007 |
#!/bin/sh -e
git pull
# If .gitmodules has changed.
git submodule sync
# If new submodules were added in upstream.
git submodule update --init
# If the head is detached on any of them.
git submodule foreach git checkout master
# TODO: Accept failing pulls when not in the correct networks. Find a better solution?
#git submodule foreach git pull
SUBMODULES=$(git config --file .gitmodules --get-regexp path | awk '{ print $2 }')
CURRENT_DIRECTORY="${PWD}"
for SUBMODULE in ${SUBMODULES}; do
echo "${SUBMODULE}"
cd "${CURRENT_DIRECTORY}/${SUBMODULE}"
git pull || true
done
| FunTimeCoding/cpp-skeleton | script/update-repository.sh | Shell | mit | 590 |
/*
* linux/fs/ext4/readpage.c
*
* Copyright (C) 2002, Linus Torvalds.
* Copyright (C) 2015, Google, Inc.
*
* This was originally taken from fs/mpage.c
*
* The intent is the ext4_mpage_readpages() function here is intended
* to replace mpage_readpages() in the general case, not just for
* encrypted files. It has some limitations (see below), where it
* will fall back to read_block_full_page(), but these limitations
* should only be hit when page_size != block_size.
*
* This will allow us to attach a callback function to support ext4
* encryption.
*
* If anything unusual happens, such as:
*
* - encountering a page which has buffers
* - encountering a page which has a non-hole after a hole
* - encountering a page with non-contiguous blocks
*
* then this code just gives up and calls the buffer_head-based read function.
* It does handle a page which has holes at the end - that is a common case:
* the end-of-file on blocksize < PAGE_CACHE_SIZE setups.
*
*/
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/mm.h>
#include <linux/kdev_t.h>
#include <linux/gfp.h>
#include <linux/bio.h>
#include <linux/fs.h>
#include <linux/buffer_head.h>
#include <linux/blkdev.h>
#include <linux/highmem.h>
#include <linux/prefetch.h>
#include <linux/mpage.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/pagevec.h>
#include <linux/cleancache.h>
#include "ext4.h"
/*
* Call ext4_decrypt on every single page, reusing the encryption
* context.
*/
static void completion_pages(struct work_struct *work)
{
#ifdef CONFIG_EXT4_FS_ENCRYPTION
struct ext4_crypto_ctx *ctx =
container_of(work, struct ext4_crypto_ctx, r.work);
struct bio *bio = ctx->r.bio;
struct bio_vec *bv;
int i;
bio_for_each_segment_all(bv, bio, i) {
struct page *page = bv->bv_page;
int ret = ext4_decrypt(page);
if (ret) {
WARN_ON_ONCE(1);
SetPageError(page);
} else
SetPageUptodate(page);
unlock_page(page);
}
ext4_release_crypto_ctx(ctx);
bio_put(bio);
#else
BUG();
#endif
}
static inline bool ext4_bio_encrypted(struct bio *bio)
{
#ifdef CONFIG_EXT4_FS_ENCRYPTION
return unlikely(bio->bi_private != NULL);
#else
return false;
#endif
}
/*
* I/O completion handler for multipage BIOs.
*
* The mpage code never puts partial pages into a BIO (except for end-of-file).
* If a page does not map to a contiguous run of blocks then it simply falls
* back to block_read_full_page().
*
* Why is this? If a page's completion depends on a number of different BIOs
* which can complete in any order (or at the same time) then determining the
* status of that page is hard. See end_buffer_async_read() for the details.
* There is no point in duplicating all that complexity.
*/
static void mpage_end_io(struct bio *bio, int err)
{
struct bio_vec *bv;
int i;
if (ext4_bio_encrypted(bio)) {
struct ext4_crypto_ctx *ctx = bio->bi_private;
if (err) {
ext4_release_crypto_ctx(ctx);
} else {
INIT_WORK(&ctx->r.work, completion_pages);
ctx->r.bio = bio;
queue_work(ext4_read_workqueue, &ctx->r.work);
return;
}
}
bio_for_each_segment_all(bv, bio, i) {
struct page *page = bv->bv_page;
if (!err) {
SetPageUptodate(page);
} else {
ClearPageUptodate(page);
SetPageError(page);
}
unlock_page(page);
}
bio_put(bio);
}
int ext4_mpage_readpages(struct address_space *mapping,
struct list_head *pages, struct page *page,
unsigned nr_pages)
{
struct bio *bio = NULL;
unsigned page_idx;
sector_t last_block_in_bio = 0;
struct inode *inode = mapping->host;
const unsigned blkbits = inode->i_blkbits;
const unsigned blocks_per_page = PAGE_CACHE_SIZE >> blkbits;
const unsigned blocksize = 1 << blkbits;
sector_t block_in_file;
sector_t last_block;
sector_t last_block_in_file;
sector_t blocks[MAX_BUF_PER_PAGE];
unsigned page_block;
struct block_device *bdev = inode->i_sb->s_bdev;
int length;
unsigned relative_block = 0;
struct ext4_map_blocks map;
map.m_pblk = 0;
map.m_lblk = 0;
map.m_len = 0;
map.m_flags = 0;
for (page_idx = 0; nr_pages; page_idx++, nr_pages--) {
int fully_mapped = 1;
unsigned first_hole = blocks_per_page;
prefetchw(&page->flags);
if (pages) {
page = list_entry(pages->prev, struct page, lru);
list_del(&page->lru);
if (add_to_page_cache_lru(page, mapping,
page->index, GFP_KERNEL))
goto next_page;
}
if (page_has_buffers(page))
goto confused;
block_in_file = (sector_t)page->index << (PAGE_CACHE_SHIFT - blkbits);
last_block = block_in_file + nr_pages * blocks_per_page;
last_block_in_file = (i_size_read(inode) + blocksize - 1) >> blkbits;
if (last_block > last_block_in_file)
last_block = last_block_in_file;
page_block = 0;
/*
* Map blocks using the previous result first.
*/
if ((map.m_flags & EXT4_MAP_MAPPED) &&
block_in_file > map.m_lblk &&
block_in_file < (map.m_lblk + map.m_len)) {
unsigned map_offset = block_in_file - map.m_lblk;
unsigned last = map.m_len - map_offset;
for (relative_block = 0; ; relative_block++) {
if (relative_block == last) {
/* needed? */
map.m_flags &= ~EXT4_MAP_MAPPED;
break;
}
if (page_block == blocks_per_page)
break;
blocks[page_block] = map.m_pblk + map_offset +
relative_block;
page_block++;
block_in_file++;
}
}
/*
* Then do more ext4_map_blocks() calls until we are
* done with this page.
*/
while (page_block < blocks_per_page) {
if (block_in_file < last_block) {
map.m_lblk = block_in_file;
map.m_len = last_block - block_in_file;
if (ext4_map_blocks(NULL, inode, &map, 0) < 0) {
set_error_page:
SetPageError(page);
zero_user_segment(page, 0,
PAGE_CACHE_SIZE);
unlock_page(page);
goto next_page;
}
}
if ((map.m_flags & EXT4_MAP_MAPPED) == 0) {
fully_mapped = 0;
if (first_hole == blocks_per_page)
first_hole = page_block;
page_block++;
block_in_file++;
continue;
}
if (first_hole != blocks_per_page)
goto confused; /* hole -> non-hole */
/* Contiguous blocks? */
if (page_block && blocks[page_block-1] != map.m_pblk-1)
goto confused;
for (relative_block = 0; ; relative_block++) {
if (relative_block == map.m_len) {
/* needed? */
map.m_flags &= ~EXT4_MAP_MAPPED;
break;
} else if (page_block == blocks_per_page)
break;
blocks[page_block] = map.m_pblk+relative_block;
page_block++;
block_in_file++;
}
}
if (first_hole != blocks_per_page) {
zero_user_segment(page, first_hole << blkbits,
PAGE_CACHE_SIZE);
if (first_hole == 0) {
SetPageUptodate(page);
unlock_page(page);
goto next_page;
}
} else if (fully_mapped) {
SetPageMappedToDisk(page);
}
if (fully_mapped && blocks_per_page == 1 &&
!PageUptodate(page) && cleancache_get_page(page) == 0) {
SetPageUptodate(page);
goto confused;
}
/*
* This page will go to BIO. Do we need to send this
* BIO off first?
*/
if (bio && (last_block_in_bio != blocks[0] - 1)) {
submit_and_realloc:
submit_bio(READ, bio);
bio = NULL;
}
if (bio == NULL) {
struct ext4_crypto_ctx *ctx = NULL;
if (ext4_encrypted_inode(inode) &&
S_ISREG(inode->i_mode)) {
ctx = ext4_get_crypto_ctx(inode, GFP_NOFS);
if (IS_ERR(ctx))
goto set_error_page;
}
bio = bio_alloc(GFP_KERNEL,
min_t(int, nr_pages, bio_get_nr_vecs(bdev)));
if (!bio) {
if (ctx)
ext4_release_crypto_ctx(ctx);
goto set_error_page;
}
bio->bi_bdev = bdev;
bio->bi_iter.bi_sector = blocks[0] << (blkbits - 9);
bio->bi_end_io = mpage_end_io;
bio->bi_private = ctx;
}
length = first_hole << blkbits;
if (bio_add_page(bio, page, length, 0) < length)
goto submit_and_realloc;
if (((map.m_flags & EXT4_MAP_BOUNDARY) &&
(relative_block == map.m_len)) ||
(first_hole != blocks_per_page)) {
submit_bio(READ, bio);
bio = NULL;
} else
last_block_in_bio = blocks[blocks_per_page - 1];
goto next_page;
confused:
if (bio) {
submit_bio(READ, bio);
bio = NULL;
}
if (!PageUptodate(page))
block_read_full_page(page, ext4_get_block);
else
unlock_page(page);
next_page:
if (pages)
page_cache_release(page);
}
BUG_ON(pages && !list_empty(pages));
if (bio)
submit_bio(READ, bio);
return 0;
}
| menghang/android_kernel_xiaomi_msm8996 | fs/ext4/readpage.c | C | gpl-2.0 | 8,396 |
/*
* Copyright 2008 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
* Copyright 2009 Jerome Glisse.
*
* 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) OR AUTHOR(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.
*
* Authors: Dave Airlie
* Alex Deucher
* Jerome Glisse
*/
#ifndef __AMDGPU_OBJECT_H__
#define __AMDGPU_OBJECT_H__
#include <drm/amdgpu_drm.h>
#include "amdgpu.h"
#define AMDGPU_BO_INVALID_OFFSET LONG_MAX
#define AMDGPU_BO_MAX_PLACEMENTS 3
struct amdgpu_bo_param {
unsigned long size;
int byte_align;
u32 domain;
u32 preferred_domain;
u64 flags;
enum ttm_bo_type type;
struct reservation_object *resv;
};
/* bo virtual addresses in a vm */
struct amdgpu_bo_va_mapping {
struct amdgpu_bo_va *bo_va;
struct list_head list;
struct rb_node rb;
uint64_t start;
uint64_t last;
uint64_t __subtree_last;
uint64_t offset;
uint64_t flags;
};
/* User space allocated BO in a VM */
struct amdgpu_bo_va {
struct amdgpu_vm_bo_base base;
/* protected by bo being reserved */
unsigned ref_count;
/* all other members protected by the VM PD being reserved */
struct dma_fence *last_pt_update;
/* mappings for this bo_va */
struct list_head invalids;
struct list_head valids;
/* If the mappings are cleared or filled */
bool cleared;
bool is_xgmi;
};
struct amdgpu_bo {
/* Protected by tbo.reserved */
u32 preferred_domains;
u32 allowed_domains;
struct ttm_place placements[AMDGPU_BO_MAX_PLACEMENTS];
struct ttm_placement placement;
struct ttm_buffer_object tbo;
struct ttm_bo_kmap_obj kmap;
u64 flags;
unsigned pin_count;
u64 tiling_flags;
u64 metadata_flags;
void *metadata;
u32 metadata_size;
unsigned prime_shared_count;
/* per VM structure for page tables and with virtual addresses */
struct amdgpu_vm_bo_base *vm_bo;
/* Constant after initialization */
struct drm_gem_object gem_base;
struct amdgpu_bo *parent;
struct amdgpu_bo *shadow;
struct ttm_bo_kmap_obj dma_buf_vmap;
struct amdgpu_mn *mn;
union {
struct list_head mn_list;
struct list_head shadow_list;
};
struct kgd_mem *kfd_bo;
};
static inline struct amdgpu_bo *ttm_to_amdgpu_bo(struct ttm_buffer_object *tbo)
{
return container_of(tbo, struct amdgpu_bo, tbo);
}
/**
* amdgpu_mem_type_to_domain - return domain corresponding to mem_type
* @mem_type: ttm memory type
*
* Returns corresponding domain of the ttm mem_type
*/
static inline unsigned amdgpu_mem_type_to_domain(u32 mem_type)
{
switch (mem_type) {
case TTM_PL_VRAM:
return AMDGPU_GEM_DOMAIN_VRAM;
case TTM_PL_TT:
return AMDGPU_GEM_DOMAIN_GTT;
case TTM_PL_SYSTEM:
return AMDGPU_GEM_DOMAIN_CPU;
case AMDGPU_PL_GDS:
return AMDGPU_GEM_DOMAIN_GDS;
case AMDGPU_PL_GWS:
return AMDGPU_GEM_DOMAIN_GWS;
case AMDGPU_PL_OA:
return AMDGPU_GEM_DOMAIN_OA;
default:
break;
}
return 0;
}
/**
* amdgpu_bo_reserve - reserve bo
* @bo: bo structure
* @no_intr: don't return -ERESTARTSYS on pending signal
*
* Returns:
* -ERESTARTSYS: A wait for the buffer to become unreserved was interrupted by
* a signal. Release all buffer reservations and return to user-space.
*/
static inline int amdgpu_bo_reserve(struct amdgpu_bo *bo, bool no_intr)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
int r;
r = ttm_bo_reserve(&bo->tbo, !no_intr, false, NULL);
if (unlikely(r != 0)) {
if (r != -ERESTARTSYS)
dev_err(adev->dev, "%p reserve failed\n", bo);
return r;
}
return 0;
}
static inline void amdgpu_bo_unreserve(struct amdgpu_bo *bo)
{
ttm_bo_unreserve(&bo->tbo);
}
static inline unsigned long amdgpu_bo_size(struct amdgpu_bo *bo)
{
return bo->tbo.num_pages << PAGE_SHIFT;
}
static inline unsigned amdgpu_bo_ngpu_pages(struct amdgpu_bo *bo)
{
return (bo->tbo.num_pages << PAGE_SHIFT) / AMDGPU_GPU_PAGE_SIZE;
}
static inline unsigned amdgpu_bo_gpu_page_alignment(struct amdgpu_bo *bo)
{
return (bo->tbo.mem.page_alignment << PAGE_SHIFT) / AMDGPU_GPU_PAGE_SIZE;
}
/**
* amdgpu_bo_mmap_offset - return mmap offset of bo
* @bo: amdgpu object for which we query the offset
*
* Returns mmap offset of the object.
*/
static inline u64 amdgpu_bo_mmap_offset(struct amdgpu_bo *bo)
{
return drm_vma_node_offset_addr(&bo->tbo.vma_node);
}
/**
* amdgpu_bo_in_cpu_visible_vram - check if BO is (partly) in visible VRAM
*/
static inline bool amdgpu_bo_in_cpu_visible_vram(struct amdgpu_bo *bo)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
unsigned fpfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
struct drm_mm_node *node = bo->tbo.mem.mm_node;
unsigned long pages_left;
if (bo->tbo.mem.mem_type != TTM_PL_VRAM)
return false;
for (pages_left = bo->tbo.mem.num_pages; pages_left;
pages_left -= node->size, node++)
if (node->start < fpfn)
return true;
return false;
}
/**
* amdgpu_bo_explicit_sync - return whether the bo is explicitly synced
*/
static inline bool amdgpu_bo_explicit_sync(struct amdgpu_bo *bo)
{
return bo->flags & AMDGPU_GEM_CREATE_EXPLICIT_SYNC;
}
bool amdgpu_bo_is_amdgpu_bo(struct ttm_buffer_object *bo);
void amdgpu_bo_placement_from_domain(struct amdgpu_bo *abo, u32 domain);
int amdgpu_bo_create(struct amdgpu_device *adev,
struct amdgpu_bo_param *bp,
struct amdgpu_bo **bo_ptr);
int amdgpu_bo_create_reserved(struct amdgpu_device *adev,
unsigned long size, int align,
u32 domain, struct amdgpu_bo **bo_ptr,
u64 *gpu_addr, void **cpu_addr);
int amdgpu_bo_create_kernel(struct amdgpu_device *adev,
unsigned long size, int align,
u32 domain, struct amdgpu_bo **bo_ptr,
u64 *gpu_addr, void **cpu_addr);
void amdgpu_bo_free_kernel(struct amdgpu_bo **bo, u64 *gpu_addr,
void **cpu_addr);
int amdgpu_bo_kmap(struct amdgpu_bo *bo, void **ptr);
void *amdgpu_bo_kptr(struct amdgpu_bo *bo);
void amdgpu_bo_kunmap(struct amdgpu_bo *bo);
struct amdgpu_bo *amdgpu_bo_ref(struct amdgpu_bo *bo);
void amdgpu_bo_unref(struct amdgpu_bo **bo);
int amdgpu_bo_pin(struct amdgpu_bo *bo, u32 domain);
int amdgpu_bo_pin_restricted(struct amdgpu_bo *bo, u32 domain,
u64 min_offset, u64 max_offset);
int amdgpu_bo_unpin(struct amdgpu_bo *bo);
int amdgpu_bo_evict_vram(struct amdgpu_device *adev);
int amdgpu_bo_init(struct amdgpu_device *adev);
int amdgpu_bo_late_init(struct amdgpu_device *adev);
void amdgpu_bo_fini(struct amdgpu_device *adev);
int amdgpu_bo_fbdev_mmap(struct amdgpu_bo *bo,
struct vm_area_struct *vma);
int amdgpu_bo_set_tiling_flags(struct amdgpu_bo *bo, u64 tiling_flags);
void amdgpu_bo_get_tiling_flags(struct amdgpu_bo *bo, u64 *tiling_flags);
int amdgpu_bo_set_metadata (struct amdgpu_bo *bo, void *metadata,
uint32_t metadata_size, uint64_t flags);
int amdgpu_bo_get_metadata(struct amdgpu_bo *bo, void *buffer,
size_t buffer_size, uint32_t *metadata_size,
uint64_t *flags);
void amdgpu_bo_move_notify(struct ttm_buffer_object *bo,
bool evict,
struct ttm_mem_reg *new_mem);
int amdgpu_bo_fault_reserve_notify(struct ttm_buffer_object *bo);
void amdgpu_bo_fence(struct amdgpu_bo *bo, struct dma_fence *fence,
bool shared);
int amdgpu_bo_sync_wait(struct amdgpu_bo *bo, void *owner, bool intr);
u64 amdgpu_bo_gpu_offset(struct amdgpu_bo *bo);
int amdgpu_bo_validate(struct amdgpu_bo *bo);
int amdgpu_bo_restore_shadow(struct amdgpu_bo *shadow,
struct dma_fence **fence);
uint32_t amdgpu_bo_get_preferred_pin_domain(struct amdgpu_device *adev,
uint32_t domain);
/*
* sub allocation
*/
static inline uint64_t amdgpu_sa_bo_gpu_addr(struct amdgpu_sa_bo *sa_bo)
{
return sa_bo->manager->gpu_addr + sa_bo->soffset;
}
static inline void * amdgpu_sa_bo_cpu_addr(struct amdgpu_sa_bo *sa_bo)
{
return sa_bo->manager->cpu_ptr + sa_bo->soffset;
}
int amdgpu_sa_bo_manager_init(struct amdgpu_device *adev,
struct amdgpu_sa_manager *sa_manager,
unsigned size, u32 align, u32 domain);
void amdgpu_sa_bo_manager_fini(struct amdgpu_device *adev,
struct amdgpu_sa_manager *sa_manager);
int amdgpu_sa_bo_manager_start(struct amdgpu_device *adev,
struct amdgpu_sa_manager *sa_manager);
int amdgpu_sa_bo_new(struct amdgpu_sa_manager *sa_manager,
struct amdgpu_sa_bo **sa_bo,
unsigned size, unsigned align);
void amdgpu_sa_bo_free(struct amdgpu_device *adev,
struct amdgpu_sa_bo **sa_bo,
struct dma_fence *fence);
#if defined(CONFIG_DEBUG_FS)
void amdgpu_sa_bo_dump_debug_info(struct amdgpu_sa_manager *sa_manager,
struct seq_file *m);
#endif
#endif
| koct9i/linux | drivers/gpu/drm/amd/amdgpu/amdgpu_object.h | C | gpl-2.0 | 9,556 |
/* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 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 PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "App.h"
#include "Dialogs/ModalPopups.h"
using namespace pxSizerFlags;
using namespace Threading;
// NOTE: Currently unused module. Stuck Threads are not detected or handled at this time,
// though I would like to have something in place in the distant future. --air
Dialogs::StuckThreadDialog::StuckThreadDialog( wxWindow* parent, StuckThreadActionType action, pxThread& stuck_thread )
: wxDialogWithHelpers( parent, _("PCSX2 Thread is not responding") )
{
stuck_thread.AddListener( this );
*this += Heading( wxsFormat(
pxE( L"The thread '%s' is not responding. It could be deadlocked, or it might just be running *really* slowly."
),
stuck_thread.GetName().data()
) );
*this += Heading(
L"\nDo you want to stop the program [Yes/No]?"
L"\nOr press [Ignore] to suppress further assertions."
);
*this += new ModalButtonPanel( this, MsgButtons().Cancel().Custom(L"Wait", "wait") ) | StdCenter();
if( wxWindow* idyes = FindWindowById( wxID_YES ) )
idyes->SetFocus();
}
void Dialogs::StuckThreadDialog::OnThreadCleanup()
{
}
| micove/pcsx2 | pcsx2/gui/Dialogs/StuckThreadDialog.cpp | C++ | gpl-2.0 | 1,813 |
#
# Copyright (C) 2006-2013 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=iproute2
PKG_VERSION:=3.11.0
PKG_RELEASE:=1
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
PKG_SOURCE_URL:=http://kernel.org/pub/linux/utils/net/iproute2/
PKG_MD5SUM:=d7ffb27bc9f0d80577b1f3fb9d1a7689
PKG_BUILD_PARALLEL:=1
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(BUILD_VARIANT)/$(PKG_NAME)-$(PKG_VERSION)
include $(INCLUDE_DIR)/package.mk
define Package/iproute2/Default
TITLE:=Routing control utility ($(2))
SECTION:=net
CATEGORY:=Network
URL:=http://linux-net.osdl.org/index.php/Iproute2
SUBMENU:=Routing and Redirection
DEPENDS:= +libnl-tiny
VARIANT:=$(1)
endef
Package/ip=$(call Package/iproute2/Default,tiny,Minimal)
Package/ip-full=$(call Package/iproute2/Default,full,Full)
define Package/ip/conffiles
/etc/iproute2/rt_tables
endef
define Package/ip-$(BUILD_VARIANT)/conffiles
$(Package/ip/conffiles)
endef
define Package/tc
$(call Package/iproute2/Default)
TITLE:=Traffic control utility
DEPENDS:=+kmod-sched-core
endef
define Package/genl
$(call Package/iproute2/Default)
TITLE:=General netlink utility frontend
endef
define Package/ss
$(call Package/iproute2/Default)
TITLE:=Socket statistics utility
endef
ifeq ($(BUILD_VARIANT),tiny)
IP_CONFIG_TINY:=y
endif
define Build/Configure
$(SED) "s,-I/usr/include/db3,," $(PKG_BUILD_DIR)/Makefile
$(SED) "s,^KERNEL_INCLUDE.*,KERNEL_INCLUDE=$(LINUX_DIR)/include," \
$(PKG_BUILD_DIR)/Makefile
$(SED) "s,^LIBC_INCLUDE.*,LIBC_INCLUDE=$(STAGING_DIR)/include," \
$(PKG_BUILD_DIR)/Makefile
echo "static const char SNAPSHOT[] = \"$(PKG_VERSION)-$(PKG_RELEASE)-openwrt\";" \
> $(PKG_BUILD_DIR)/include/SNAPSHOT.h
endef
ifdef CONFIG_USE_EGLIBC
ifndef CONFIG_EGLIBC_VERSION_2_13
TARGET_CFLAGS += -DHAVE_SETNS
endif
endif
TARGET_CFLAGS += -ffunction-sections -fdata-sections
MAKE_FLAGS += \
EXTRA_CCOPTS="$(TARGET_CFLAGS) -I../include -I$(STAGING_DIR)/usr/include/libnl-tiny" \
KERNEL_INCLUDE="$(LINUX_DIR)/include" \
SHARED_LIBS="" \
LDFLAGS="-Wl,--gc-sections" \
IP_CONFIG_TINY=$(IP_CONFIG_TINY) \
FPIC=""
define Build/Compile
+$(MAKE_VARS) $(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR) $(MAKE_FLAGS)
endef
define Build/InstallDev
$(INSTALL_DIR) $(1)/usr/include
$(CP) $(PKG_BUILD_DIR)/include/libnetlink.h $(1)/usr/include/
$(INSTALL_DIR) $(1)/usr/lib
$(CP) $(PKG_BUILD_DIR)/lib/libnetlink.a $(1)/usr/lib/
endef
define Package/ip/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_DIR) $(1)/etc/iproute2
$(INSTALL_DATA) $(PKG_BUILD_DIR)/etc/iproute2/rt_tables $(1)/etc/iproute2
$(INSTALL_BIN) $(PKG_BUILD_DIR)/ip/ip $(1)/usr/sbin/
endef
define Package/ip-$(BUILD_VARIANT)/install
$(Package/ip/install)
endef
define Package/tc/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/tc/tc $(1)/usr/sbin/
$(INSTALL_DIR) $(1)/etc/hotplug.d/iface
$(INSTALL_BIN) ./files/15-teql $(1)/etc/hotplug.d/iface/
endef
define Package/genl/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/genl/genl $(1)/usr/sbin/
endef
define Package/ss/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/misc/ss $(1)/usr/sbin/
endef
$(eval $(call BuildPackage,ip))
$(eval $(call BuildPackage,ip-full))
$(eval $(call BuildPackage,tc))
$(eval $(call BuildPackage,genl))
$(eval $(call BuildPackage,ss))
| sprinkler/rainmachine-openwrt-os | package/network/utils/iproute2/Makefile | Makefile | gpl-2.0 | 3,441 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/omnibox/omnibox_field_trial.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string16.h"
#include "chrome/browser/autocomplete/autocomplete_input.h"
#include "chrome/browser/search/search.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/metrics/variations/variations_util.h"
#include "components/variations/entropy_provider.h"
#include "testing/gtest/include/gtest/gtest.h"
class OmniboxFieldTrialTest : public testing::Test {
public:
OmniboxFieldTrialTest() {
ResetFieldTrialList();
}
void ResetFieldTrialList() {
// Destroy the existing FieldTrialList before creating a new one to avoid
// a DCHECK.
field_trial_list_.reset();
field_trial_list_.reset(new base::FieldTrialList(
new metrics::SHA1EntropyProvider("foo")));
chrome_variations::testing::ClearAllVariationParams();
OmniboxFieldTrial::ActivateDynamicTrials();
}
// Creates and activates a field trial.
static base::FieldTrial* CreateTestTrial(const std::string& name,
const std::string& group_name) {
base::FieldTrial* trial = base::FieldTrialList::CreateFieldTrial(
name, group_name);
trial->group();
return trial;
}
// EXPECTS that demotions[match_type] exists with value expected_value.
static void VerifyDemotion(
const OmniboxFieldTrial::DemotionMultipliers& demotions,
AutocompleteMatchType::Type match_type,
float expected_value);
// EXPECT()s that OmniboxFieldTrial::GetValueForRuleInContext(|rule|,
// |page_classification|) returns |rule_value|.
static void ExpectRuleValue(
const std::string& rule_value,
const std::string& rule,
AutocompleteInput::PageClassification page_classification);
private:
scoped_ptr<base::FieldTrialList> field_trial_list_;
DISALLOW_COPY_AND_ASSIGN(OmniboxFieldTrialTest);
};
// static
void OmniboxFieldTrialTest::VerifyDemotion(
const OmniboxFieldTrial::DemotionMultipliers& demotions,
AutocompleteMatchType::Type match_type,
float expected_value) {
OmniboxFieldTrial::DemotionMultipliers::const_iterator demotion_it =
demotions.find(match_type);
ASSERT_TRUE(demotion_it != demotions.end());
EXPECT_FLOAT_EQ(expected_value, demotion_it->second);
}
// static
void OmniboxFieldTrialTest::ExpectRuleValue(
const std::string& rule_value,
const std::string& rule,
AutocompleteInput::PageClassification page_classification) {
EXPECT_EQ(rule_value,
OmniboxFieldTrial::GetValueForRuleInContext(
rule, page_classification));
}
// Test if GetDisabledProviderTypes() properly parses various field trial
// group names.
TEST_F(OmniboxFieldTrialTest, GetDisabledProviderTypes) {
EXPECT_EQ(0, OmniboxFieldTrial::GetDisabledProviderTypes());
{
SCOPED_TRACE("Invalid groups");
CreateTestTrial("AutocompleteDynamicTrial_0", "DisabledProviders_");
EXPECT_EQ(0, OmniboxFieldTrial::GetDisabledProviderTypes());
ResetFieldTrialList();
CreateTestTrial("AutocompleteDynamicTrial_1", "DisabledProviders_XXX");
EXPECT_EQ(0, OmniboxFieldTrial::GetDisabledProviderTypes());
ResetFieldTrialList();
CreateTestTrial("AutocompleteDynamicTrial_1", "DisabledProviders_12abc");
EXPECT_EQ(0, OmniboxFieldTrial::GetDisabledProviderTypes());
}
{
SCOPED_TRACE("Valid group name, unsupported trial name.");
ResetFieldTrialList();
CreateTestTrial("UnsupportedTrialName", "DisabledProviders_20");
EXPECT_EQ(0, OmniboxFieldTrial::GetDisabledProviderTypes());
}
{
SCOPED_TRACE("Valid field and group name.");
ResetFieldTrialList();
CreateTestTrial("AutocompleteDynamicTrial_2", "DisabledProviders_3");
EXPECT_EQ(3, OmniboxFieldTrial::GetDisabledProviderTypes());
// Two groups should be OR-ed together.
CreateTestTrial("AutocompleteDynamicTrial_3", "DisabledProviders_6");
EXPECT_EQ(7, OmniboxFieldTrial::GetDisabledProviderTypes());
}
}
// Test if InZeroSuggestFieldTrial() properly parses various field trial
// group names.
TEST_F(OmniboxFieldTrialTest, ZeroSuggestFieldTrial) {
EXPECT_FALSE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
{
SCOPED_TRACE("Valid group name, unsupported trial name.");
ResetFieldTrialList();
CreateTestTrial("UnsupportedTrialName", "EnableZeroSuggest");
EXPECT_FALSE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
ResetFieldTrialList();
CreateTestTrial("UnsupportedTrialName", "EnableZeroSuggest_Queries");
EXPECT_FALSE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
ResetFieldTrialList();
CreateTestTrial("UnsupportedTrialName", "EnableZeroSuggest_URLS");
EXPECT_FALSE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
}
{
SCOPED_TRACE("Valid trial name, unsupported group name.");
ResetFieldTrialList();
CreateTestTrial("AutocompleteDynamicTrial_2", "UnrelatedGroup");
EXPECT_FALSE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
}
{
SCOPED_TRACE("Valid field and group name.");
ResetFieldTrialList();
CreateTestTrial("AutocompleteDynamicTrial_2", "EnableZeroSuggest");
EXPECT_TRUE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
ResetFieldTrialList();
CreateTestTrial("AutocompleteDynamicTrial_2", "EnableZeroSuggest_Queries");
EXPECT_TRUE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
ResetFieldTrialList();
CreateTestTrial("AutocompleteDynamicTrial_3", "EnableZeroSuggest_URLs");
EXPECT_TRUE(OmniboxFieldTrial::InZeroSuggestFieldTrial());
}
}
TEST_F(OmniboxFieldTrialTest, GetDemotionsByTypeWithFallback) {
{
std::map<std::string, std::string> params;
params[std::string(OmniboxFieldTrial::kDemoteByTypeRule) + ":1:*"] =
"1:50,2:0";
params[std::string(OmniboxFieldTrial::kDemoteByTypeRule) + ":3:*"] =
"5:100";
params[std::string(OmniboxFieldTrial::kDemoteByTypeRule) + ":*:*"] = "1:25";
ASSERT_TRUE(chrome_variations::AssociateVariationParams(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A", params));
}
base::FieldTrialList::CreateFieldTrial(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A");
OmniboxFieldTrial::DemotionMultipliers demotions_by_type;
OmniboxFieldTrial::GetDemotionsByType(
AutocompleteInput::NTP, &demotions_by_type);
ASSERT_EQ(2u, demotions_by_type.size());
VerifyDemotion(demotions_by_type, AutocompleteMatchType::HISTORY_URL, 0.5);
VerifyDemotion(demotions_by_type, AutocompleteMatchType::HISTORY_TITLE, 0.0);
OmniboxFieldTrial::GetDemotionsByType(
AutocompleteInput::HOME_PAGE, &demotions_by_type);
ASSERT_EQ(1u, demotions_by_type.size());
VerifyDemotion(demotions_by_type, AutocompleteMatchType::NAVSUGGEST, 1.0);
OmniboxFieldTrial::GetDemotionsByType(
AutocompleteInput::BLANK, &demotions_by_type);
ASSERT_EQ(1u, demotions_by_type.size());
VerifyDemotion(demotions_by_type, AutocompleteMatchType::HISTORY_URL, 0.25);
}
TEST_F(OmniboxFieldTrialTest, GetUndemotableTopTypes) {
{
std::map<std::string, std::string> params;
const std::string rule(OmniboxFieldTrial::kUndemotableTopTypeRule);
params[rule + ":1:*"] = "1,3";
params[rule + ":3:*"] = "5";
params[rule + ":*:*"] = "2";
ASSERT_TRUE(chrome_variations::AssociateVariationParams(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A", params));
}
base::FieldTrialList::CreateFieldTrial(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A");
OmniboxFieldTrial::UndemotableTopMatchTypes undemotable_types;
undemotable_types = OmniboxFieldTrial::GetUndemotableTopTypes(
AutocompleteInput::NTP);
ASSERT_EQ(2u, undemotable_types.size());
ASSERT_EQ(1u, undemotable_types.count(AutocompleteMatchType::HISTORY_URL));
ASSERT_EQ(1u, undemotable_types.count(AutocompleteMatchType::HISTORY_BODY));
undemotable_types = OmniboxFieldTrial::GetUndemotableTopTypes(
AutocompleteInput::HOME_PAGE);
ASSERT_EQ(1u, undemotable_types.size());
ASSERT_EQ(1u, undemotable_types.count(AutocompleteMatchType::NAVSUGGEST));
undemotable_types = OmniboxFieldTrial::GetUndemotableTopTypes(
AutocompleteInput::BLANK);
ASSERT_EQ(1u, undemotable_types.size());
ASSERT_EQ(1u, undemotable_types.count(AutocompleteMatchType::HISTORY_TITLE));
}
TEST_F(OmniboxFieldTrialTest, GetValueForRuleInContext) {
{
std::map<std::string, std::string> params;
// Rule 1 has some exact matches and fallbacks at every level.
params["rule1:1:0"] = "rule1-1-0-value"; // NTP
params["rule1:3:0"] = "rule1-3-0-value"; // HOME_PAGE
params["rule1:4:1"] = "rule1-4-1-value"; // OTHER
params["rule1:4:*"] = "rule1-4-*-value"; // OTHER
params["rule1:*:1"] = "rule1-*-1-value"; // global
params["rule1:*:*"] = "rule1-*-*-value"; // global
// Rule 2 has no exact matches but has fallbacks.
params["rule2:*:0"] = "rule2-*-0-value"; // global
params["rule2:1:*"] = "rule2-1-*-value"; // NTP
params["rule2:*:*"] = "rule2-*-*-value"; // global
// Rule 3 has only a global fallback.
params["rule3:*:*"] = "rule3-*-*-value"; // global
// Rule 4 has an exact match but no fallbacks.
params["rule4:4:0"] = "rule4-4-0-value"; // OTHER
// Add a malformed rule to make sure it doesn't screw things up.
params["unrecognized"] = "unrecognized-value";
ASSERT_TRUE(chrome_variations::AssociateVariationParams(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A", params));
}
base::FieldTrialList::CreateFieldTrial(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A");
if (chrome::IsInstantExtendedAPIEnabled()) {
// Tests with Instant Extended enabled.
// Tests for rule 1.
ExpectRuleValue("rule1-4-1-value",
"rule1", AutocompleteInput::OTHER); // exact match
ExpectRuleValue("rule1-*-1-value",
"rule1", AutocompleteInput::BLANK); // partial fallback
ExpectRuleValue("rule1-*-1-value",
"rule1",
AutocompleteInput::NTP); // partial fallback
// Tests for rule 2.
ExpectRuleValue("rule2-1-*-value",
"rule2",
AutocompleteInput::NTP); // partial fallback
ExpectRuleValue("rule2-*-*-value",
"rule2", AutocompleteInput::OTHER); // global fallback
// Tests for rule 3.
ExpectRuleValue("rule3-*-*-value",
"rule3",
AutocompleteInput::HOME_PAGE); // global fallback
ExpectRuleValue("rule3-*-*-value",
"rule3",
AutocompleteInput::OTHER); // global fallback
// Tests for rule 4.
ExpectRuleValue("",
"rule4",
AutocompleteInput::BLANK); // no global fallback
ExpectRuleValue("",
"rule4",
AutocompleteInput::HOME_PAGE); // no global fallback
// Tests for rule 5 (a missing rule).
ExpectRuleValue("",
"rule5", AutocompleteInput::OTHER); // no rule at all
} else {
// Tests for rule 1.
ExpectRuleValue("rule1-1-0-value",
"rule1", AutocompleteInput::NTP); // exact match
ExpectRuleValue("rule1-1-0-value",
"rule1", AutocompleteInput::NTP); // exact match
ExpectRuleValue("rule1-*-*-value",
"rule1", AutocompleteInput::BLANK); // fallback to global
ExpectRuleValue("rule1-3-0-value",
"rule1",
AutocompleteInput::HOME_PAGE); // exact match
ExpectRuleValue("rule1-4-*-value",
"rule1", AutocompleteInput::OTHER); // partial fallback
ExpectRuleValue("rule1-*-*-value",
"rule1",
AutocompleteInput:: // fallback to global
SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT);
// Tests for rule 2.
ExpectRuleValue("rule2-*-0-value",
"rule2",
AutocompleteInput::HOME_PAGE); // partial fallback
ExpectRuleValue("rule2-*-0-value",
"rule2", AutocompleteInput::OTHER); // partial fallback
// Tests for rule 3.
ExpectRuleValue("rule3-*-*-value",
"rule3",
AutocompleteInput::HOME_PAGE); // fallback to global
ExpectRuleValue("rule3-*-*-value",
"rule3", AutocompleteInput::OTHER); // fallback to global
// Tests for rule 4.
ExpectRuleValue("",
"rule4", AutocompleteInput::BLANK); // no global fallback
ExpectRuleValue("",
"rule4",
AutocompleteInput::HOME_PAGE); // no global fallback
ExpectRuleValue("rule4-4-0-value",
"rule4", AutocompleteInput::OTHER); // exact match
// Tests for rule 5 (a missing rule).
ExpectRuleValue("",
"rule5", AutocompleteInput::OTHER); // no rule at all
}
}
| qtekfun/htcDesire820Kernel | external/chromium_org/chrome/browser/omnibox/omnibox_field_trial_unittest.cc | C++ | gpl-2.0 | 13,390 |
YUI.add("lang/calendar-base_nb-NO",function(e){e.Intl.add("calendar-base","nb-NO",{very_short_weekdays:["S\u00f8","Ma","Ti","On","To","Fr","L\u00f8"],first_weekday:1,weekends:[0,6]})},"3.14.1");
| aqt01/math_problems | node_modules/yui/calendar-base/lang/calendar-base_nb-NO.js | JavaScript | gpl-2.0 | 195 |
/*
* DHD Protocol Module for CDC and BDC.
*
* Copyright (C) 1999-2010, 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 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* 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.
*
* $Id: dhd_cdc.c,v 1.22.4.2.4.7.2.41 2010/06/23 19:58:18 Exp $
*
* BDC is like CDC, except it includes a header for data packets to convey
* packet priority over the bus, and flags (e.g. to indicate checksum status
* for dongle offload).
*/
#include <typedefs.h>
#include <osl.h>
#include <bcmutils.h>
#include <bcmcdc.h>
#include <bcmendian.h>
#include <dngl_stats.h>
#include <dhd.h>
#include <dhd_proto.h>
#include <dhd_bus.h>
#include <dhd_dbg.h>
#ifdef CONFIG_CONTROL_PM
bool g_PMcontrol = FALSE;
#endif
extern int dhd_preinit_ioctls(dhd_pub_t *dhd);
/* Packet alignment for most efficient SDIO (can change based on platform) */
#ifndef DHD_SDALIGN
#define DHD_SDALIGN 32
#endif
#if !ISPOWEROF2(DHD_SDALIGN)
#error DHD_SDALIGN is not a power of 2!
#endif
#define RETRIES 2 /* # of retries to retrieve matching ioctl response */
#define BUS_HEADER_LEN (16+DHD_SDALIGN) /* Must be atleast SDPCM_RESERVE
* defined in dhd_sdio.c (amount of header tha might be added)
* plus any space that might be needed for alignment padding.
*/
#define ROUND_UP_MARGIN 2048 /* Biggest SDIO block size possible for
* round off at the end of buffer
*/
#define MAX_TRY_CNT 5 //# of retries to disable deepsleep */
typedef struct dhd_prot {
uint16 reqid;
uint8 pending;
uint32 lastcmd;
uint8 bus_header[BUS_HEADER_LEN];
cdc_ioctl_t msg;
unsigned char buf[WLC_IOCTL_MAXLEN + ROUND_UP_MARGIN];
} dhd_prot_t;
static int
dhdcdc_msg(dhd_pub_t *dhd)
{
dhd_prot_t *prot = dhd->prot;
int len = ltoh32(prot->msg.len) + sizeof(cdc_ioctl_t);
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
/* NOTE : cdc->msg.len holds the desired length of the buffer to be
* returned. Only up to CDC_MAX_MSG_SIZE of this buffer area
* is actually sent to the dongle
*/
if (len > CDC_MAX_MSG_SIZE)
len = CDC_MAX_MSG_SIZE;
/* Send request */
return dhd_bus_txctl(dhd->bus, (uchar*)&prot->msg, len);
}
static int
dhdcdc_cmplt(dhd_pub_t *dhd, uint32 id, uint32 len)
{
int ret;
dhd_prot_t *prot = dhd->prot;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
do {
ret = dhd_bus_rxctl(dhd->bus, (uchar*)&prot->msg, len+sizeof(cdc_ioctl_t));
if (ret < 0)
break;
} while (CDC_IOC_ID(ltoh32(prot->msg.flags)) != id);
return ret;
}
int
dhdcdc_query_ioctl(dhd_pub_t *dhd, int ifidx, uint cmd, void *buf, uint len)
{
dhd_prot_t *prot = dhd->prot;
cdc_ioctl_t *msg = &prot->msg;
void *info;
int ret = 0, retries = 0;
uint32 id, flags = 0;
if (DHD_TRACE_ON()) {
if ((cmd == WLC_GET_VAR) || (cmd == WLC_SET_VAR)) {
DHD_TRACE(("%s: cmd %d '%s' len %d\n", __FUNCTION__, cmd, (char *)buf, len));
} else {
DHD_TRACE(("%s: cmd %d len %d\n", __FUNCTION__, cmd, len));
}
}
/* Respond "bcmerror" and "bcmerrorstr" with local cache */
if (cmd == WLC_GET_VAR && buf)
{
if (!strcmp((char *)buf, "bcmerrorstr"))
{
strncpy((char *)buf, bcmerrorstr(dhd->dongle_error), BCME_STRLEN);
goto done;
}
else if (!strcmp((char *)buf, "bcmerror"))
{
*(int *)buf = dhd->dongle_error;
goto done;
}
}
memset(msg, 0, sizeof(cdc_ioctl_t));
msg->cmd = htol32(cmd);
msg->len = htol32(len);
msg->flags = (++prot->reqid << CDCF_IOC_ID_SHIFT);
CDC_SET_IF_IDX(msg, ifidx);
msg->flags = htol32(msg->flags);
if (buf)
memcpy(prot->buf, buf, len);
if ((ret = dhdcdc_msg(dhd)) < 0) {
DHD_ERROR(("dhdcdc_query_ioctl: dhdcdc_msg failed w/status %d\n", ret));
goto done;
}
retry:
/* wait for interrupt and get first fragment */
if ((ret = dhdcdc_cmplt(dhd, prot->reqid, len)) < 0)
goto done;
flags = ltoh32(msg->flags);
id = (flags & CDCF_IOC_ID_MASK) >> CDCF_IOC_ID_SHIFT;
if ((id < prot->reqid) && (++retries < RETRIES))
goto retry;
if (id != prot->reqid) {
DHD_ERROR(("%s: %s: unexpected request id %d (expected %d)\n",
dhd_ifname(dhd, ifidx), __FUNCTION__, id, prot->reqid));
ret = -EINVAL;
goto done;
}
/* Check info buffer */
info = (void*)&msg[1];
/* Copy info buffer */
if (buf)
{
if (ret < (int)len)
len = ret;
memcpy(buf, info, len);
}
/* Check the ERROR flag */
if (flags & CDCF_IOC_ERROR)
{
ret = ltoh32(msg->status);
/* Cache error from dongle */
dhd->dongle_error = ret;
}
done:
return ret;
}
int
dhdcdc_set_ioctl(dhd_pub_t *dhd, int ifidx, uint cmd, void *buf, uint len)
{
dhd_prot_t *prot = dhd->prot;
cdc_ioctl_t *msg = &prot->msg;
int ret = 0;
uint32 flags, id;
if (prot == 0) {
DHD_ERROR(("dhdcdc_set_ioctl: dhd->prot NULL. idx=%d, cmd=0x%x", ifidx, cmd));
goto done;
}
if (DHD_TRACE_ON()) {
if ((cmd == WLC_GET_VAR) || (cmd == WLC_SET_VAR)) {
DHD_TRACE(("%s: cmd %d '%s' len %d\n", __FUNCTION__, cmd, (char *)buf, len));
} else {
DHD_TRACE(("%s: cmd %d len %d\n", __FUNCTION__, cmd, len));
}
}
#ifdef CONFIG_CONTROL_PM
if((g_PMcontrol == TRUE) && (cmd == WLC_SET_PM)) {
printk("SET PM ignore! !!!!!!!!!!!!!!!!!!!!!!! \r\n");
goto done;
}
#endif
memset(msg, 0, sizeof(cdc_ioctl_t));
msg->cmd = htol32(cmd);
msg->len = htol32(len);
msg->flags = (++prot->reqid << CDCF_IOC_ID_SHIFT) | CDCF_IOC_SET;
CDC_SET_IF_IDX(msg, ifidx);
msg->flags |= htol32(msg->flags);
if (buf)
memcpy(prot->buf, buf, len);
if ((ret = dhdcdc_msg(dhd)) < 0)
goto done;
if ((ret = dhdcdc_cmplt(dhd, prot->reqid, len)) < 0)
goto done;
flags = ltoh32(msg->flags);
id = (flags & CDCF_IOC_ID_MASK) >> CDCF_IOC_ID_SHIFT;
if (id != prot->reqid) {
DHD_ERROR(("%s: %s: unexpected request id %d (expected %d)\n",
dhd_ifname(dhd, ifidx), __FUNCTION__, id, prot->reqid));
ret = -EINVAL;
goto done;
}
/* Check the ERROR flag */
if (flags & CDCF_IOC_ERROR)
{
ret = ltoh32(msg->status);
/* Cache error from dongle */
dhd->dongle_error = ret;
}
done:
return ret;
}
extern int dhd_bus_interface(struct dhd_bus *bus, uint arg, void* arg2);
int
dhd_prot_ioctl(dhd_pub_t *dhd, int ifidx, wl_ioctl_t * ioc, void * buf, int len)
{
dhd_prot_t *prot = dhd->prot;
int ret = -1;
if (dhd->busstate == DHD_BUS_DOWN) {
DHD_ERROR(("%s : bus is down. we have nothing to do\n", __FUNCTION__));
return ret;
}
dhd_os_proto_block(dhd);
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
ASSERT(len <= WLC_IOCTL_MAXLEN);
if (len > WLC_IOCTL_MAXLEN)
goto done;
if (prot->pending == TRUE) {
DHD_TRACE(("CDC packet is pending!!!! cmd=0x%x (%lu) lastcmd=0x%x (%lu)\n",
ioc->cmd, (unsigned long)ioc->cmd, prot->lastcmd,
(unsigned long)prot->lastcmd));
if ((ioc->cmd == WLC_SET_VAR) || (ioc->cmd == WLC_GET_VAR)) {
DHD_TRACE(("iovar cmd=%s\n", (char*)buf));
}
goto done;
}
prot->pending = TRUE;
prot->lastcmd = ioc->cmd;
if (ioc->set)
ret = dhdcdc_set_ioctl(dhd, ifidx, ioc->cmd, buf, len);
else {
ret = dhdcdc_query_ioctl(dhd, ifidx, ioc->cmd, buf, len);
if (ret > 0)
ioc->used = ret - sizeof(cdc_ioctl_t);
}
/* Too many programs assume ioctl() returns 0 on success */
if (ret >= 0)
ret = 0;
else {
cdc_ioctl_t *msg = &prot->msg;
ioc->needed = ltoh32(msg->len); /* len == needed when set/query fails from dongle */
}
/* Intercept the wme_dp ioctl here */
if ((!ret) && (ioc->cmd == WLC_SET_VAR) && (!strcmp(buf, "wme_dp"))) {
int slen, val = 0;
slen = strlen("wme_dp") + 1;
if (len >= (int)(slen + sizeof(int)))
bcopy(((char *)buf + slen), &val, sizeof(int));
dhd->wme_dp = (uint8) ltoh32(val);
}
prot->pending = FALSE;
done:
dhd_os_proto_unblock(dhd);
return ret;
}
int
dhd_prot_iovar_op(dhd_pub_t *dhdp, const char *name,
void *params, int plen, void *arg, int len, bool set)
{
return BCME_UNSUPPORTED;
}
void
dhd_prot_dump(dhd_pub_t *dhdp, struct bcmstrbuf *strbuf)
{
bcm_bprintf(strbuf, "Protocol CDC: reqid %d\n", dhdp->prot->reqid);
}
void
dhd_prot_hdrpush(dhd_pub_t *dhd, int ifidx, void *pktbuf)
{
#ifdef BDC
struct bdc_header *h;
#endif /* BDC */
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
#ifdef BDC
/* Push BDC header used to convey priority for buses that don't */
PKTPUSH(dhd->osh, pktbuf, BDC_HEADER_LEN);
h = (struct bdc_header *)PKTDATA(dhd->osh, pktbuf);
h->flags = (BDC_PROTO_VER << BDC_FLAG_VER_SHIFT);
if (PKTSUMNEEDED(pktbuf))
h->flags |= BDC_FLAG_SUM_NEEDED;
h->priority = (PKTPRIO(pktbuf) & BDC_PRIORITY_MASK);
h->flags2 = 0;
h->rssi = 0;
#endif /* BDC */
BDC_SET_IF_IDX(h, ifidx);
}
bool
dhd_proto_fcinfo(dhd_pub_t *dhd, void *pktbuf, uint8 *fcbits)
{
#ifdef BDC
struct bdc_header *h;
if (PKTLEN(dhd->osh, pktbuf) < BDC_HEADER_LEN) {
DHD_ERROR(("%s: rx data too short (%d < %d)\n",
__FUNCTION__, PKTLEN(dhd->osh, pktbuf), BDC_HEADER_LEN));
return BCME_ERROR;
}
h = (struct bdc_header *)PKTDATA(dhd->osh, pktbuf);
*fcbits = h->priority >> BDC_PRIORITY_FC_SHIFT;
if ((h->flags2 & BDC_FLAG2_FC_FLAG) == BDC_FLAG2_FC_FLAG)
return TRUE;
#endif
return FALSE;
}
int
dhd_prot_hdrpull(dhd_pub_t *dhd, int *ifidx, void *pktbuf)
{
#ifdef BDC
struct bdc_header *h;
#endif
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
#ifdef BDC
/* Pop BDC header used to convey priority for buses that don't */
if (PKTLEN(dhd->osh, pktbuf) < BDC_HEADER_LEN) {
DHD_ERROR(("%s: rx data too short (%d < %d)\n", __FUNCTION__,
PKTLEN(dhd->osh, pktbuf), BDC_HEADER_LEN));
return BCME_ERROR;
}
h = (struct bdc_header *)PKTDATA(dhd->osh, pktbuf);
if ((*ifidx = BDC_GET_IF_IDX(h)) >= DHD_MAX_IFS) {
DHD_ERROR(("%s: rx data ifnum out of range (%d)\n",
__FUNCTION__, *ifidx));
return BCME_ERROR;
}
if (((h->flags & BDC_FLAG_VER_MASK) >> BDC_FLAG_VER_SHIFT) != BDC_PROTO_VER) {
DHD_ERROR(("%s: non-BDC packet received, flags 0x%x\n",
dhd_ifname(dhd, *ifidx), h->flags));
return BCME_ERROR;
}
if (h->flags & BDC_FLAG_SUM_GOOD) {
DHD_INFO(("%s: BDC packet received with good rx-csum, flags 0x%x\n",
dhd_ifname(dhd, *ifidx), h->flags));
PKTSETSUMGOOD(pktbuf, TRUE);
}
PKTSETPRIO(pktbuf, (h->priority & BDC_PRIORITY_MASK));
PKTPULL(dhd->osh, pktbuf, BDC_HEADER_LEN);
#endif /* BDC */
return 0;
}
int
dhd_prot_attach(dhd_pub_t *dhd)
{
dhd_prot_t *cdc;
#ifndef DHD_USE_STATIC_BUF
if (!(cdc = (dhd_prot_t *)MALLOC(dhd->osh, sizeof(dhd_prot_t)))) {
DHD_ERROR(("%s: kmalloc failed\n", __FUNCTION__));
goto fail;
}
#else
if (!(cdc = (dhd_prot_t *)dhd_os_prealloc(DHD_PREALLOC_PROT, sizeof(dhd_prot_t)))) {
DHD_ERROR(("%s: kmalloc failed\n", __FUNCTION__));
goto fail;
}
#endif /* DHD_USE_STATIC_BUF */
memset(cdc, 0, sizeof(dhd_prot_t));
/* ensure that the msg buf directly follows the cdc msg struct */
if ((uintptr)(&cdc->msg + 1) != (uintptr)cdc->buf) {
DHD_ERROR(("dhd_prot_t is not correctly defined\n"));
goto fail;
}
dhd->prot = cdc;
#ifdef BDC
dhd->hdrlen += BDC_HEADER_LEN;
#endif
dhd->maxctl = WLC_IOCTL_MAXLEN + sizeof(cdc_ioctl_t) + ROUND_UP_MARGIN;
return 0;
fail:
#ifndef DHD_USE_STATIC_BUF
if (cdc != NULL)
MFREE(dhd->osh, cdc, sizeof(dhd_prot_t));
#endif
return BCME_NOMEM;
}
/* ~NOTE~ What if another thread is waiting on the semaphore? Holding it? */
void
dhd_prot_detach(dhd_pub_t *dhd)
{
#ifndef DHD_USE_STATIC_BUF
MFREE(dhd->osh, dhd->prot, sizeof(dhd_prot_t));
#endif
dhd->prot = NULL;
}
void
dhd_prot_dstats(dhd_pub_t *dhd)
{
/* No stats from dongle added yet, copy bus stats */
dhd->dstats.tx_packets = dhd->tx_packets;
dhd->dstats.tx_errors = dhd->tx_errors;
dhd->dstats.rx_packets = dhd->rx_packets;
dhd->dstats.rx_errors = dhd->rx_errors;
dhd->dstats.rx_dropped = dhd->rx_dropped;
dhd->dstats.multicast = dhd->rx_multicast;
return;
}
int
dhd_prot_init(dhd_pub_t *dhd)
{
int ret = 0;
char buf[128];
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
dhd_os_proto_block(dhd);
/* Get the device MAC address */
strcpy(buf, "cur_etheraddr");
ret = dhdcdc_query_ioctl(dhd, 0, WLC_GET_VAR, buf, sizeof(buf));
if (ret < 0) {
dhd_os_proto_unblock(dhd);
return ret;
}
memcpy(dhd->mac.octet, buf, ETHER_ADDR_LEN);
dhd_os_proto_unblock(dhd);
#ifdef EMBEDDED_PLATFORM
ret = dhd_preinit_ioctls(dhd);
#endif /* EMBEDDED_PLATFORM */
/* Always assumes wl for now */
dhd->iswl = TRUE;
return ret;
}
void
dhd_prot_stop(dhd_pub_t *dhd)
{
/* Nothing to do for CDC */
}
dhd_pub_t *dhd_get_pub(struct net_device *dev); /* dhd_linux.c */
extern void dhd_os_deepsleep_block(void); /* dhd_linux.c */
extern void dhd_os_deepsleep_unblock(void); /* dhd_linux.c */
extern void dhd_os_deepsleep_wait(void); /* dhd_linux.c */
int dhd_deepsleep(struct net_device *dev, int flag)
{
char iovbuf[20];
uint powervar = 0;
dhd_pub_t *dhdp = dhd_get_pub(dev);
int cnt = 0;
int ret = 0;
switch (flag) {
case 1 : /* Deepsleep on */
dhd_os_deepsleep_wait();
DHD_ERROR(("[WiFi] Deepsleep On\n"));
/* Disable MPC */
powervar = 0;
bcm_mkiovar("mpc", (char *)&powervar, 4, iovbuf, sizeof(iovbuf));
dhdcdc_set_ioctl(dhdp, 0, WLC_SET_VAR, iovbuf, sizeof(iovbuf));
/* Enable Deepsleep*/
powervar = 1;
bcm_mkiovar("deepsleep", (char *)&powervar, 4, iovbuf, sizeof(iovbuf));
dhdcdc_set_ioctl(dhdp, 0, WLC_SET_VAR, iovbuf, sizeof(iovbuf));
break;
case 0: /* Deepsleep Off */
dhd_os_deepsleep_block();
DHD_ERROR(("[WiFi] Deepsleep Off\n"));
/* Disable Deepsleep */
for( cnt = 0 ; cnt < MAX_TRY_CNT ; cnt++ ) {
powervar = 0;
bcm_mkiovar("deepsleep", (char *)&powervar, 4, iovbuf, sizeof(iovbuf));
dhdcdc_set_ioctl(dhdp, 0, WLC_SET_VAR, iovbuf, sizeof(iovbuf));
memset(iovbuf,0,sizeof(iovbuf));
strcpy(iovbuf, "deepsleep");
if ((ret = dhdcdc_query_ioctl(dhdp, 0, WLC_GET_VAR, iovbuf, sizeof(iovbuf))) < 0 ) {
DHD_ERROR(("the error of dhd deepsleep status ret value : %d\n",ret));
}else {
if(!(*(int *)iovbuf )) {
DHD_ERROR(("deepsleep mode is 0, ok , count : %d\n",cnt));
break;
}
}
}
/* Enable MPC */
powervar = 1;
memset(iovbuf,0,sizeof(iovbuf));
bcm_mkiovar("mpc", (char *)&powervar, 4, iovbuf, sizeof(iovbuf));
dhdcdc_set_ioctl(dhdp, 0, WLC_SET_VAR, iovbuf, sizeof(iovbuf));
dhd_os_deepsleep_unblock();
break;
}
return 0;
}
| shianyow/kernel-android-skyrocket | drivers/net/wireless/bcm4329/src/dhd/sys/dhd_cdc.c | C | gpl-2.0 | 15,180 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef CREATE_DRASCULA_H
#define CREATE_DRASCULA_H
#define ARRAYSIZE(x) ((int)(sizeof(x) / sizeof(x[0])))
#define DATAALIGNMENT 4
#define NUM_LANGS 6
#define NUM_TEXT 501
#define NUM_TEXTD 84
#define NUM_TEXTB 15
#define NUM_TEXTBJ 29
#define NUM_TEXTE 24
#define NUM_TEXTI 33
#define NUM_TEXTL 32
#define NUM_TEXTP 20
#define NUM_TEXTT 25
#define NUM_TEXTVB 63
#define NUM_TEXTSYS 4
#define NUM_TEXTHIS 5
#define NUM_TEXTVERBS 6
#define NUM_TEXTMISC 7
#define NUM_TEXTD1 11
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef signed short int16;
enum Verbs {
kVerbDefault = -1,
kVerbLook = 1,
kVerbPick = 2,
kVerbOpen = 3,
kVerbClose = 4,
kVerbTalk = 5,
kVerbMove = 6
};
struct RoomTalkAction {
int room;
int chapter;
int action;
int objectID;
int speechID;
};
struct ItemLocation {
int x;
int y;
};
struct CharInfo {
char inChar;
uint16 mappedChar;
char charType; // 0 - letters, 1 - signs, 2 - accented
};
struct RoomUpdate {
int roomNum;
int flag;
int flagValue;
int sourceX;
int sourceY;
int destX;
int destY;
int width;
int height;
int type; // 0 - background, 1 - rect
};
enum TalkSequenceCommands {
kPause = 0,
kSetFlag = 1,
kClearFlag = 2,
kPickObject = 3,
kAddObject = 4,
kBreakOut = 5,
kConverse = 6,
kPlaceVB = 7,
kUpdateRoom = 8,
kUpdateScreen = 9,
kTrackProtagonist = 10,
kPlaySound = 11,
kFinishSound = 12,
kTalkerGeneral = 13,
kTalkerDrunk = 14,
kTalkerPianist = 15,
kTalkerBJ = 16,
kTalkerVBNormal = 17,
kTalkerVBDoor = 18,
kTalkerIgorSeated = 19,
kTalkerWerewolf = 20,
kTalkerMus = 21,
kTalkerDrascula = 22,
kTalkerBartender0 = 23,
kTalkerBartender1 = 24
};
struct TalkSequenceCommand {
int chapter;
int sequence;
int commandType;
int action;
};
#endif /* CREATE_DRASCULA_H */
| alexbevi/scummvm | devtools/create_drascula/create_drascula.h | C | gpl-2.0 | 2,731 |
<?php
/**
* @package Joomla.UnitTest
* @subpackage Crypt
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
/**
* Test class for JCryptCipherBlowfish.
*
* @package Joomla.UnitTest
* @subpackage Crypt
* @since 12.1
*/
class JCryptCipherBlowfishTest extends TestCase
{
/**
* @var JCryptCipherBlowfish
* @since 12.1
*/
private $_cipher;
/**
* Prepares the environment before running a test.
*
* @return void
*
* @since 12.1
*/
protected function setUp()
{
parent::setUp();
// Only run the test if mcrypt is loaded.
if (!extension_loaded('mcrypt'))
{
$this->markTestSkipped('The mcrypt extension must be available for this test to run.');
}
$this->_cipher = new JCryptCipherBlowfish;
// Build the key for testing.
$this->key = new JCryptKey('blowfish');
$this->key->private = file_get_contents(__DIR__ . '/stubs/encrypted/blowfish/key.priv');
$this->key->public = file_get_contents(__DIR__ . '/stubs/encrypted/blowfish/key.pub');
}
/**
* Cleans up the environment after running a test.
*
* @return void
*
* @since 12.1
*/
protected function tearDown()
{
$this->_cipher = null;
parent::tearDown();
}
/**
* Test...
*
* @return array
*/
public function data()
{
return array(
array(
'1.txt',
'c-;3-(Is>{DJzOHMCv_<#yKuN/G`/Us{GkgicWG$M|HW;kI0BVZ^|FY/"Obt53?PNaWwhmRtH;lWkWE4vlG5CIFA!abu&F=Xo#Qw}gAp3;GL\'k])%D}C+W&ne6_F$3P5'),
array(
'2.txt',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ' .
'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor ' .
'in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt ' .
'in culpa qui officia deserunt mollit anim id est laborum.'),
array('3.txt', 'لا أحد يحب الألم بذاته، يسعى ورائه أو يبتغيه، ببساطة لأنه الألم...'),
array('4.txt',
'Широкая электрификация южных губерний даст мощный ' .
'толчок подъёму сельского хозяйства'),
array('5.txt', 'The quick brown fox jumps over the lazy dog.')
);
}
/**
* Tests JCryptCipherBlowfish->decrypt()
*
* @param string $file @todo
* @param string $data @todo
*
* @return void
*
* @dataProvider data
* @since 12.1
*/
public function testDecrypt($file, $data)
{
$encrypted = file_get_contents(__DIR__ . '/stubs/encrypted/blowfish/' . $file);
$decrypted = $this->_cipher->decrypt($encrypted, $this->key);
// Assert that the decrypted values are the same as the expected ones.
$this->assertEquals($data, $decrypted);
}
/**
* Tests JCryptCipherBlowfish->encrypt()
*
* @param string $file @todo
* @param string $data @todo
*
* @return void
*
* @dataProvider data
* @since 12.1
*/
public function testEncrypt($file, $data)
{
$encrypted = $this->_cipher->encrypt($data, $this->key);
// Assert that the encrypted value is not the same as the clear text value.
$this->assertNotEquals($data, $encrypted);
// Assert that the encrypted values are the same as the expected ones.
$this->assertStringEqualsFile(__DIR__ . '/stubs/encrypted/blowfish/' . $file, $encrypted);
}
/**
* Tests JCryptCipherBlowfish->generateKey()
*
* @return void
*
* @since 12.1
*/
public function testGenerateKey()
{
$key = $this->_cipher->generateKey(array('password' => 'J00ml@R0cks!'));
// Assert that the key is the correct type.
$this->assertInstanceOf('JCryptKey', $key);
// Assert that the private key is 56 bytes long.
$this->assertEquals(56, strlen($key->private));
// Assert the key is of the correct type.
$this->assertAttributeEquals('blowfish', 'type', $key);
}
}
| n2h/joomla-spark | tests/unit/suites/libraries/joomla/crypt/cipher/JCryptCipherBlowfishTest.php | PHP | gpl-2.0 | 4,102 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/supervised_user_manager_impl.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/managed/locally_managed_user_constants.h"
#include "chrome/browser/chromeos/login/user_manager_impl.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/managed_mode/managed_user_service.h"
#include "chrome/browser/managed_mode/managed_user_service_factory.h"
#include "chromeos/settings/cros_settings_names.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/gaia/gaia_auth_util.h"
using content::BrowserThread;
namespace {
// A map from locally managed user local user id to sync user id.
const char kManagedUserSyncId[] =
"ManagedUserSyncId";
// A map from locally managed user id to manager user id.
const char kManagedUserManagers[] =
"ManagedUserManagers";
// A map from locally managed user id to manager display name.
const char kManagedUserManagerNames[] =
"ManagedUserManagerNames";
// A map from locally managed user id to manager display e-mail.
const char kManagedUserManagerDisplayEmails[] =
"ManagedUserManagerDisplayEmails";
// A vector pref of the locally managed accounts defined on this device, that
// had not logged in yet.
const char kLocallyManagedUsersFirstRun[] = "LocallyManagedUsersFirstRun";
// A pref of the next id for locally managed users generation.
const char kLocallyManagedUsersNextId[] =
"LocallyManagedUsersNextId";
// A pref of the next id for locally managed users generation.
const char kLocallyManagedUserCreationTransactionDisplayName[] =
"LocallyManagedUserCreationTransactionDisplayName";
// A pref of the next id for locally managed users generation.
const char kLocallyManagedUserCreationTransactionUserId[] =
"LocallyManagedUserCreationTransactionUserId";
std::string LoadSyncToken(base::FilePath profile_dir) {
std::string token;
base::FilePath token_file =
profile_dir.Append(chromeos::kManagedUserTokenFilename);
VLOG(1) << "Loading" << token_file.value();
if (!base::ReadFileToString(token_file, &token))
return std::string();
return token;
}
} // namespace
namespace chromeos {
// static
void SupervisedUserManager::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterListPref(kLocallyManagedUsersFirstRun);
registry->RegisterIntegerPref(kLocallyManagedUsersNextId, 0);
registry->RegisterStringPref(
kLocallyManagedUserCreationTransactionDisplayName, "");
registry->RegisterStringPref(
kLocallyManagedUserCreationTransactionUserId, "");
registry->RegisterDictionaryPref(kManagedUserSyncId);
registry->RegisterDictionaryPref(kManagedUserManagers);
registry->RegisterDictionaryPref(kManagedUserManagerNames);
registry->RegisterDictionaryPref(kManagedUserManagerDisplayEmails);
}
SupervisedUserManagerImpl::SupervisedUserManagerImpl(UserManagerImpl* owner)
: owner_(owner),
cros_settings_(CrosSettings::Get()) {
// SupervisedUserManager instance should be used only on UI thread.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
SupervisedUserManagerImpl::~SupervisedUserManagerImpl() {
}
std::string SupervisedUserManagerImpl::GenerateUserId() {
int counter = g_browser_process->local_state()->
GetInteger(kLocallyManagedUsersNextId);
std::string id;
bool user_exists;
do {
id = base::StringPrintf("%d@%s", counter,
UserManager::kLocallyManagedUserDomain);
counter++;
user_exists = (NULL != owner_->FindUser(id));
DCHECK(!user_exists);
if (user_exists) {
LOG(ERROR) << "Supervised user with id " << id << " already exists.";
}
} while (user_exists);
g_browser_process->local_state()->
SetInteger(kLocallyManagedUsersNextId, counter);
g_browser_process->local_state()->CommitPendingWrite();
return id;
}
const User* SupervisedUserManagerImpl::CreateUserRecord(
const std::string& manager_id,
const std::string& local_user_id,
const std::string& sync_user_id,
const base::string16& display_name) {
const User* user = FindByDisplayName(display_name);
DCHECK(!user);
if (user)
return user;
const User* manager = owner_->FindUser(manager_id);
CHECK(manager);
PrefService* local_state = g_browser_process->local_state();
User* new_user = User::CreateLocallyManagedUser(local_user_id);
owner_->AddUserRecord(new_user);
ListPrefUpdate prefs_new_users_update(local_state,
kLocallyManagedUsersFirstRun);
DictionaryPrefUpdate sync_id_update(local_state, kManagedUserSyncId);
DictionaryPrefUpdate manager_update(local_state, kManagedUserManagers);
DictionaryPrefUpdate manager_name_update(local_state,
kManagedUserManagerNames);
DictionaryPrefUpdate manager_email_update(local_state,
kManagedUserManagerDisplayEmails);
prefs_new_users_update->Insert(0, new base::StringValue(local_user_id));
sync_id_update->SetWithoutPathExpansion(local_user_id,
new base::StringValue(sync_user_id));
manager_update->SetWithoutPathExpansion(local_user_id,
new base::StringValue(manager->email()));
manager_name_update->SetWithoutPathExpansion(local_user_id,
new base::StringValue(manager->GetDisplayName()));
manager_email_update->SetWithoutPathExpansion(local_user_id,
new base::StringValue(manager->display_email()));
owner_->SaveUserDisplayName(local_user_id, display_name);
g_browser_process->local_state()->CommitPendingWrite();
return new_user;
}
std::string SupervisedUserManagerImpl::GetUserSyncId(const std::string& user_id)
const {
PrefService* local_state = g_browser_process->local_state();
const DictionaryValue* sync_ids =
local_state->GetDictionary(kManagedUserSyncId);
std::string result;
sync_ids->GetStringWithoutPathExpansion(user_id, &result);
return result;
}
base::string16 SupervisedUserManagerImpl::GetManagerDisplayName(
const std::string& user_id) const {
PrefService* local_state = g_browser_process->local_state();
const DictionaryValue* manager_names =
local_state->GetDictionary(kManagedUserManagerNames);
base::string16 result;
if (manager_names->GetStringWithoutPathExpansion(user_id, &result) &&
!result.empty())
return result;
return UTF8ToUTF16(GetManagerDisplayEmail(user_id));
}
std::string SupervisedUserManagerImpl::GetManagerUserId(
const std::string& user_id) const {
PrefService* local_state = g_browser_process->local_state();
const DictionaryValue* manager_ids =
local_state->GetDictionary(kManagedUserManagers);
std::string result;
manager_ids->GetStringWithoutPathExpansion(user_id, &result);
return result;
}
std::string SupervisedUserManagerImpl::GetManagerDisplayEmail(
const std::string& user_id) const {
PrefService* local_state = g_browser_process->local_state();
const DictionaryValue* manager_mails =
local_state->GetDictionary(kManagedUserManagerDisplayEmails);
std::string result;
if (manager_mails->GetStringWithoutPathExpansion(user_id, &result) &&
!result.empty()) {
return result;
}
return GetManagerUserId(user_id);
}
const User* SupervisedUserManagerImpl::FindByDisplayName(
const base::string16& display_name) const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const UserList& users = owner_->GetUsers();
for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
if (((*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) &&
((*it)->display_name() == display_name)) {
return *it;
}
}
return NULL;
}
const User* SupervisedUserManagerImpl::FindBySyncId(
const std::string& sync_id) const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
const UserList& users = owner_->GetUsers();
for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
if (((*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) &&
(GetUserSyncId((*it)->email()) == sync_id)) {
return *it;
}
}
return NULL;
}
void SupervisedUserManagerImpl::StartCreationTransaction(
const base::string16& display_name) {
g_browser_process->local_state()->
SetString(kLocallyManagedUserCreationTransactionDisplayName,
UTF16ToASCII(display_name));
g_browser_process->local_state()->CommitPendingWrite();
}
void SupervisedUserManagerImpl::SetCreationTransactionUserId(
const std::string& email) {
g_browser_process->local_state()->
SetString(kLocallyManagedUserCreationTransactionUserId,
email);
g_browser_process->local_state()->CommitPendingWrite();
}
void SupervisedUserManagerImpl::CommitCreationTransaction() {
g_browser_process->local_state()->
ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
g_browser_process->local_state()->
ClearPref(kLocallyManagedUserCreationTransactionUserId);
g_browser_process->local_state()->CommitPendingWrite();
}
bool SupervisedUserManagerImpl::HasFailedUserCreationTransaction() {
return !(g_browser_process->local_state()->
GetString(kLocallyManagedUserCreationTransactionDisplayName).
empty());
}
void SupervisedUserManagerImpl::RollbackUserCreationTransaction() {
PrefService* prefs = g_browser_process->local_state();
std::string display_name = prefs->
GetString(kLocallyManagedUserCreationTransactionDisplayName);
std::string user_id = prefs->
GetString(kLocallyManagedUserCreationTransactionUserId);
LOG(WARNING) << "Cleaning up transaction for "
<< display_name << "/" << user_id;
if (user_id.empty()) {
// Not much to do - just remove transaction.
prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
prefs->CommitPendingWrite();
return;
}
if (gaia::ExtractDomainName(user_id) !=
UserManager::kLocallyManagedUserDomain) {
LOG(WARNING) << "Clean up transaction for non-locally managed user found :"
<< user_id << ", will not remove data";
prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
prefs->ClearPref(kLocallyManagedUserCreationTransactionUserId);
prefs->CommitPendingWrite();
return;
}
owner_->RemoveNonOwnerUserInternal(user_id, NULL);
prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
prefs->ClearPref(kLocallyManagedUserCreationTransactionUserId);
prefs->CommitPendingWrite();
}
void SupervisedUserManagerImpl::RemoveNonCryptohomeData(
const std::string& user_id) {
PrefService* prefs = g_browser_process->local_state();
ListPrefUpdate prefs_new_users_update(prefs, kLocallyManagedUsersFirstRun);
prefs_new_users_update->Remove(base::StringValue(user_id), NULL);
DictionaryPrefUpdate synd_id_update(prefs, kManagedUserSyncId);
synd_id_update->RemoveWithoutPathExpansion(user_id, NULL);
DictionaryPrefUpdate managers_update(prefs, kManagedUserManagers);
managers_update->RemoveWithoutPathExpansion(user_id, NULL);
DictionaryPrefUpdate manager_names_update(prefs,
kManagedUserManagerNames);
manager_names_update->RemoveWithoutPathExpansion(user_id, NULL);
DictionaryPrefUpdate manager_emails_update(prefs,
kManagedUserManagerDisplayEmails);
manager_emails_update->RemoveWithoutPathExpansion(user_id, NULL);
}
bool SupervisedUserManagerImpl::CheckForFirstRun(const std::string& user_id) {
ListPrefUpdate prefs_new_users_update(g_browser_process->local_state(),
kLocallyManagedUsersFirstRun);
return prefs_new_users_update->Remove(base::StringValue(user_id), NULL);
}
void SupervisedUserManagerImpl::UpdateManagerName(const std::string& manager_id,
const base::string16& new_display_name) {
PrefService* local_state = g_browser_process->local_state();
const DictionaryValue* manager_ids =
local_state->GetDictionary(kManagedUserManagers);
DictionaryPrefUpdate manager_name_update(local_state,
kManagedUserManagerNames);
for (DictionaryValue::Iterator it(*manager_ids); !it.IsAtEnd();
it.Advance()) {
std::string user_id;
bool has_manager_id = it.value().GetAsString(&user_id);
DCHECK(has_manager_id);
if (user_id == manager_id) {
manager_name_update->SetWithoutPathExpansion(
it.key(),
new base::StringValue(new_display_name));
}
}
}
void SupervisedUserManagerImpl::LoadSupervisedUserToken(
Profile* profile,
const LoadTokenCallback& callback) {
// TODO(antrim): use profile->GetPath() once we sure it is safe.
base::FilePath profile_dir = ProfileHelper::GetProfilePathByUserIdHash(
UserManager::Get()->GetUserByProfile(profile)->username_hash());
PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&LoadSyncToken, profile_dir),
callback);
}
void SupervisedUserManagerImpl::ConfigureSyncWithToken(
Profile* profile,
const std::string& token) {
if (!token.empty())
ManagedUserServiceFactory::GetForProfile(profile)->InitSync(token);
}
} // namespace chromeos
| qtekfun/htcDesire820Kernel | external/chromium_org/chrome/browser/chromeos/login/supervised_user_manager_impl.cc | C++ | gpl-2.0 | 13,875 |
-----------------------------------
-- Area: Pashhow Marshlands
-- MOB: Marsh Funguar
-----------------------------------
require("scripts/globals/fieldsofvalor");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
checkRegime(player,mob,24,1);
checkRegime(player,mob,60,2);
end;
| UnknownX7/darkstar | scripts/zones/Pashhow_Marshlands/mobs/Marsh_Funguar.lua | Lua | gpl-3.0 | 370 |
#ifndef ETAS_BOA_H
#define ETAS_BOA_H
/**
* @file boa.h
* @brief Doxygen-Documentation of Basic OpenAPI.
* @copyright Copyright (c) 2008 ETAS GmbH. All rights reserved.
*
* $Revision: 5976 $
*
*
* @mainpage Basic OpenAPI Overview
* <HR>
* @htmlinclude "page_boa_overview.html"
*
* @page PAGE_BOA_ERROR_MANAGEMENT BOA - Error Management
* @htmlinclude "page_boa_error_management.html"
*
* @page PAGE_BOA_TIMER_MANAGEMENT BOA - Timer Management
* @htmlinclude "page_boa_time_management.html"
*
* @page PAGE_BOA_EXTENSIONS_CAN BOA - CAN Specifics
* @htmlinclude "page_boa_extensions_CAN.html"
*
* @page PAGE_BOA_EXTENSIONS_LIN BOA - LIN Specifics
* @htmlinclude "page_boa_extensions_LIN.html"
*
* @page PAGE_BOA_EXTENSIONS_FLEXRAY BOA - FlexRay Specifics
* @htmlinclude "page_boa_extensions_FlexRay.html"
*
* @page PAGE_BOA_MULTITHREADING BOA - Multi-Threading
* @htmlinclude "page_boa_multithreading.html"
*
* @addtogroup GROUP_BOA_COMMON Common (BOA)
* @{
*
* @defgroup GROUP_BOA_GLOBAL_TYPES Global Types
* @ingroup GROUP_BOA_COMMON
*
* @defgroup GROUP_BOA_ERROR_MANAGEMENT Error Management
* @ingroup GROUP_BOA_COMMON
*
* @}
*
*
* @addtogroup GROUP_BOA_OCI Open Controller Interface (OCI)
* @brief The Open Controller Interface (OCI) offers an access to
* the Automotive Bus Systems (CAN, LIN, FlexRay) via ETAS
* systems.\ It is a low level, bus specific interface, that
* allows an access to the bus systems on a frame based
* level.
* @{
*
* @defgroup GROUP_OCI_COMMON OCI Common
* @ingroup GROUP_BOA_OCI
*
* @defgroup GROUP_OCI_CAN_CONTROLLER OCI CAN
* @ingroup GROUP_BOA_OCI
*
* @defgroup GROUP_OCI_LIN_CONTROLLER OCI LIN
* @ingroup GROUP_BOA_OCI
*
* @defgroup GROUP_OCI_FLEXRAY_CONTROLLER OCI FlexRay
* @ingroup GROUP_BOA_OCI
*
* @}
*
*
*
*
*
* @addtogroup GROUP_BOA_CSI Connection Service Interface (CSI)
* @brief The Connection Service Interface (CSI) implements a framework for the different
Basic OpenAPI components.
*
* @{
*
* @defgroup GROUP_CSI_COMMON Enumerate Sub Service (ESS)
* @ingroup GROUP_BOA_CSI
*
* @defgroup GROUP_CSI_COMPONENT Enumerate Component Service (ECS)
* @ingroup GROUP_BOA_CSI
*
* @defgroup GROUP_CSI_SFS Search For Service (SFS)
* @ingroup GROUP_BOA_CSI
*
* @defgroup GROUP_CSI_CTS Connect To Service (CTS)
* @ingroup GROUP_BOA_CSI
*
* @}
*
*/
/**
@page BackwardsCompatibilityPage Backwards compatibility and API versioning
This page discusses BOA's approach to backwards compatibility of OCI APIs.
@section ApiVersioning API versioning
As the OCI APIs evolve, new functionality may be added to an API, or existing functionality may be modified and expanded.
To allow changes to an API to be identified, each OCI API has an associated version number. The version of the original
API is defined as 1.0.0.0, and the version number is incremented as new BOA releases modify the definition of the API.
The documentation for each OCI API notes the changes which have occurred in each version. So, for example, the
documentation for the structure field @ref OCI_LINControllerCapabilities::slaveBaudrateType notes that this field was
introduced in version 1.1 of the OCI_LIN API.
(The version number of an API contains 4 digits, but currently only the first two are used meaningfully).
@section BackwardsCompatibility Backwards compatibility
When a OCI API is modified and a new version is created, it is necessary that the following use cases are correctly
supported:
- An OCD which implements the new API definition may be used by a client which was built to use the old API definition.
Such a client must still get the behaviour which he expects from the OCD.
- A client which was built to use the new API definition may be used with an OCD which implements the old API definition.
The client must still be able to operate, though obviously without using any features which were introduced in the new
API definition.
The BOA framework supports both these use cases via a common mechanism. When a OCI client creates a new session of a
OCI API for a particular URI, the OCI client and the referenced OCD can each discover which versions of that OCI API
are supported by the other.
First, consider how a OCI client can discover the latest API version which is supported by the OCD associated with his
chosen URI (using the example of OCI_CAN):
-# The OCI client begins by choosing the latest version of OIC_CAN of which he is aware, e.g. v1.3. He uses
@ref CSI_CreateInterfaceStack() to try to create an interface stack which requests this API version for his chosen URI.
-# If @ref CSI_CreateInterfaceStack() fails with the error @ref BOA_ERR_PROTOCOL_VERSION_NOT_SUPPORTED the OCI client
concludes that the OCD associated with his chosen URI does not support the latest version of OCI_CAN. The OCI client
then repeatedly calls @ref CSI_CreateInterfaceStack() for older and older versions of OCI_CAN, until he finds a version
of OCI_CAN which succeeds. This is the latest version of OCI_CAN which is supported by the OCD associated with the
client's chosen URI.
-# Now the OCI client can call @ref OCI_CreateCANControllerBind() to create a session of OCI_CAN, using the
successfully-constructed interface stack.
Now consider the OCD's point of view: an OCD can discover the API version requested by a OCI client via the parameter
<tt>protocolStack</tt> which is passed to the OCD's implementation of @ref OCI_CreateCANControllerBind() (again using
OCI_CAN as an example). The field <tt>protocolStack->server.id.api.version</tt> contains the required information.
Once the OCD has discovered the API version requested by the client, the OCD can behave accordingly, either offering
new behaviour if the client requested a newer API version, or offering old behaviour in order to maintain backwards
compatibility with an older client.
There now follow some examples, using the new functionality introduced in v1.1 of OCI_LIN. In this version of OCI_LIN,
the field @ref OCI_LINControllerCapabilities::slaveBaudrateType was added, and zero became a permitted value for the
field @ref OCI_LINConfiguration::baudrate.
@section Example1 Example: client built with OCI_LIN v1.1, using an OCD built with OCI_LIN v1.1
The client begins by using @ref CSI_CreateInterfaceStack() to request an interface stack for OCI_LIN v1.1. This is
successful, so he passes the interface stack to @ref OCI_CreateLINControllerBind() to create an OCI_LIN session.
Because the client successfully requested OCI_LIN v1.1, he knows that the OCD will provide a valid value in the field
@ref OCI_LINControllerCapabilities::slaveBaudrateType when he calls @ref OCI_GetLINControllerCapabilities(), and that
he may be able to use zero as a value for @ref OCI_LINConfiguration::baudrate.
The OCD knows that the client requested OCI_LIN v1.1, so the OCD knows that it can safely populate the field
@ref OCI_LINControllerCapabilities::slaveBaudrateType when the client calls @ref OCI_GetLINControllerCapabilities(),
and that in some circumstances the client may use zero as a value for @ref OCI_LINConfiguration::baudrate.
@section Example2 Example: client built with OCI_LIN v1.0, using an OCD built with OCI_LIN v1.1
The client begins by using @ref CSI_CreateInterfaceStack() to request an interface stack for OCI_LIN v1.0, because the
client knows no newer API version. This is successful, so he passes the interface stack to @ref OCI_CreateLINControllerBind()
to create an OCI_LIN session.
The client is unaware of the new field @ref OCI_LINControllerCapabilities::slaveBaudrateType and will not attempt to
access it when he calls @ref OCI_GetLINControllerCapabilities(). Furthermore, the client will never use zero as a value
for @ref OCI_LINConfiguration::baudrate.
The OCD knows that the client requested OCI_LIN v1.0, so the OCD knows that it should not populate the field
@ref OCI_LINControllerCapabilities::slaveBaudrateType when the client calls @ref OCI_GetLINControllerCapabilities()
(indeed, this field may lie beyond the end of the structure instance provided by the client), and that the client will
never use zero as a value for @ref OCI_LINConfiguration::baudrate.
@section Example3 Example: client built with OCI_LIN v1.1, using an OCD built with OCI_LIN v1.0
The client begins by using @ref CSI_CreateInterfaceStack() to request an interface stack for OCI_LIN v1.1. However, this
is unsuccessful, so he tries again with OCI_LIN v1.0. This works, so he passes the interface stack to
@ref OCI_CreateLINControllerBind() to create an OCI_LIN session.
The client knows that he must not expect the OCD to output a valid value in the field
@ref OCI_LINControllerCapabilities::slaveBaudrateType when he calls @ref OCI_GetLINControllerCapabilities(), since the
OCD knows nothing of this field. Furthermore, the client knows that he must never use the value zero for the field
@ref OCI_LINConfiguration::baudrate, since the OCD will treat this as an error.
The OCD is unaware of the new field @ref OCI_LINControllerCapabilities::slaveBaudrateType and will not attempt to populate
it when the client calls @ref OCI_GetLINControllerCapabilities(). Furthermore, the OCD will never expect the value zero
to be used for @ref OCI_LINConfiguration::baudrate.
@section Conclusion
By enabling the OCI client and the OCD to reach a common understanding of each other's abilities at runtime, the above
mechanism enables future versions of BOA to make complex syntactic and semantic changes to the OCI APIs while still
allowing clients and OCDs to maintain backwards-compatibility with older versions.
However, in order to keep the implementation of clients and OCDs simple, future versions of BOA will restrict the kinds
of changes which may be made to OCI APIs:
- Extra functions may be added to the end of an OCI API's vtable.
- Extra fields may be added to the end of an existing OCI structure.
- Existing fields of an OCI structure may have their semantics modified (e.g. the range of permitted values may be extended
or reduced).
In all cases:
- a client should not use the new functionality unless he has successfully requested an API version which supports it;
- an OCD should not implement the new functionality unless the client requested an API version which supports it.
*/
#endif
| uincore/busmaster | Sources/LIN_ETAS_BOA/EXTERNAL/BOA 1.5/Common/boa.h | C | gpl-3.0 | 10,309 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_AUDIOFORMATWRITER_H_INCLUDED
#define JUCE_AUDIOFORMATWRITER_H_INCLUDED
//==============================================================================
/**
Writes samples to an audio file stream.
A subclass that writes a specific type of audio format will be created by
an AudioFormat object.
After creating one of these with the AudioFormat::createWriterFor() method
you can call its write() method to store the samples, and then delete it.
@see AudioFormat, AudioFormatReader
*/
class JUCE_API AudioFormatWriter
{
protected:
//==============================================================================
/** Creates an AudioFormatWriter object.
@param destStream the stream to write to - this will be deleted
by this object when it is no longer needed
@param formatName the description that will be returned by the getFormatName()
method
@param sampleRate the sample rate to use - the base class just stores
this value, it doesn't do anything with it
@param numberOfChannels the number of channels to write - the base class just stores
this value, it doesn't do anything with it
@param bitsPerSample the bit depth of the stream - the base class just stores
this value, it doesn't do anything with it
*/
AudioFormatWriter (OutputStream* destStream,
const String& formatName,
double sampleRate,
unsigned int numberOfChannels,
unsigned int bitsPerSample);
public:
/** Destructor. */
virtual ~AudioFormatWriter();
//==============================================================================
/** Returns a description of what type of format this is.
E.g. "AIFF file"
*/
const String& getFormatName() const noexcept { return formatName; }
//==============================================================================
/** Writes a set of samples to the audio stream.
Note that if you're trying to write the contents of an AudioSampleBuffer, you
can use AudioSampleBuffer::writeToAudioWriter().
@param samplesToWrite an array of arrays containing the sample data for
each channel to write. This is a zero-terminated
array of arrays, and can contain a different number
of channels than the actual stream uses, and the
writer should do its best to cope with this.
If the format is fixed-point, each channel will be formatted
as an array of signed integers using the full 32-bit
range -0x80000000 to 0x7fffffff, regardless of the source's
bit-depth. If it is a floating-point format, you should treat
the arrays as arrays of floats, and just cast it to an (int**)
to pass it into the method.
@param numSamples the number of samples to write
*/
virtual bool write (const int** samplesToWrite, int numSamples) = 0;
/** Some formats may support a flush operation that makes sure the file is in a
valid state before carrying on.
If supported, this means that by calling flush periodically when writing data
to a large file, then it should still be left in a readable state if your program
crashes.
It goes without saying that this method must be called from the same thread that's
calling write()!
If the format supports flushing and the operation succeeds, this returns true.
*/
virtual bool flush();
//==============================================================================
/** Reads a section of samples from an AudioFormatReader, and writes these to
the output.
This will take care of any floating-point conversion that's required to convert
between the two formats. It won't deal with sample-rate conversion, though.
If numSamplesToRead < 0, it will write the entire length of the reader.
@returns false if it can't read or write properly during the operation
*/
bool writeFromAudioReader (AudioFormatReader& reader,
int64 startSample,
int64 numSamplesToRead);
/** Reads some samples from an AudioSource, and writes these to the output.
The source must already have been initialised with the AudioSource::prepareToPlay() method
@param source the source to read from
@param numSamplesToRead total number of samples to read and write
@param samplesPerBlock the maximum number of samples to fetch from the source
@returns false if it can't read or write properly during the operation
*/
bool writeFromAudioSource (AudioSource& source,
int numSamplesToRead,
int samplesPerBlock = 2048);
/** Writes some samples from an AudioSampleBuffer. */
bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
int startSample, int numSamples);
/** Writes some samples from a set of float data channels. */
bool writeFromFloatArrays (const float* const* channels, int numChannels, int numSamples);
//==============================================================================
/** Returns the sample rate being used. */
double getSampleRate() const noexcept { return sampleRate; }
/** Returns the number of channels being written. */
int getNumChannels() const noexcept { return (int) numChannels; }
/** Returns the bit-depth of the data being written. */
int getBitsPerSample() const noexcept { return (int) bitsPerSample; }
/** Returns true if it's a floating-point format, false if it's fixed-point. */
bool isFloatingPoint() const noexcept { return usesFloatingPointData; }
//==============================================================================
/**
Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
data into a buffer which will be flushed to disk by a background thread.
*/
class ThreadedWriter
{
public:
/** Creates a ThreadedWriter for a given writer and a thread.
The writer object which is passed in here will be owned and deleted by
the ThreadedWriter when it is no longer needed.
To stop the writer and flush the buffer to disk, simply delete this object.
*/
ThreadedWriter (AudioFormatWriter* writer,
TimeSliceThread& backgroundThread,
int numSamplesToBuffer);
/** Destructor. */
~ThreadedWriter();
/** Pushes some incoming audio data into the FIFO.
If there's enough free space in the buffer, this will add the data to it,
If the FIFO is too full to accept this many samples, the method will return
false - then you could either wait until the background thread has had time to
consume some of the buffered data and try again, or you can give up
and lost this block.
The data must be an array containing the same number of channels as the
AudioFormatWriter object is using. None of these channels can be null.
*/
bool write (const float* const* data, int numSamples);
class JUCE_API IncomingDataReceiver
{
public:
IncomingDataReceiver() {}
virtual ~IncomingDataReceiver() {}
virtual void reset (int numChannels, double sampleRate, int64 totalSamplesInSource) = 0;
virtual void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
int startOffsetInBuffer, int numSamples) = 0;
};
/** Allows you to specify a callback that this writer should update with the
incoming data.
The receiver will be cleared and will the writer will begin adding data to
it as the data arrives. Pass a null pointer to remove the current receiver.
The object passed-in must not be deleted while this writer is still using it.
*/
void setDataReceiver (IncomingDataReceiver*);
/** Sets how many samples should be written before calling the AudioFormatWriter::flush method.
Set this to 0 to disable flushing (this is the default).
*/
void setFlushInterval (int numSamplesPerFlush) noexcept;
private:
class Buffer;
friend struct ContainerDeletePolicy<Buffer>;
ScopedPointer<Buffer> buffer;
};
protected:
//==============================================================================
/** The sample rate of the stream. */
double sampleRate;
/** The number of channels being written to the stream. */
unsigned int numChannels;
/** The bit depth of the file. */
unsigned int bitsPerSample;
/** True if it's a floating-point format, false if it's fixed-point. */
bool usesFloatingPointData;
/** The output stream for use by subclasses. */
OutputStream* output;
/** Used by AudioFormatWriter subclasses to copy data to different formats. */
template <class DestSampleType, class SourceSampleType, class DestEndianness>
struct WriteHelper
{
typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
static void write (void* destData, int numDestChannels, const int* const* source,
int numSamples, const int sourceOffset = 0) noexcept
{
for (int i = 0; i < numDestChannels; ++i)
{
const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
if (*source != nullptr)
{
dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
++source;
}
else
{
dest.clearSamples (numSamples);
}
}
}
};
private:
String formatName;
friend class ThreadedWriter;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter)
};
#endif // JUCE_AUDIOFORMATWRITER_H_INCLUDED
| deeuu/LoudnessMeters | src/JuceLibraryCode/modules/juce_audio_formats/format/juce_AudioFormatWriter.h | C | gpl-3.0 | 12,197 |
-----------------------------------
-- Area: The Eldieme Necropolis (S) (175)
-- Mob: Norvallen_Knight
-----------------------------------
-- require("scripts/zones/The_Eldieme_Necropolis_[S]/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
| rpetit3/darkstar | scripts/zones/The_Eldieme_Necropolis_[S]/mobs/Norvallen_Knight.lua | Lua | gpl-3.0 | 843 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Brad Olson <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = '''
---
module: authorized_key
short_description: Adds or removes an SSH authorized key
description:
- "Adds or removes SSH authorized keys for particular user accounts"
version_added: "0.5"
options:
user:
description:
- The username on the remote host whose authorized_keys file will be modified
required: true
key:
description:
- The SSH public key(s), as a string or (since 1.9) url (https://github.com/username.keys)
required: true
path:
description:
- Alternate path to the authorized_keys file
required: false
default: "(homedir)+/.ssh/authorized_keys"
version_added: "1.2"
manage_dir:
description:
- Whether this module should manage the directory of the authorized key file. If
set, the module will create the directory, as well as set the owner and permissions
of an existing directory. Be sure to
set C(manage_dir=no) if you are using an alternate directory for
authorized_keys, as set with C(path), since you could lock yourself out of
SSH access. See the example below.
required: false
choices: [ "yes", "no" ]
default: "yes"
version_added: "1.2"
state:
description:
- Whether the given key (with the given key_options) should or should not be in the file
required: false
choices: [ "present", "absent" ]
default: "present"
key_options:
description:
- A string of ssh key options to be prepended to the key in the authorized_keys file
required: false
default: null
version_added: "1.4"
exclusive:
description:
- Whether to remove all other non-specified keys from the authorized_keys file. Multiple keys
can be specified in a single C(key) string value by separating them by newlines.
- This option is not loop aware, so if you use C(with_) , it will be exclusive per iteration
of the loop, if you want multiple keys in the file you need to pass them all to C(key) in a
single batch as mentioned above.
required: false
choices: [ "yes", "no" ]
default: "no"
version_added: "1.9"
validate_certs:
description:
- This only applies if using a https url as the source of the keys. If set to C(no), the SSL certificates will not be validated.
- This should only set to C(no) used on personally controlled sites using self-signed certificates as it avoids verifying the source site.
- Prior to 2.1 the code worked as if this was set to C(yes).
required: false
default: "yes"
choices: ["yes", "no"]
version_added: "2.1"
comment:
description:
- Change the comment on the public key. Rewriting the comment is useful in
cases such as fetching it from GitHub or GitLab.
- If no comment is specified, the existing comment will be kept.
required: false
default: None
version_added: "2.4"
author: "Ansible Core Team"
'''
EXAMPLES = '''
- name: Set authorized key took from file
authorized_key:
user: charlie
state: present
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
- name: Set authorized key took from url
authorized_key:
user: charlie
state: present
key: https://github.com/charlie.keys
- name: Set authorized key in alternate location
authorized_key:
user: charlie
state: present
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
path: /etc/ssh/authorized_keys/charlie
manage_dir: False
- name: Set up multiple authorized keys
authorized_key:
user: deploy
state: present
key: '{{ item }}'
with_file:
- public_keys/doe-jane
- public_keys/doe-john
- name: Set authorized key defining key options
authorized_key:
user: charlie
state: present
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
key_options: 'no-port-forwarding,from="10.0.1.1"'
- name: Set authorized key without validating the TLS/SSL certificates
authorized_key:
user: charlie
state: present
key: https://github.com/user.keys
validate_certs: False
- name: Set authorized key, removing all the authorized key already set
authorized_key:
user: root
key: '{{ item }}'
state: present
exclusive: True
with_file:
- public_keys/doe-jane
- name: Set authorized key for user ubuntu copying it from current user
authorized_key:
user: ubuntu
state: present
key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"
'''
RETURN = '''
exclusive:
description: If the key has been forced to be exclusive or not.
returned: success
type: boolean
sample: False
key:
description: The key that the module was running against.
returned: success
type: string
sample: https://github.com/user.keys
key_option:
description: Key options related to the key.
returned: success
type: string
sample: null
keyfile:
description: Path for authorized key file.
returned: success
type: string
sample: /home/user/.ssh/authorized_keys
manage_dir:
description: Whether this module managed the directory of the authorized key file.
returned: success
type: boolean
sample: True
path:
description: Alternate path to the authorized_keys file
returned: success
type: string
sample: null
state:
description: Whether the given key (with the given key_options) should or should not be in the file
returned: success
type: string
sample: present
unique:
description: Whether the key is unique
returned: success
type: boolean
sample: false
user:
description: The username on the remote host whose authorized_keys file will be modified
returned: success
type: string
sample: user
validate_certs:
description: This only applies if using a https url as the source of the keys. If set to C(no), the SSL certificates will not be validated.
returned: success
type: boolean
sample: true
'''
# Makes sure the public key line is present or absent in the user's .ssh/authorized_keys.
#
# Arguments
# =========
# user = username
# key = line to add to authorized_keys for user
# path = path to the user's authorized_keys file (default: ~/.ssh/authorized_keys)
# manage_dir = whether to create, and control ownership of the directory (default: true)
# state = absent|present (default: present)
#
# see example in examples/playbooks
import os
import pwd
import os.path
import tempfile
import re
import shlex
from operator import itemgetter
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
class keydict(dict):
""" a dictionary that maintains the order of keys as they are added
This has become an abuse of the dict interface. Probably should be
rewritten to be an entirely custom object with methods instead of
bracket-notation.
Our requirements are for a data structure that:
* Preserves insertion order
* Can store multiple values for a single key.
The present implementation has the following functions used by the rest of
the code:
* __setitem__(): to add a key=value. The value can never be disassociated
with the key, only new values can be added in addition.
* items(): to retrieve the key, value pairs.
Other dict methods should work but may be surprising. For instance, there
will be multiple keys that are the same in keys() and __getitem__() will
return a list of the values that have been set via __setitem__.
"""
# http://stackoverflow.com/questions/2328235/pythonextend-the-dict-class
def __init__(self, *args, **kw):
super(keydict, self).__init__(*args, **kw)
self.itemlist = list(super(keydict, self).keys())
def __setitem__(self, key, value):
self.itemlist.append(key)
if key in self:
self[key].append(value)
else:
super(keydict, self).__setitem__(key, [value])
def __iter__(self):
return iter(self.itemlist)
def keys(self):
return self.itemlist
def _item_generator(self):
indexes = {}
for key in self.itemlist:
if key in indexes:
indexes[key] += 1
else:
indexes[key] = 0
yield key, self[key][indexes[key]]
def iteritems(self):
raise NotImplementedError("Do not use this as it's not available on py3")
def items(self):
return list(self._item_generator())
def itervalues(self):
raise NotImplementedError("Do not use this as it's not available on py3")
def values(self):
return [item[1] for item in self.items()]
def keyfile(module, user, write=False, path=None, manage_dir=True):
"""
Calculate name of authorized keys file, optionally creating the
directories and file, properly setting permissions.
:param str user: name of user in passwd file
:param bool write: if True, write changes to authorized_keys file (creating directories if needed)
:param str path: if not None, use provided path rather than default of '~user/.ssh/authorized_keys'
:param bool manage_dir: if True, create and set ownership of the parent dir of the authorized_keys file
:return: full path string to authorized_keys for user
"""
if module.check_mode and path is not None:
keysfile = path
return keysfile
try:
user_entry = pwd.getpwnam(user)
except KeyError as e:
if module.check_mode and path is None:
module.fail_json(msg="Either user must exist or you must provide full path to key file in check mode")
module.fail_json(msg="Failed to lookup user %s: %s" % (user, to_native(e)))
if path is None:
homedir = user_entry.pw_dir
sshdir = os.path.join(homedir, ".ssh")
keysfile = os.path.join(sshdir, "authorized_keys")
else:
sshdir = os.path.dirname(path)
keysfile = path
if not write:
return keysfile
uid = user_entry.pw_uid
gid = user_entry.pw_gid
if manage_dir:
if not os.path.exists(sshdir):
os.mkdir(sshdir, int('0700', 8))
if module.selinux_enabled():
module.set_default_selinux_context(sshdir, False)
os.chown(sshdir, uid, gid)
os.chmod(sshdir, int('0700', 8))
if not os.path.exists(keysfile):
basedir = os.path.dirname(keysfile)
if not os.path.exists(basedir):
os.makedirs(basedir)
try:
f = open(keysfile, "w") # touches file so we can set ownership and perms
finally:
f.close()
if module.selinux_enabled():
module.set_default_selinux_context(keysfile, False)
try:
os.chown(keysfile, uid, gid)
os.chmod(keysfile, int('0600', 8))
except OSError:
pass
return keysfile
def parseoptions(module, options):
'''
reads a string containing ssh-key options
and returns a dictionary of those options
'''
options_dict = keydict() # ordered dict
if options:
# the following regex will split on commas while
# ignoring those commas that fall within quotes
regex = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''')
parts = regex.split(options)[1:-1]
for part in parts:
if "=" in part:
(key, value) = part.split("=", 1)
options_dict[key] = value
elif part != ",":
options_dict[part] = None
return options_dict
def parsekey(module, raw_key, rank=None):
'''
parses a key, which may or may not contain a list
of ssh-key options at the beginning
rank indicates the keys original ordering, so that
it can be written out in the same order.
'''
VALID_SSH2_KEY_TYPES = [
'ssh-ed25519',
'ecdsa-sha2-nistp256',
'ecdsa-sha2-nistp384',
'ecdsa-sha2-nistp521',
'ssh-dss',
'ssh-rsa',
]
options = None # connection options
key = None # encrypted key string
key_type = None # type of ssh key
type_index = None # index of keytype in key string|list
# remove comment yaml escapes
raw_key = raw_key.replace(r'\#', '#')
# split key safely
lex = shlex.shlex(raw_key)
lex.quotes = []
lex.commenters = '' # keep comment hashes
lex.whitespace_split = True
key_parts = list(lex)
if key_parts and key_parts[0] == '#':
# comment line, invalid line, etc.
return (raw_key, 'skipped', None, None, rank)
for i in range(0, len(key_parts)):
if key_parts[i] in VALID_SSH2_KEY_TYPES:
type_index = i
key_type = key_parts[i]
break
# check for options
if type_index is None:
return None
elif type_index > 0:
options = " ".join(key_parts[:type_index])
# parse the options (if any)
options = parseoptions(module, options)
# get key after the type index
key = key_parts[(type_index + 1)]
# set comment to everything after the key
if len(key_parts) > (type_index + 1):
comment = " ".join(key_parts[(type_index + 2):])
return (key, key_type, options, comment, rank)
def readfile(filename):
if not os.path.isfile(filename):
return ''
f = open(filename)
try:
return f.read()
finally:
f.close()
def parsekeys(module, lines):
keys = {}
for rank_index, line in enumerate(lines.splitlines(True)):
key_data = parsekey(module, line, rank=rank_index)
if key_data:
# use key as identifier
keys[key_data[0]] = key_data
else:
# for an invalid line, just set the line
# dict key to the line so it will be re-output later
keys[line] = (line, 'skipped', None, None, rank_index)
return keys
def writefile(module, filename, content):
fd, tmp_path = tempfile.mkstemp('', 'tmp', os.path.dirname(filename))
f = open(tmp_path, "w")
try:
f.write(content)
except IOError as e:
module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, to_native(e)))
f.close()
module.atomic_move(tmp_path, filename)
def serialize(keys):
lines = []
new_keys = keys.values()
# order the new_keys by their original ordering, via the rank item in the tuple
ordered_new_keys = sorted(new_keys, key=itemgetter(4))
for key in ordered_new_keys:
try:
(keyhash, key_type, options, comment, rank) = key
option_str = ""
if options:
option_strings = []
for option_key, value in options.items():
if value is None:
option_strings.append("%s" % option_key)
else:
option_strings.append("%s=%s" % (option_key, value))
option_str = ",".join(option_strings)
option_str += " "
# comment line or invalid line, just leave it
if not key_type:
key_line = key
if key_type == 'skipped':
key_line = key[0]
else:
key_line = "%s%s %s %s\n" % (option_str, key_type, keyhash, comment)
except Exception:
key_line = key
lines.append(key_line)
return ''.join(lines)
def enforce_state(module, params):
"""
Add or remove key.
"""
user = params["user"]
key = params["key"]
path = params.get("path", None)
manage_dir = params.get("manage_dir", True)
state = params.get("state", "present")
key_options = params.get("key_options", None)
exclusive = params.get("exclusive", False)
comment = params.get("comment", None)
error_msg = "Error getting key from: %s"
# if the key is a url, request it and use it as key source
if key.startswith("http"):
try:
resp, info = fetch_url(module, key)
if info['status'] != 200:
module.fail_json(msg=error_msg % key)
else:
key = resp.read()
except Exception:
module.fail_json(msg=error_msg % key)
# resp.read gives bytes on python3, convert to native string type
key = to_native(key, errors='surrogate_or_strict')
# extract individual keys into an array, skipping blank lines and comments
new_keys = [s for s in key.splitlines() if s and not s.startswith('#')]
# check current state -- just get the filename, don't create file
do_write = False
params["keyfile"] = keyfile(module, user, do_write, path, manage_dir)
existing_content = readfile(params["keyfile"])
existing_keys = parsekeys(module, existing_content)
# Add a place holder for keys that should exist in the state=present and
# exclusive=true case
keys_to_exist = []
# we will order any non exclusive new keys higher than all the existing keys,
# resulting in the new keys being written to the key file after existing keys, but
# in the order of new_keys
max_rank_of_existing_keys = len(existing_keys)
# Check our new keys, if any of them exist we'll continue.
for rank_index, new_key in enumerate(new_keys):
parsed_new_key = parsekey(module, new_key, rank=rank_index)
if not parsed_new_key:
module.fail_json(msg="invalid key specified: %s" % new_key)
if key_options is not None:
parsed_options = parseoptions(module, key_options)
# rank here is the rank in the provided new keys, which may be unrelated to rank in existing_keys
parsed_new_key = (parsed_new_key[0], parsed_new_key[1], parsed_options, parsed_new_key[3], parsed_new_key[4])
if comment is not None:
parsed_new_key = (parsed_new_key[0], parsed_new_key[1], parsed_new_key[2], comment, parsed_new_key[4])
matched = False
non_matching_keys = []
if parsed_new_key[0] in existing_keys:
# Then we check if everything (except the rank at index 4) matches, including
# the key type and options. If not, we append this
# existing key to the non-matching list
# We only want it to match everything when the state
# is present
if parsed_new_key[:4] != existing_keys[parsed_new_key[0]][:4] and state == "present":
non_matching_keys.append(existing_keys[parsed_new_key[0]])
else:
matched = True
# handle idempotent state=present
if state == "present":
keys_to_exist.append(parsed_new_key[0])
if len(non_matching_keys) > 0:
for non_matching_key in non_matching_keys:
if non_matching_key[0] in existing_keys:
del existing_keys[non_matching_key[0]]
do_write = True
# new key that didn't exist before. Where should it go in the ordering?
if not matched:
# We want the new key to be after existing keys if not exclusive (rank > max_rank_of_existing_keys)
total_rank = max_rank_of_existing_keys + parsed_new_key[4]
# replace existing key tuple with new parsed key with its total rank
existing_keys[parsed_new_key[0]] = (parsed_new_key[0], parsed_new_key[1], parsed_new_key[2], parsed_new_key[3], total_rank)
do_write = True
elif state == "absent":
if not matched:
continue
del existing_keys[parsed_new_key[0]]
do_write = True
# remove all other keys to honor exclusive
# for 'exclusive', make sure keys are written in the order the new keys were
if state == "present" and exclusive:
to_remove = frozenset(existing_keys).difference(keys_to_exist)
for key in to_remove:
del existing_keys[key]
do_write = True
if do_write:
filename = keyfile(module, user, do_write, path, manage_dir)
new_content = serialize(existing_keys)
diff = None
if module._diff:
diff = {
'before_header': params['keyfile'],
'after_header': filename,
'before': existing_content,
'after': new_content,
}
params['diff'] = diff
if module.check_mode:
module.exit_json(changed=True, diff=diff)
writefile(module, filename, new_content)
params['changed'] = True
else:
if module.check_mode:
module.exit_json(changed=False)
return params
def main():
module = AnsibleModule(
argument_spec=dict(
user=dict(required=True, type='str'),
key=dict(required=True, type='str'),
path=dict(required=False, type='str'),
manage_dir=dict(required=False, type='bool', default=True),
state=dict(default='present', choices=['absent', 'present']),
key_options=dict(required=False, type='str'),
unique=dict(default=False, type='bool'),
exclusive=dict(default=False, type='bool'),
comment=dict(required=False, default=None, type='str'),
validate_certs=dict(default=True, type='bool'),
),
supports_check_mode=True
)
results = enforce_state(module, module.params)
module.exit_json(**results)
if __name__ == '__main__':
main()
| tsdmgz/ansible | lib/ansible/modules/system/authorized_key.py | Python | gpl-3.0 | 21,971 |
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved.
// EBML numbers (ids and sizes)
// C++ header
#ifndef _EBML_NUMBER_HH
#define _EBML_NUMBER_HH
#include "NetCommon.h"
#include "Boolean.hh"
#include <stdio.h>
#define EBML_NUMBER_MAX_LEN 8
class EBMLNumber {
public:
EBMLNumber(Boolean stripLeading1 = True);
virtual ~EBMLNumber();
u_int64_t val() const;
char* hexString() const; // used for debugging
Boolean operator==(u_int64_t arg2) const { return val() == arg2; }
Boolean operator!=(u_int64_t arg2) const { return !(*this == arg2); }
public:
Boolean stripLeading1;
unsigned len;
u_int8_t data[EBML_NUMBER_MAX_LEN];
};
// Definitions of some Matroska/EBML IDs (including the ones that we check for):
#define MATROSKA_ID_EBML 0x1A45DFA3
#define MATROSKA_ID_VOID 0xEC
#define MATROSKA_ID_CRC_32 0xBF
#define MATROSKA_ID_SEGMENT 0x18538067
#define MATROSKA_ID_SEEK_HEAD 0x114D9B74
#define MATROSKA_ID_SEEK 0x4DBB
#define MATROSKA_ID_SEEK_ID 0x53AB
#define MATROSKA_ID_SEEK_POSITION 0x53AC
#define MATROSKA_ID_INFO 0x1549A966
#define MATROSKA_ID_SEGMENT_UID 0x73A4
#define MATROSKA_ID_TIMECODE_SCALE 0x2AD7B1
#define MATROSKA_ID_DURATION 0x4489
#define MATROSKA_ID_DATE_UTC 0x4461
#define MATROSKA_ID_TITLE 0x7BA9
#define MATROSKA_ID_MUXING_APP 0x4D80
#define MATROSKA_ID_WRITING_APP 0x5741
#define MATROSKA_ID_CLUSTER 0x1F43B675
#define MATROSKA_ID_TIMECODE 0xE7
#define MATROSKA_ID_POSITION 0xA7
#define MATROSKA_ID_PREV_SIZE 0xAB
#define MATROSKA_ID_SIMPLEBLOCK 0xA3
#define MATROSKA_ID_BLOCK_GROUP 0xA0
#define MATROSKA_ID_BLOCK 0xA1
#define MATROSKA_ID_BLOCK_DURATION 0x9B
#define MATROSKA_ID_REFERENCE_BLOCK 0xFB
#define MATROSKA_ID_TRACKS 0x1654AE6B
#define MATROSKA_ID_TRACK_ENTRY 0xAE
#define MATROSKA_ID_TRACK_NUMBER 0xD7
#define MATROSKA_ID_TRACK_UID 0x73C5
#define MATROSKA_ID_TRACK_TYPE 0x83
#define MATROSKA_ID_FLAG_ENABLED 0xB9
#define MATROSKA_ID_FLAG_DEFAULT 0x88
#define MATROSKA_ID_FLAG_FORCED 0x55AA
#define MATROSKA_ID_FLAG_LACING 0x9C
#define MATROSKA_ID_MIN_CACHE 0x6DE7
#define MATROSKA_ID_DEFAULT_DURATION 0x23E383
#define MATROSKA_ID_TRACK_TIMECODE_SCALE 0x23314F
#define MATROSKA_ID_MAX_BLOCK_ADDITION_ID 0x55EE
#define MATROSKA_ID_NAME 0x536E
#define MATROSKA_ID_LANGUAGE 0x22B59C
#define MATROSKA_ID_CODEC 0x86
#define MATROSKA_ID_CODEC_PRIVATE 0x63A2
#define MATROSKA_ID_CODEC_NAME 0x258688
#define MATROSKA_ID_CODEC_DECODE_ALL 0xAA
#define MATROSKA_ID_VIDEO 0xE0
#define MATROSKA_ID_FLAG_INTERLACED 0x9A
#define MATROSKA_ID_PIXEL_WIDTH 0xB0
#define MATROSKA_ID_PIXEL_HEIGHT 0xBA
#define MATROSKA_ID_DISPLAY_WIDTH 0x54B0
#define MATROSKA_ID_DISPLAY_HEIGHT 0x54BA
#define MATROSKA_ID_DISPLAY_UNIT 0x54B2
#define MATROSKA_ID_AUDIO 0xE1
#define MATROSKA_ID_SAMPLING_FREQUENCY 0xB5
#define MATROSKA_ID_OUTPUT_SAMPLING_FREQUENCY 0x78B5
#define MATROSKA_ID_CHANNELS 0x9F
#define MATROSKA_ID_BIT_DEPTH 0x6264
#define MATROSKA_ID_CONTENT_ENCODINGS 0x6D80
#define MATROSKA_ID_CONTENT_ENCODING 0x6240
#define MATROSKA_ID_CONTENT_COMPRESSION 0x5034
#define MATROSKA_ID_CONTENT_COMP_ALGO 0x4254
#define MATROSKA_ID_CONTENT_COMP_SETTINGS 0x4255
#define MATROSKA_ID_CONTENT_ENCRYPTION 0x5035
#define MATROSKA_ID_ATTACHMENTS 0x1941A469
#define MATROSKA_ID_ATTACHED_FILE 0x61A7
#define MATROSKA_ID_FILE_DESCRIPTION 0x467E
#define MATROSKA_ID_FILE_NAME 0x466E
#define MATROSKA_ID_FILE_MIME_TYPE 0x4660
#define MATROSKA_ID_FILE_DATA 0x465C
#define MATROSKA_ID_FILE_UID 0x46AE
#define MATROSKA_ID_CUES 0x1C53BB6B
#define MATROSKA_ID_CUE_POINT 0xBB
#define MATROSKA_ID_CUE_TIME 0xB3
#define MATROSKA_ID_CUE_TRACK_POSITIONS 0xB7
#define MATROSKA_ID_CUE_TRACK 0xF7
#define MATROSKA_ID_CUE_CLUSTER_POSITION 0xF1
#define MATROSKA_ID_CUE_BLOCK_NUMBER 0x5378
#define MATROSKA_ID_TAGS 0x1254C367
#define MATROSKA_ID_SEEK_PRE_ROLL 0x56BB
#define MATROSKA_ID_CODEC_DELAY 0x56AA
#define MATROSKA_ID_DISCARD_PADDING 0x75A2
class EBMLId: public EBMLNumber {
public:
EBMLId();
virtual ~EBMLId();
char const* stringName() const; // used for debugging
};
class EBMLDataSize: public EBMLNumber {
public:
EBMLDataSize();
virtual ~EBMLDataSize();
};
#endif
| OpenSight/StreamSwitch | sources/stsw_rtsp_source/live/liveMedia/EBMLNumber.hh | C++ | agpl-3.0 | 4,898 |
#include <osg/Referenced>
#include <osg/Node>
#include <osg/Camera>
#include <osg/TextureRectangle>
#include <osg/Texture2D>
#include <osgGA/GUIEventHandler>
#include <limits>
#ifndef DEPTHPEELING_H
#define DEPTHPEELING_H
// Some choices for the kind of textures we can use ...
#define USE_TEXTURE_RECTANGLE
//#define USE_NON_POWER_OF_TWO_TEXTURE
#define USE_PACKED_DEPTH_STENCIL
template<typename T>
inline T
nextPowerOfTwo(T k)
{
if (k == T(0))
return 1;
k--;
for (int i = 1; i < std::numeric_limits<T>::digits; i <<= 1)
k = k | k >> i;
return k + 1;
}
class DepthPeeling : public osg::Referenced {
public:
DepthPeeling(unsigned int width, unsigned int height);
void setSolidScene(osg::Node* scene);
void setTransparentScene(osg::Node* scene);
osg::Node* getRoot();
void resize(int width, int height);
void setNumPasses(unsigned int numPasses);
unsigned int getNumPasses() const;
void setTexUnit(unsigned int texUnit);
void setShowAllLayers(bool showAllLayers);
bool getShowAllLayers() const;
void setOffsetValue(unsigned int offsetValue);
unsigned int getOffsetValue() const;
static const char *PeelingShader; /* use this to support depth peeling in GLSL shaders in transparent objects */
class EventHandler : public osgGA::GUIEventHandler {
public:
EventHandler(DepthPeeling* depthPeeling);
/** Handle events, return true if handled, false otherwise. */
virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*);
protected:
osg::ref_ptr<DepthPeeling> _depthPeeling;
};
protected:
osg::Node *createQuad(unsigned int layerNumber, unsigned int numTiles);
void createPeeling();
class CullCallback : public osg::NodeCallback {
public:
CullCallback(unsigned int texUnit, unsigned int offsetValue);
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
private:
unsigned int _texUnit;
unsigned int _offsetValue;
};
unsigned int _numPasses;
unsigned int _texUnit;
unsigned int _texWidth;
unsigned int _texHeight;
bool _showAllLayers;
unsigned int _offsetValue;
// The root node that is handed over to the viewer
osg::ref_ptr<osg::Group> _root;
// The scene that is displayed
osg::ref_ptr<osg::Group> _solidscene;
osg::ref_ptr<osg::Group> _transparentscene;
// The final camera that composites the pre rendered textures to the final picture
osg::ref_ptr<osg::Camera> _compositeCamera;
#ifdef USE_TEXTURE_RECTANGLE
std::vector<osg::ref_ptr<osg::TextureRectangle> > _depthTextures;
std::vector<osg::ref_ptr<osg::TextureRectangle> > _colorTextures;
#else
std::vector<osg::ref_ptr<osg::Texture2D> > _depthTextures;
std::vector<osg::ref_ptr<osg::Texture2D> > _colorTextures;
#endif
};
#endif // #ifndef DEPTHPEELING_H
| kctan0805/vdpm | share/openscenegraph/OpenSceneGraph-3.4.0/examples/osgoit/DepthPeeling.h | C | lgpl-2.1 | 2,949 |
/*
* Copyright 2011-2013, The Trustees of Indiana University and Northwestern
* University. 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.
* --- END LICENSE_HEADER BLOCK ---
*/
window.DynamicFields = {
initialize: function() {
/* Any fields marked with the class 'dynamic_field' will have an add button appended
* to the DOM after the label */
this.add_button_to_controls();
$(document).on('click', '.add-dynamic-field', function(event){
/* When we click the add button we need to manipulate the parent container, which
* is a <div class="controls dynamic"> wrapper */
/* CSS selectors are faster than doing a last() call in jQuery */
var input_template = $(this).parent().find('input:last');
/* By doing this we should just keep pushing the add button down as the last
* element of the parent container */
var new_input = $(input_template).clone().attr('value', '');
$(input_template).after(new_input);
});
},
/* Simpler is better */
add_button_to_controls: function() {
var controls = $('.controls.dynamic').append(DynamicFields.add_input_html);
},
add_input_html: '<span class="add-dynamic-field muted"><i class="icon-plus"></i></span>'
}
| tessafallon/dhf | avalon/trunk/app/assets/javascripts/dynamic_fields.js | JavaScript | apache-2.0 | 1,767 |
namespace Microsoft.Azure.Management.StorSimple8000Series.Models
{
using Azure;
using Management;
using StorSimple8000Series;
using Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The ACS configuration.
/// </summary>
public partial class AcsConfiguration
{
/// <summary>
/// Initializes a new instance of the AcsConfiguration class.
/// </summary>
public AcsConfiguration() { }
/// <summary>
/// Initializes a new instance of the AcsConfiguration class.
/// </summary>
/// <param name="namespaceProperty">The namespace.</param>
/// <param name="realm">The realm.</param>
/// <param name="serviceUrl">The service URL.</param>
public AcsConfiguration(string namespaceProperty, string realm, string serviceUrl)
{
NamespaceProperty = namespaceProperty;
Realm = realm;
ServiceUrl = serviceUrl;
}
/// <summary>
/// Gets or sets the namespace.
/// </summary>
[JsonProperty(PropertyName = "namespace")]
public string NamespaceProperty { get; set; }
/// <summary>
/// Gets or sets the realm.
/// </summary>
[JsonProperty(PropertyName = "realm")]
public string Realm { get; set; }
/// <summary>
/// Gets or sets the service URL.
/// </summary>
[JsonProperty(PropertyName = "serviceUrl")]
public string ServiceUrl { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (NamespaceProperty == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "NamespaceProperty");
}
if (Realm == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Realm");
}
if (ServiceUrl == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ServiceUrl");
}
}
}
}
| SiddharthChatrolaMs/azure-sdk-for-net | src/SDKs/StorSimple8000Series/Management.StorSimple8000Series/Generated/Models/AcsConfiguration.cs | C# | apache-2.0 | 2,277 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.rest.action.admin.indices;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.AcknowledgedRestListener;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
public class RestIndexDeleteAliasesAction extends BaseRestHandler {
public RestIndexDeleteAliasesAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(DELETE, "/{index}/_alias/{name}", this);
controller.registerHandler(DELETE, "/{index}/_aliases/{name}", this);
}
@Override
public String getName() {
return "index_delete_aliases_action";
}
@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
final String[] aliases = Strings.splitStringByCommaToArray(request.param("name"));
IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest();
indicesAliasesRequest.timeout(request.paramAsTime("timeout", indicesAliasesRequest.timeout()));
indicesAliasesRequest.addAliasAction(AliasActions.remove().indices(indices).aliases(aliases));
indicesAliasesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout()));
return channel -> client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestListener<>(channel));
}
}
| fred84/elasticsearch | server/src/main/java/org/elasticsearch/rest/action/admin/indices/RestIndexDeleteAliasesAction.java | Java | apache-2.0 | 2,750 |
/**
* 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.camel.impl;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.EndpointConfiguration;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.PollingConsumer;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.spi.HasId;
import org.apache.camel.spi.UriParam;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.EndpointHelper;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A default endpoint useful for implementation inheritance.
* <p/>
* Components which leverages <a
* href="http://camel.apache.org/asynchronous-routing-engine.html">asynchronous
* processing model</a> should check the {@link #isSynchronous()} to determine
* if asynchronous processing is allowed. The <tt>synchronous</tt> option on the
* endpoint allows Camel end users to dictate whether they want the asynchronous
* model or not. The option is default <tt>false</tt> which means asynchronous
* processing is allowed.
*
* @version
*/
public abstract class DefaultEndpoint extends ServiceSupport implements Endpoint, HasId, CamelContextAware {
private static final Logger LOG = LoggerFactory.getLogger(DefaultEndpoint.class);
private String endpointUri;
private EndpointConfiguration endpointConfiguration;
private CamelContext camelContext;
private Component component;
@UriParam(defaultValue = "InOnly", label = "advanced",
description = "Sets the default exchange pattern when creating an exchange")
private ExchangePattern exchangePattern = ExchangePattern.InOnly;
// option to allow end user to dictate whether async processing should be
// used or not (if possible)
@UriParam(defaultValue = "false", label = "advanced",
description = "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).")
private boolean synchronous;
private final String id = EndpointHelper.createEndpointId();
private Map<String, Object> consumerProperties;
private int pollingConsumerQueueSize = 1000;
private boolean pollingConsumerBlockWhenFull = true;
private long pollingConsumerBlockTimeout;
/**
* Constructs a fully-initialized DefaultEndpoint instance. This is the
* preferred method of constructing an object from Java code (as opposed to
* Spring beans, etc.).
*
* @param endpointUri the full URI used to create this endpoint
* @param component the component that created this endpoint
*/
protected DefaultEndpoint(String endpointUri, Component component) {
this.camelContext = component == null ? null : component.getCamelContext();
this.component = component;
this.setEndpointUri(endpointUri);
}
/**
* Constructs a DefaultEndpoint instance which has <b>not</b> been created
* using a {@link Component}.
* <p/>
* <b>Note:</b> It is preferred to create endpoints using the associated
* component.
*
* @param endpointUri the full URI used to create this endpoint
* @param camelContext the Camel Context in which this endpoint is operating
*/
@Deprecated
protected DefaultEndpoint(String endpointUri, CamelContext camelContext) {
this(endpointUri);
this.camelContext = camelContext;
}
/**
* Constructs a partially-initialized DefaultEndpoint instance.
* <p/>
* <b>Note:</b> It is preferred to create endpoints using the associated
* component.
*
* @param endpointUri the full URI used to create this endpoint
*/
@Deprecated
protected DefaultEndpoint(String endpointUri) {
this.setEndpointUri(endpointUri);
}
/**
* Constructs a partially-initialized DefaultEndpoint instance. Useful when
* creating endpoints manually (e.g., as beans in Spring).
* <p/>
* Please note that the endpoint URI must be set through properties (or
* overriding {@link #createEndpointUri()} if one uses this constructor.
* <p/>
* <b>Note:</b> It is preferred to create endpoints using the associated
* component.
*/
protected DefaultEndpoint() {
}
public int hashCode() {
return getEndpointUri().hashCode() * 37 + 1;
}
@Override
public boolean equals(Object object) {
if (object instanceof DefaultEndpoint) {
DefaultEndpoint that = (DefaultEndpoint)object;
return ObjectHelper.equal(this.getEndpointUri(), that.getEndpointUri());
}
return false;
}
@Override
public String toString() {
String value = null;
try {
value = getEndpointUri();
} catch (RuntimeException e) {
// ignore any exception and use null for building the string value
}
return String.format("Endpoint[%s]", URISupport.sanitizeUri(value));
}
/**
* Returns a unique String ID which can be used for aliasing without having
* to use the whole URI which is not unique
*/
public String getId() {
return id;
}
public String getEndpointUri() {
if (endpointUri == null) {
endpointUri = createEndpointUri();
if (endpointUri == null) {
throw new IllegalArgumentException("endpointUri is not specified and " + getClass().getName()
+ " does not implement createEndpointUri() to create a default value");
}
}
return endpointUri;
}
public EndpointConfiguration getEndpointConfiguration() {
if (endpointConfiguration == null) {
endpointConfiguration = createEndpointConfiguration(getEndpointUri());
}
return endpointConfiguration;
}
/**
* Sets a custom {@link EndpointConfiguration}
*
* @param endpointConfiguration a custom endpoint configuration to be used.
*/
public void setEndpointConfiguration(EndpointConfiguration endpointConfiguration) {
this.endpointConfiguration = endpointConfiguration;
}
public String getEndpointKey() {
if (isLenientProperties()) {
// only use the endpoint uri without parameters as the properties is
// lenient
String uri = getEndpointUri();
if (uri.indexOf('?') != -1) {
return ObjectHelper.before(uri, "?");
} else {
return uri;
}
} else {
// use the full endpoint uri
return getEndpointUri();
}
}
public CamelContext getCamelContext() {
return camelContext;
}
/**
* Returns the component that created this endpoint.
*
* @return the component that created this endpoint, or <tt>null</tt> if
* none set
*/
public Component getComponent() {
return component;
}
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public PollingConsumer createPollingConsumer() throws Exception {
// should not call configurePollingConsumer when its EventDrivenPollingConsumer
if (LOG.isDebugEnabled()) {
LOG.debug("Creating EventDrivenPollingConsumer with queueSize: {} blockWhenFull: {} blockTimeout: {}",
new Object[]{getPollingConsumerQueueSize(), isPollingConsumerBlockWhenFull(), getPollingConsumerBlockTimeout()});
}
EventDrivenPollingConsumer consumer = new EventDrivenPollingConsumer(this, getPollingConsumerQueueSize());
consumer.setBlockWhenFull(isPollingConsumerBlockWhenFull());
consumer.setBlockTimeout(getPollingConsumerBlockTimeout());
return consumer;
}
public Exchange createExchange(Exchange exchange) {
return exchange.copy();
}
public Exchange createExchange() {
return createExchange(getExchangePattern());
}
public Exchange createExchange(ExchangePattern pattern) {
return new DefaultExchange(this, pattern);
}
/**
* Returns the default exchange pattern to use when creating an exchange.
*/
public ExchangePattern getExchangePattern() {
return exchangePattern;
}
/**
* Sets the default exchange pattern when creating an exchange.
*/
public void setExchangePattern(ExchangePattern exchangePattern) {
this.exchangePattern = exchangePattern;
}
/**
* Returns whether synchronous processing should be strictly used.
*/
public boolean isSynchronous() {
return synchronous;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel is
* allowed to use asynchronous processing (if supported).
*
* @param synchronous <tt>true</tt> to enforce synchronous processing
*/
public void setSynchronous(boolean synchronous) {
this.synchronous = synchronous;
}
/**
* Gets the {@link org.apache.camel.PollingConsumer} queue size, when {@link org.apache.camel.impl.EventDrivenPollingConsumer}
* is being used. Notice some Camel components may have their own implementation of {@link org.apache.camel.PollingConsumer} and
* therefore not using the default {@link org.apache.camel.impl.EventDrivenPollingConsumer} implementation.
* <p/>
* The default value is <tt>1000</tt>
*/
public int getPollingConsumerQueueSize() {
return pollingConsumerQueueSize;
}
/**
* Sets the {@link org.apache.camel.PollingConsumer} queue size, when {@link org.apache.camel.impl.EventDrivenPollingConsumer}
* is being used. Notice some Camel components may have their own implementation of {@link org.apache.camel.PollingConsumer} and
* therefore not using the default {@link org.apache.camel.impl.EventDrivenPollingConsumer} implementation.
* <p/>
* The default value is <tt>1000</tt>
*/
public void setPollingConsumerQueueSize(int pollingConsumerQueueSize) {
this.pollingConsumerQueueSize = pollingConsumerQueueSize;
}
/**
* Whether to block when adding to the internal queue off when {@link org.apache.camel.impl.EventDrivenPollingConsumer}
* is being used. Notice some Camel components may have their own implementation of {@link org.apache.camel.PollingConsumer} and
* therefore not using the default {@link org.apache.camel.impl.EventDrivenPollingConsumer} implementation.
* <p/>
* Setting this option to <tt>false</tt>, will result in an {@link java.lang.IllegalStateException} being thrown
* when trying to add to the queue, and its full.
* <p/>
* The default value is <tt>true</tt> which will block the producer queue until the queue has space.
*/
public boolean isPollingConsumerBlockWhenFull() {
return pollingConsumerBlockWhenFull;
}
/**
* Set whether to block when adding to the internal queue off when {@link org.apache.camel.impl.EventDrivenPollingConsumer}
* is being used. Notice some Camel components may have their own implementation of {@link org.apache.camel.PollingConsumer} and
* therefore not using the default {@link org.apache.camel.impl.EventDrivenPollingConsumer} implementation.
* <p/>
* Setting this option to <tt>false</tt>, will result in an {@link java.lang.IllegalStateException} being thrown
* when trying to add to the queue, and its full.
* <p/>
* The default value is <tt>true</tt> which will block the producer queue until the queue has space.
*/
public void setPollingConsumerBlockWhenFull(boolean pollingConsumerBlockWhenFull) {
this.pollingConsumerBlockWhenFull = pollingConsumerBlockWhenFull;
}
/**
* Sets the timeout in millis to use when adding to the internal queue off when {@link org.apache.camel.impl.EventDrivenPollingConsumer}
* is being used.
*
* @see #setPollingConsumerBlockWhenFull(boolean)
*/
public long getPollingConsumerBlockTimeout() {
return pollingConsumerBlockTimeout;
}
/**
* Sets the timeout in millis to use when adding to the internal queue off when {@link org.apache.camel.impl.EventDrivenPollingConsumer}
* is being used.
*
* @see #setPollingConsumerBlockWhenFull(boolean)
*/
public void setPollingConsumerBlockTimeout(long pollingConsumerBlockTimeout) {
this.pollingConsumerBlockTimeout = pollingConsumerBlockTimeout;
}
public void configureProperties(Map<String, Object> options) {
Map<String, Object> consumerProperties = IntrospectionSupport.extractProperties(options, "consumer.");
if (consumerProperties != null && !consumerProperties.isEmpty()) {
setConsumerProperties(consumerProperties);
}
}
/**
* Sets the bean properties on the given bean.
* <p/>
* This is the same logical implementation as {@link DefaultComponent#setProperties(Object, java.util.Map)}
*
* @param bean the bean
* @param parameters properties to set
*/
protected void setProperties(Object bean, Map<String, Object> parameters) throws Exception {
// set reference properties first as they use # syntax that fools the regular properties setter
EndpointHelper.setReferenceProperties(getCamelContext(), bean, parameters);
EndpointHelper.setProperties(getCamelContext(), bean, parameters);
}
/**
* A factory method to lazily create the endpointUri if none is specified
*/
protected String createEndpointUri() {
return null;
}
/**
* A factory method to lazily create the endpoint configuration if none is specified
*/
protected EndpointConfiguration createEndpointConfiguration(String uri) {
// using this factory method to be backwards compatible with the old code
if (getComponent() != null) {
// prefer to use component endpoint configuration
try {
return getComponent().createConfiguration(uri);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
} else if (getCamelContext() != null) {
// fallback and use a mapped endpoint configuration
return new MappedEndpointConfiguration(getCamelContext(), uri);
}
// not configuration possible
return null;
}
/**
* Sets the endpointUri if it has not been specified yet via some kind of
* dependency injection mechanism. This allows dependency injection
* frameworks such as Spring or Guice to set the default endpoint URI in
* cases where it has not been explicitly configured using the name/context
* in which an Endpoint is created.
*/
public void setEndpointUriIfNotSpecified(String value) {
if (endpointUri == null) {
setEndpointUri(value);
}
}
/**
* Sets the URI that created this endpoint.
*/
protected void setEndpointUri(String endpointUri) {
this.endpointUri = endpointUri;
}
public boolean isLenientProperties() {
// default should be false for most components
return false;
}
public Map<String, Object> getConsumerProperties() {
if (consumerProperties == null) {
// must create empty if none exists
consumerProperties = new HashMap<String, Object>();
}
return consumerProperties;
}
public void setConsumerProperties(Map<String, Object> consumerProperties) {
// append consumer properties
if (consumerProperties != null && !consumerProperties.isEmpty()) {
if (this.consumerProperties == null) {
this.consumerProperties = new HashMap<String, Object>(consumerProperties);
} else {
this.consumerProperties.putAll(consumerProperties);
}
}
}
protected void configureConsumer(Consumer consumer) throws Exception {
if (consumerProperties != null) {
// use a defensive copy of the consumer properties as the methods below will remove the used properties
// and in case we restart routes, we need access to the original consumer properties again
Map<String, Object> copy = new HashMap<String, Object>(consumerProperties);
// set reference properties first as they use # syntax that fools the regular properties setter
EndpointHelper.setReferenceProperties(getCamelContext(), consumer, copy);
EndpointHelper.setProperties(getCamelContext(), consumer, copy);
// special consumer.bridgeErrorHandler option
Object bridge = copy.remove("bridgeErrorHandler");
if (bridge != null && "true".equals(bridge)) {
if (consumer instanceof DefaultConsumer) {
DefaultConsumer defaultConsumer = (DefaultConsumer) consumer;
defaultConsumer.setExceptionHandler(new BridgeExceptionHandlerToErrorHandler(defaultConsumer));
} else {
throw new IllegalArgumentException("Option consumer.bridgeErrorHandler is only supported by endpoints,"
+ " having their consumer extend DefaultConsumer. The consumer is a " + consumer.getClass().getName() + " class.");
}
}
if (!this.isLenientProperties() && copy.size() > 0) {
throw new ResolveEndpointFailedException(this.getEndpointUri(), "There are " + copy.size()
+ " parameters that couldn't be set on the endpoint consumer."
+ " Check the uri if the parameters are spelt correctly and that they are properties of the endpoint."
+ " Unknown consumer parameters=[" + copy + "]");
}
}
}
protected void configurePollingConsumer(PollingConsumer consumer) throws Exception {
configureConsumer(consumer);
}
@Override
protected void doStart() throws Exception {
// noop
}
@Override
protected void doStop() throws Exception {
// noop
}
}
| snadakuduru/camel | camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java | Java | apache-2.0 | 19,420 |
/*
* Copyright 2012-2019 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
*
* https://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.logging.log4j2;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.ExtendedThrowablePatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;
import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter;
/**
* {@link ThrowablePatternConverter} that adds some additional whitespace around the stack
* trace.
*
* @author Vladimir Tsanev
* @author Phillip Webb
* @since 1.3.0
*/
@Plugin(name = "ExtendedWhitespaceThrowablePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({ "xwEx", "xwThrowable", "xwException" })
public final class ExtendedWhitespaceThrowablePatternConverter extends ThrowablePatternConverter {
private final ExtendedThrowablePatternConverter delegate;
private ExtendedWhitespaceThrowablePatternConverter(Configuration configuration, String[] options) {
super("WhitespaceExtendedThrowable", "throwable", options, configuration);
this.delegate = ExtendedThrowablePatternConverter.newInstance(configuration, options);
}
@Override
public void format(LogEvent event, StringBuilder buffer) {
if (event.getThrown() != null) {
buffer.append(this.options.getSeparator());
this.delegate.format(event, buffer);
buffer.append(this.options.getSeparator());
}
}
/**
* Creates a new instance of the class. Required by Log4J2.
* @param configuration current configuration
* @param options pattern options, may be null. If first element is "short", only the
* first line of the throwable will be formatted.
* @return a new {@code WhitespaceThrowablePatternConverter}
*/
public static ExtendedWhitespaceThrowablePatternConverter newInstance(Configuration configuration,
String[] options) {
return new ExtendedWhitespaceThrowablePatternConverter(configuration, options);
}
}
| ilayaperumalg/spring-boot | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverter.java | Java | apache-2.0 | 2,660 |
using System;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace NuGet.VisualStudio
{
public static class DTEExtensions
{
public static Project GetActiveProject(this IVsMonitorSelection vsMonitorSelection)
{
return VsUtility.GetActiveProject(vsMonitorSelection);
}
public static bool GetIsSolutionNodeSelected(this IVsMonitorSelection vsMonitorSelection)
{
return VsUtility.GetIsSolutionNodeSelected(vsMonitorSelection);
}
}
} | mrward/nuget | src/VisualStudio/Extensions/DTEExtensions.cs | C# | apache-2.0 | 617 |
package com.typesafe.slick.docs.test
class JoinsUnionsTest extends RecordedDoctest {
def run = com.typesafe.slick.docs.JoinsUnions.main(null)
}
| jkutner/slick | slick-testkit/src/doctest/scala/com/typesafe/slick/docs/test/JoinsUnionsTest.scala | Scala | bsd-2-clause | 147 |
// Type definitions for jira-client 6.13
// Project: http://github.com/jira-node/node-jira-client
// Definitions by: Anatoliy Ostapenko <https://github.com/KOPTE3>
// Orta Therox <https://github.com/orta>
// Robert Kesterson <https://github.com/rkesters>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
import { CoreOptions, RequestResponse } from "request";
import { ReadStream } from "fs";
declare class JiraApi {
private protocol: string;
private host: string;
private port: string | null;
private apiVersion: string;
private base: string;
private intermediatePath?: string;
private strictSSL: boolean;
private webhookVersion: string;
private greenhopperVersion: string;
constructor(options: JiraApi.JiraApiOptions);
findIssue(
issueNumber: string,
expand?: string,
fields?: string,
properties?: string,
fieldsByKeys?: boolean
): Promise<JiraApi.JsonResponse>;
getUnresolvedIssueCount(version: string): Promise<number>;
getProject(project: string): Promise<JiraApi.JsonResponse>;
createProject(project: string): Promise<JiraApi.JsonResponse>;
findRapidView(projectName: string): Promise<JiraApi.JsonResponse[]>;
getLastSprintForRapidView(rapidViewId: string): Promise<JiraApi.JsonResponse>;
getSprintIssues(rapidViewId: string, sprintId: string): Promise<JiraApi.JsonResponse>;
listSprints(rapidViewId: string): Promise<JiraApi.JsonResponse>;
addIssueToSprint(issueId: string, sprintId: string): Promise<JiraApi.JsonResponse>;
issueLink(link: JiraApi.LinkObject): Promise<JiraApi.JsonResponse>;
getRemoteLinks(issueNumber: string): Promise<JiraApi.JsonResponse>;
createRemoteLink(issueNumber: string, remoteLink: JiraApi.LinkObject): Promise<JiraApi.JsonResponse>;
getVersions(project: string): Promise<JiraApi.JsonResponse>;
createVersion(version: string): Promise<JiraApi.JsonResponse>;
updateVersion(version: string): Promise<JiraApi.JsonResponse>;
deleteVersion(
versionId: string,
moveFixIssuesToId: string,
moveAffectedIssuesToId: string
): Promise<JiraApi.JsonResponse>;
searchJira(searchString: string, optional?: JiraApi.SearchQuery): Promise<JiraApi.JsonResponse>;
createUser(user: JiraApi.UserObject): Promise<JiraApi.JsonResponse>;
searchUsers(options: JiraApi.SearchUserOptions): Promise<JiraApi.JsonResponse>;
getUsersInGroup(groupname: string, startAt?: number, maxResults?: number): Promise<JiraApi.JsonResponse>;
addNewIssue(issue: JiraApi.IssueObject): Promise<JiraApi.JsonResponse>;
addWatcher(issueKey: string, username: string): Promise<JiraApi.JsonResponse>;
getIssueWatchers(issueId: string): Promise<JiraApi.JsonResponse[]>;
deleteIssue(issueId: string): Promise<JiraApi.JsonResponse>;
updateIssue(issueId: string, issueUpdate: JiraApi.IssueObject, query?: JiraApi.Query): Promise<JiraApi.JsonResponse>;
listComponents(project: string): Promise<JiraApi.JsonResponse>;
addNewComponent(component: JiraApi.ComponentObject): Promise<JiraApi.JsonResponse>;
deleteComponent(componentId: string): Promise<JiraApi.JsonResponse>;
createCustomField(field: JiraApi.FieldObject): Promise<JiraApi.JsonResponse>;
listFields(): Promise<JiraApi.FieldObject[]>;
createFieldOption(fieldKey: string, option: JiraApi.FieldOptionObject): Promise<JiraApi.JsonResponse>;
listFieldOptions(fieldKey: string): Promise<JiraApi.JsonResponse>;
upsertFieldOption(
fieldKey: string,
optionId: string,
option: JiraApi.FieldOptionObject
): Promise<JiraApi.JsonResponse>;
getFieldOption(fieldKey: string, optionId: string): Promise<JiraApi.JsonResponse>;
deleteFieldOption(fieldKey: string, optionId: string): Promise<JiraApi.JsonResponse>;
getIssueProperty(issueNumber: string, property: string): Promise<JiraApi.JsonResponse>;
listPriorities(): Promise<JiraApi.JsonResponse>;
listTransitions(issueId: string): Promise<JiraApi.JsonResponse>;
transitionIssue(issueId: string, issueTransition: JiraApi.TransitionObject): Promise<JiraApi.JsonResponse>;
listProjects(): Promise<JiraApi.JsonResponse>;
addComment(issueId: string, comment: string): Promise<JiraApi.JsonResponse>;
updateComment(issueId: string, commentId: string, comment: string, options?: any): Promise<JiraApi.JsonResponse>;
addWorklog(
issueId: string,
worklog: JiraApi.WorklogObject,
newEstimate?: JiraApi.EstimateObject
): Promise<JiraApi.JsonResponse>;
deleteWorklog(issueId: string, worklogId: string): Promise<JiraApi.JsonResponse>;
getIssueWorklogs(issueId: string): Promise<JiraApi.JsonResponse>;
listIssueTypes(): Promise<JiraApi.JsonResponse>;
registerWebhook(webhook: JiraApi.WebhookObject): Promise<JiraApi.JsonResponse>;
listWebhooks(): Promise<JiraApi.JsonResponse>;
getWebhook(webhookID: string): Promise<JiraApi.JsonResponse>;
deleteWebhook(webhookID: string): Promise<JiraApi.JsonResponse>;
getCurrentUser(): Promise<JiraApi.JsonResponse>;
getBacklogForRapidView(rapidViewId: string): Promise<JiraApi.JsonResponse>;
addAttachmentOnIssue(issueId: string, readStream: ReadStream): Promise<JiraApi.JsonResponse>;
issueNotify(issueId: string, notificationBody: JiraApi.NotificationObject): Promise<JiraApi.JsonResponse>;
listStatus(): Promise<JiraApi.JsonResponse>;
getDevStatusSummary(issueId: string): Promise<JiraApi.JsonResponse>;
getDevStatusDetail(issueId: string, applicationType: string, dataType: string): Promise<JiraApi.JsonResponse>;
moveToBacklog(issues: string[]): Promise<JiraApi.JsonResponse>;
getAllBoards(
startAt?: number,
maxResults?: number,
type?: string,
name?: string,
projectKeyOrId?: string
): Promise<JiraApi.JsonResponse>;
createBoard(boardBody: JiraApi.BoardObject): Promise<JiraApi.JsonResponse>;
getBoard(boardId: string): Promise<JiraApi.JsonResponse>;
deleteBoard(boardId: string): Promise<JiraApi.JsonResponse>;
getIssuesForBacklog(
boardId: string,
startAt?: number,
maxResults?: number,
jql?: string,
validateQuery?: boolean,
fields?: string
): Promise<JiraApi.JsonResponse>;
getConfiguration(boardId: string): Promise<JiraApi.JsonResponse>;
getIssuesForBoard(
boardId: string,
startAt?: number,
maxResults?: number,
jql?: string,
validateQuery?: boolean,
fields?: string
): Promise<JiraApi.JsonResponse>;
getEpics(
boardId: string,
startAt?: number,
maxResults?: number,
done?: "true" | "false"
): Promise<JiraApi.JsonResponse>;
getBoardIssuesForEpic(
boardId: string,
epicId: string,
startAt?: number,
maxResults?: number,
jql?: string,
validateQuery?: boolean,
fields?: string
): Promise<JiraApi.JsonResponse>;
getProjects(boardId: string, startAt?: number, maxResults?: number): Promise<JiraApi.JsonResponse>;
getProjectsFull(boardId: string): Promise<JiraApi.JsonResponse>;
getBoardPropertiesKeys(boardId: string): Promise<JiraApi.JsonResponse>;
deleteBoardProperty(boardId: string, propertyKey: string): Promise<JiraApi.JsonResponse>;
setBoardProperty(boardId: string, propertyKey: string, body: string): Promise<JiraApi.JsonResponse>;
getBoardProperty(boardId: string, propertyKey: string): Promise<JiraApi.JsonResponse>;
getAllSprints(
boardId: string,
startAt?: number,
maxResults?: number,
state?: "future" | "active" | "closed"
): Promise<JiraApi.JsonResponse>;
getBoardIssuesForSprint(
boardId: string,
sprintId: string,
startAt?: number,
maxResults?: number,
jql?: string,
validateQuery?: boolean,
fields?: string
): Promise<JiraApi.JsonResponse>;
getAllVersions(
boardId: string,
startAt?: number,
maxResults?: number,
released?: "true" | "false"
): Promise<JiraApi.JsonResponse>;
private makeRequestHeader(uri: string, options?: JiraApi.UriOptions);
private makeUri(options: JiraApi.UriOptions): string;
private makeWebhookUri(options: JiraApi.UriOptions): string;
private makeSprintQueryUri(options: JiraApi.UriOptions): string;
private makeDevStatusUri(options: JiraApi.UriOptions): string;
private makeAgileUri(options: JiraApi.UriOptions): string;
private doRequest(requestOptions: CoreOptions): Promise<RequestResponse>;
}
declare namespace JiraApi {
interface JiraApiOptions {
protocol?: string;
host: string;
port?: string;
username?: string;
password?: string;
apiVersion?: string;
base?: string;
intermediatePath?: string;
strictSSL?: boolean;
request?: any;
timeout?: number;
webhookVersion?: string;
greenhopperVersion?: string;
bearer?: string;
oauth?: OAuth;
}
interface OAuth {
consumer_key: string;
consumer_secret: string;
access_token: string;
access_token_secret: string;
signature_method?: string;
}
interface LinkObject {
[name: string]: any;
}
interface Query {
[name: string]: any;
}
interface JsonResponse {
[name: string]: any;
}
interface UserObject {
[name: string]: any;
}
interface IssueObject {
[name: string]: any;
}
interface ComponentObject {
[name: string]: any;
}
interface FieldObject {
[name: string]: any;
}
interface FieldOptionObject {
[name: string]: any;
}
interface TransitionObject {
[name: string]: any;
}
interface WorklogObject {
[name: string]: any;
}
interface EstimateObject {
[name: string]: any;
}
interface WebhookObject {
[name: string]: any;
}
interface NotificationObject {
[name: string]: any;
}
interface BoardObject {
[name: string]: any;
}
interface SearchUserOptions {
username: string;
startAt?: number;
maxResults?: number;
includeActive?: boolean;
includeInactive?: boolean;
}
interface SearchQuery {
startAt?: number;
maxResults?: number;
fields?: string[];
expand?: string[];
}
interface UriOptions {
pathname: string;
query?: Query;
intermediatePath?: string;
}
}
export = JiraApi;
| dsebastien/DefinitelyTyped | types/jira-client/index.d.ts | TypeScript | mit | 10,881 |
#
# change centos_64_dvd to one of configurations in *.yml in this directory
# use the yml files to configure
#
Veewee::Definition.declare_yaml('definition.yml', "centos_64_minimal.yml")
| jordant/veewee | templates/CentOS-6.5/definition.rb | Ruby | mit | 187 |
/* Header file for exception handling.
Copyright (C) 2013-2016 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_TREE_EH_H
#define GCC_TREE_EH_H
typedef struct eh_region_d *eh_region;
extern void using_eh_for_cleanups (void);
extern void add_stmt_to_eh_lp (gimple *, int);
extern bool remove_stmt_from_eh_lp_fn (struct function *, gimple *);
extern bool remove_stmt_from_eh_lp (gimple *);
extern int lookup_stmt_eh_lp_fn (struct function *, gimple *);
extern int lookup_stmt_eh_lp (gimple *);
extern bool make_eh_dispatch_edges (geh_dispatch *);
extern void make_eh_edges (gimple *);
extern edge redirect_eh_edge (edge, basic_block);
extern void redirect_eh_dispatch_edge (geh_dispatch *, edge, basic_block);
extern bool operation_could_trap_helper_p (enum tree_code, bool, bool, bool,
bool, tree, bool *);
extern bool operation_could_trap_p (enum tree_code, bool, bool, tree);
extern bool tree_could_trap_p (tree);
extern bool stmt_could_throw_p (gimple *);
extern bool tree_could_throw_p (tree);
extern bool stmt_can_throw_external (gimple *);
extern bool stmt_can_throw_internal (gimple *);
extern bool maybe_clean_eh_stmt_fn (struct function *, gimple *);
extern bool maybe_clean_eh_stmt (gimple *);
extern bool maybe_clean_or_replace_eh_stmt (gimple *, gimple *);
extern bool maybe_duplicate_eh_stmt_fn (struct function *, gimple *,
struct function *, gimple *,
hash_map<void *, void *> *, int);
extern bool maybe_duplicate_eh_stmt (gimple *, gimple *);
extern void maybe_remove_unreachable_handlers (void);
extern bool verify_eh_edges (gimple *);
extern bool verify_eh_dispatch_edge (geh_dispatch *);
#endif /* GCC_TREE_EH_H */
| ChangsoonKim/STM32F7DiscTutor | toolchain/osx/gcc-arm-none-eabi-6-2017-q1-update/lib/gcc/arm-none-eabi/6.3.1/plugin/include/tree-eh.h | C | mit | 2,278 |
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.matchers;
import java.io.Serializable;
public class LessThan<T extends Comparable<T>> extends CompareTo<T> implements Serializable {
private static final long serialVersionUID = -133860804462310942L;
public LessThan(Comparable<T> value) {
super(value);
}
@Override
protected String getName() {
return "lt";
}
@Override
protected boolean matchResult(int result) {
return result < 0;
}
}
| lshain-android-source/external-mockito | src/org/mockito/internal/matchers/LessThan.java | Java | mit | 602 |
/*********************/
/* GNAs ContainerAPP */
/*********************/
html {
position: relative;
min-height: 100%;
}
body {
background: -webkit-linear-gradient(0deg, #8e9eab 10%, #eef2f3 90%); /* Chrome 10+, Saf5.1+ */
background: -moz-linear-gradient(0deg, #8e9eab 10%, #eef2f3 90%); /* FF3.6+ */
background: -ms-linear-gradient(0deg, #8e9eab 10%, #eef2f3 90%); /* IE10 */
background: -o-linear-gradient(0deg, #8e9eab 10%, #eef2f3 90%); /* Opera 11.10+ */
background: linear-gradient(0deg, #8e9eab 10%, #eef2f3 90%); /* W3C */
}
a {color: white; transition: all .5s ease-in-out;} | daniboomerang/Curso-Angular | TEMA7/EJERCICIOS/client/styles/gnas.css | CSS | mit | 620 |
require 'rails_helper'
RSpec.describe BankAccount, type: :model do
describe "associations" do
it{ is_expected.to belong_to :user }
end
describe "Validations" do
it{ is_expected.to validate_presence_of(:bank_id) }
it{ is_expected.to validate_presence_of(:agency) }
it{ is_expected.to validate_presence_of(:account) }
it{ is_expected.to validate_presence_of(:account_digit) }
it{ is_expected.to validate_presence_of(:owner_name) }
it{ is_expected.to validate_presence_of(:owner_document) }
end
end
| liberland/catarse | spec/models/bank_account_spec.rb | Ruby | mit | 534 |
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OptionsColor=void 0;class OptionsColor{constructor(){this.value="#fff"}static create(o,t){const e=null!=o?o:new OptionsColor;return void 0!==t&&e.load("string"==typeof t?{value:t}:t),e}load(o){void 0!==(null==o?void 0:o.value)&&(this.value=o.value)}}exports.OptionsColor=OptionsColor; | cdnjs/cdnjs | ajax/libs/tsparticles/1.17.0-alpha.9/Options/Classes/OptionsColor.min.js | JavaScript | mit | 360 |
/*
* Copyright (c) by Jaroslav Kysela <[email protected]>
* and (c) 1999 Steve Ratcliffe <[email protected]>
* Copyright (C) 1999-2000 Takashi Iwai <[email protected]>
*
* Routines for control of EMU8000 chip
*
* 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
*/
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <sound/core.h>
#include <sound/emu8000.h>
#include <sound/emu8000_reg.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/init.h>
#include <sound/control.h>
#include <sound/initval.h>
/*
* emu8000 register controls
*/
/*
* The following routines read and write registers on the emu8000. They
* should always be called via the EMU8000*READ/WRITE macros and never
* directly. The macros handle the port number and command word.
*/
/* Write a word */
void snd_emu8000_poke(struct snd_emu8000 *emu, unsigned int port, unsigned int reg, unsigned int val)
{
unsigned long flags;
spin_lock_irqsave(&emu->reg_lock, flags);
if (reg != emu->last_reg) {
outw((unsigned short)reg, EMU8000_PTR(emu)); /* Set register */
emu->last_reg = reg;
}
outw((unsigned short)val, port); /* Send data */
spin_unlock_irqrestore(&emu->reg_lock, flags);
}
/* Read a word */
unsigned short snd_emu8000_peek(struct snd_emu8000 *emu, unsigned int port, unsigned int reg)
{
unsigned short res;
unsigned long flags;
spin_lock_irqsave(&emu->reg_lock, flags);
if (reg != emu->last_reg) {
outw((unsigned short)reg, EMU8000_PTR(emu)); /* Set register */
emu->last_reg = reg;
}
res = inw(port); /* Read data */
spin_unlock_irqrestore(&emu->reg_lock, flags);
return res;
}
/* Write a double word */
void snd_emu8000_poke_dw(struct snd_emu8000 *emu, unsigned int port, unsigned int reg, unsigned int val)
{
unsigned long flags;
spin_lock_irqsave(&emu->reg_lock, flags);
if (reg != emu->last_reg) {
outw((unsigned short)reg, EMU8000_PTR(emu)); /* Set register */
emu->last_reg = reg;
}
outw((unsigned short)val, port); /* Send low word of data */
outw((unsigned short)(val>>16), port+2); /* Send high word of data */
spin_unlock_irqrestore(&emu->reg_lock, flags);
}
/* Read a double word */
unsigned int snd_emu8000_peek_dw(struct snd_emu8000 *emu, unsigned int port, unsigned int reg)
{
unsigned short low;
unsigned int res;
unsigned long flags;
spin_lock_irqsave(&emu->reg_lock, flags);
if (reg != emu->last_reg) {
outw((unsigned short)reg, EMU8000_PTR(emu)); /* Set register */
emu->last_reg = reg;
}
low = inw(port); /* Read low word of data */
res = low + (inw(port+2) << 16);
spin_unlock_irqrestore(&emu->reg_lock, flags);
return res;
}
/*
* Set up / close a channel to be used for DMA.
*/
/*exported*/ void
snd_emu8000_dma_chan(struct snd_emu8000 *emu, int ch, int mode)
{
unsigned right_bit = (mode & EMU8000_RAM_RIGHT) ? 0x01000000 : 0;
mode &= EMU8000_RAM_MODE_MASK;
if (mode == EMU8000_RAM_CLOSE) {
EMU8000_CCCA_WRITE(emu, ch, 0);
EMU8000_DCYSUSV_WRITE(emu, ch, 0x807F);
return;
}
EMU8000_DCYSUSV_WRITE(emu, ch, 0x80);
EMU8000_VTFT_WRITE(emu, ch, 0);
EMU8000_CVCF_WRITE(emu, ch, 0);
EMU8000_PTRX_WRITE(emu, ch, 0x40000000);
EMU8000_CPF_WRITE(emu, ch, 0x40000000);
EMU8000_PSST_WRITE(emu, ch, 0);
EMU8000_CSL_WRITE(emu, ch, 0);
if (mode == EMU8000_RAM_WRITE) /* DMA write */
EMU8000_CCCA_WRITE(emu, ch, 0x06000000 | right_bit);
else /* DMA read */
EMU8000_CCCA_WRITE(emu, ch, 0x04000000 | right_bit);
}
/*
*/
static void __devinit
snd_emu8000_read_wait(struct snd_emu8000 *emu)
{
while ((EMU8000_SMALR_READ(emu) & 0x80000000) != 0) {
schedule_timeout_interruptible(1);
if (signal_pending(current))
break;
}
}
/*
*/
static void __devinit
snd_emu8000_write_wait(struct snd_emu8000 *emu)
{
while ((EMU8000_SMALW_READ(emu) & 0x80000000) != 0) {
schedule_timeout_interruptible(1);
if (signal_pending(current))
break;
}
}
/*
* detect a card at the given port
*/
static int __devinit
snd_emu8000_detect(struct snd_emu8000 *emu)
{
/* Initialise */
EMU8000_HWCF1_WRITE(emu, 0x0059);
EMU8000_HWCF2_WRITE(emu, 0x0020);
EMU8000_HWCF3_WRITE(emu, 0x0000);
/* Check for a recognisable emu8000 */
/*
if ((EMU8000_U1_READ(emu) & 0x000f) != 0x000c)
return -ENODEV;
*/
if ((EMU8000_HWCF1_READ(emu) & 0x007e) != 0x0058)
return -ENODEV;
if ((EMU8000_HWCF2_READ(emu) & 0x0003) != 0x0003)
return -ENODEV;
snd_printdd("EMU8000 [0x%lx]: Synth chip found\n",
emu->port1);
return 0;
}
/*
* intiailize audio channels
*/
static void __devinit
init_audio(struct snd_emu8000 *emu)
{
int ch;
/* turn off envelope engines */
for (ch = 0; ch < EMU8000_CHANNELS; ch++)
EMU8000_DCYSUSV_WRITE(emu, ch, 0x80);
/* reset all other parameters to zero */
for (ch = 0; ch < EMU8000_CHANNELS; ch++) {
EMU8000_ENVVOL_WRITE(emu, ch, 0);
EMU8000_ENVVAL_WRITE(emu, ch, 0);
EMU8000_DCYSUS_WRITE(emu, ch, 0);
EMU8000_ATKHLDV_WRITE(emu, ch, 0);
EMU8000_LFO1VAL_WRITE(emu, ch, 0);
EMU8000_ATKHLD_WRITE(emu, ch, 0);
EMU8000_LFO2VAL_WRITE(emu, ch, 0);
EMU8000_IP_WRITE(emu, ch, 0);
EMU8000_IFATN_WRITE(emu, ch, 0);
EMU8000_PEFE_WRITE(emu, ch, 0);
EMU8000_FMMOD_WRITE(emu, ch, 0);
EMU8000_TREMFRQ_WRITE(emu, ch, 0);
EMU8000_FM2FRQ2_WRITE(emu, ch, 0);
EMU8000_PTRX_WRITE(emu, ch, 0);
EMU8000_VTFT_WRITE(emu, ch, 0);
EMU8000_PSST_WRITE(emu, ch, 0);
EMU8000_CSL_WRITE(emu, ch, 0);
EMU8000_CCCA_WRITE(emu, ch, 0);
}
for (ch = 0; ch < EMU8000_CHANNELS; ch++) {
EMU8000_CPF_WRITE(emu, ch, 0);
EMU8000_CVCF_WRITE(emu, ch, 0);
}
}
/*
* initialize DMA address
*/
static void __devinit
init_dma(struct snd_emu8000 *emu)
{
EMU8000_SMALR_WRITE(emu, 0);
EMU8000_SMARR_WRITE(emu, 0);
EMU8000_SMALW_WRITE(emu, 0);
EMU8000_SMARW_WRITE(emu, 0);
}
/*
* initialization arrays; from ADIP
*/
static unsigned short init1[128] = {
0x03ff, 0x0030, 0x07ff, 0x0130, 0x0bff, 0x0230, 0x0fff, 0x0330,
0x13ff, 0x0430, 0x17ff, 0x0530, 0x1bff, 0x0630, 0x1fff, 0x0730,
0x23ff, 0x0830, 0x27ff, 0x0930, 0x2bff, 0x0a30, 0x2fff, 0x0b30,
0x33ff, 0x0c30, 0x37ff, 0x0d30, 0x3bff, 0x0e30, 0x3fff, 0x0f30,
0x43ff, 0x0030, 0x47ff, 0x0130, 0x4bff, 0x0230, 0x4fff, 0x0330,
0x53ff, 0x0430, 0x57ff, 0x0530, 0x5bff, 0x0630, 0x5fff, 0x0730,
0x63ff, 0x0830, 0x67ff, 0x0930, 0x6bff, 0x0a30, 0x6fff, 0x0b30,
0x73ff, 0x0c30, 0x77ff, 0x0d30, 0x7bff, 0x0e30, 0x7fff, 0x0f30,
0x83ff, 0x0030, 0x87ff, 0x0130, 0x8bff, 0x0230, 0x8fff, 0x0330,
0x93ff, 0x0430, 0x97ff, 0x0530, 0x9bff, 0x0630, 0x9fff, 0x0730,
0xa3ff, 0x0830, 0xa7ff, 0x0930, 0xabff, 0x0a30, 0xafff, 0x0b30,
0xb3ff, 0x0c30, 0xb7ff, 0x0d30, 0xbbff, 0x0e30, 0xbfff, 0x0f30,
0xc3ff, 0x0030, 0xc7ff, 0x0130, 0xcbff, 0x0230, 0xcfff, 0x0330,
0xd3ff, 0x0430, 0xd7ff, 0x0530, 0xdbff, 0x0630, 0xdfff, 0x0730,
0xe3ff, 0x0830, 0xe7ff, 0x0930, 0xebff, 0x0a30, 0xefff, 0x0b30,
0xf3ff, 0x0c30, 0xf7ff, 0x0d30, 0xfbff, 0x0e30, 0xffff, 0x0f30,
};
static unsigned short init2[128] = {
0x03ff, 0x8030, 0x07ff, 0x8130, 0x0bff, 0x8230, 0x0fff, 0x8330,
0x13ff, 0x8430, 0x17ff, 0x8530, 0x1bff, 0x8630, 0x1fff, 0x8730,
0x23ff, 0x8830, 0x27ff, 0x8930, 0x2bff, 0x8a30, 0x2fff, 0x8b30,
0x33ff, 0x8c30, 0x37ff, 0x8d30, 0x3bff, 0x8e30, 0x3fff, 0x8f30,
0x43ff, 0x8030, 0x47ff, 0x8130, 0x4bff, 0x8230, 0x4fff, 0x8330,
0x53ff, 0x8430, 0x57ff, 0x8530, 0x5bff, 0x8630, 0x5fff, 0x8730,
0x63ff, 0x8830, 0x67ff, 0x8930, 0x6bff, 0x8a30, 0x6fff, 0x8b30,
0x73ff, 0x8c30, 0x77ff, 0x8d30, 0x7bff, 0x8e30, 0x7fff, 0x8f30,
0x83ff, 0x8030, 0x87ff, 0x8130, 0x8bff, 0x8230, 0x8fff, 0x8330,
0x93ff, 0x8430, 0x97ff, 0x8530, 0x9bff, 0x8630, 0x9fff, 0x8730,
0xa3ff, 0x8830, 0xa7ff, 0x8930, 0xabff, 0x8a30, 0xafff, 0x8b30,
0xb3ff, 0x8c30, 0xb7ff, 0x8d30, 0xbbff, 0x8e30, 0xbfff, 0x8f30,
0xc3ff, 0x8030, 0xc7ff, 0x8130, 0xcbff, 0x8230, 0xcfff, 0x8330,
0xd3ff, 0x8430, 0xd7ff, 0x8530, 0xdbff, 0x8630, 0xdfff, 0x8730,
0xe3ff, 0x8830, 0xe7ff, 0x8930, 0xebff, 0x8a30, 0xefff, 0x8b30,
0xf3ff, 0x8c30, 0xf7ff, 0x8d30, 0xfbff, 0x8e30, 0xffff, 0x8f30,
};
static unsigned short init3[128] = {
0x0C10, 0x8470, 0x14FE, 0xB488, 0x167F, 0xA470, 0x18E7, 0x84B5,
0x1B6E, 0x842A, 0x1F1D, 0x852A, 0x0DA3, 0x8F7C, 0x167E, 0xF254,
0x0000, 0x842A, 0x0001, 0x852A, 0x18E6, 0x8BAA, 0x1B6D, 0xF234,
0x229F, 0x8429, 0x2746, 0x8529, 0x1F1C, 0x86E7, 0x229E, 0xF224,
0x0DA4, 0x8429, 0x2C29, 0x8529, 0x2745, 0x87F6, 0x2C28, 0xF254,
0x383B, 0x8428, 0x320F, 0x8528, 0x320E, 0x8F02, 0x1341, 0xF264,
0x3EB6, 0x8428, 0x3EB9, 0x8528, 0x383A, 0x8FA9, 0x3EB5, 0xF294,
0x3EB7, 0x8474, 0x3EBA, 0x8575, 0x3EB8, 0xC4C3, 0x3EBB, 0xC5C3,
0x0000, 0xA404, 0x0001, 0xA504, 0x141F, 0x8671, 0x14FD, 0x8287,
0x3EBC, 0xE610, 0x3EC8, 0x8C7B, 0x031A, 0x87E6, 0x3EC8, 0x86F7,
0x3EC0, 0x821E, 0x3EBE, 0xD208, 0x3EBD, 0x821F, 0x3ECA, 0x8386,
0x3EC1, 0x8C03, 0x3EC9, 0x831E, 0x3ECA, 0x8C4C, 0x3EBF, 0x8C55,
0x3EC9, 0xC208, 0x3EC4, 0xBC84, 0x3EC8, 0x8EAD, 0x3EC8, 0xD308,
0x3EC2, 0x8F7E, 0x3ECB, 0x8219, 0x3ECB, 0xD26E, 0x3EC5, 0x831F,
0x3EC6, 0xC308, 0x3EC3, 0xB2FF, 0x3EC9, 0x8265, 0x3EC9, 0x8319,
0x1342, 0xD36E, 0x3EC7, 0xB3FF, 0x0000, 0x8365, 0x1420, 0x9570,
};
static unsigned short init4[128] = {
0x0C10, 0x8470, 0x14FE, 0xB488, 0x167F, 0xA470, 0x18E7, 0x84B5,
0x1B6E, 0x842A, 0x1F1D, 0x852A, 0x0DA3, 0x0F7C, 0x167E, 0x7254,
0x0000, 0x842A, 0x0001, 0x852A, 0x18E6, 0x0BAA, 0x1B6D, 0x7234,
0x229F, 0x8429, 0x2746, 0x8529, 0x1F1C, 0x06E7, 0x229E, 0x7224,
0x0DA4, 0x8429, 0x2C29, 0x8529, 0x2745, 0x07F6, 0x2C28, 0x7254,
0x383B, 0x8428, 0x320F, 0x8528, 0x320E, 0x0F02, 0x1341, 0x7264,
0x3EB6, 0x8428, 0x3EB9, 0x8528, 0x383A, 0x0FA9, 0x3EB5, 0x7294,
0x3EB7, 0x8474, 0x3EBA, 0x8575, 0x3EB8, 0x44C3, 0x3EBB, 0x45C3,
0x0000, 0xA404, 0x0001, 0xA504, 0x141F, 0x0671, 0x14FD, 0x0287,
0x3EBC, 0xE610, 0x3EC8, 0x0C7B, 0x031A, 0x07E6, 0x3EC8, 0x86F7,
0x3EC0, 0x821E, 0x3EBE, 0xD208, 0x3EBD, 0x021F, 0x3ECA, 0x0386,
0x3EC1, 0x0C03, 0x3EC9, 0x031E, 0x3ECA, 0x8C4C, 0x3EBF, 0x0C55,
0x3EC9, 0xC208, 0x3EC4, 0xBC84, 0x3EC8, 0x0EAD, 0x3EC8, 0xD308,
0x3EC2, 0x8F7E, 0x3ECB, 0x0219, 0x3ECB, 0xD26E, 0x3EC5, 0x031F,
0x3EC6, 0xC308, 0x3EC3, 0x32FF, 0x3EC9, 0x0265, 0x3EC9, 0x8319,
0x1342, 0xD36E, 0x3EC7, 0x33FF, 0x0000, 0x8365, 0x1420, 0x9570,
};
/* send an initialization array
* Taken from the oss driver, not obvious from the doc how this
* is meant to work
*/
static void __devinit
send_array(struct snd_emu8000 *emu, unsigned short *data, int size)
{
int i;
unsigned short *p;
p = data;
for (i = 0; i < size; i++, p++)
EMU8000_INIT1_WRITE(emu, i, *p);
for (i = 0; i < size; i++, p++)
EMU8000_INIT2_WRITE(emu, i, *p);
for (i = 0; i < size; i++, p++)
EMU8000_INIT3_WRITE(emu, i, *p);
for (i = 0; i < size; i++, p++)
EMU8000_INIT4_WRITE(emu, i, *p);
}
/*
* Send initialization arrays to start up, this just follows the
* initialisation sequence in the adip.
*/
static void __devinit
init_arrays(struct snd_emu8000 *emu)
{
send_array(emu, init1, ARRAY_SIZE(init1)/4);
msleep((1024 * 1000) / 44100); /* wait for 1024 clocks */
send_array(emu, init2, ARRAY_SIZE(init2)/4);
send_array(emu, init3, ARRAY_SIZE(init3)/4);
EMU8000_HWCF4_WRITE(emu, 0);
EMU8000_HWCF5_WRITE(emu, 0x83);
EMU8000_HWCF6_WRITE(emu, 0x8000);
send_array(emu, init4, ARRAY_SIZE(init4)/4);
}
#define UNIQUE_ID1 0xa5b9
#define UNIQUE_ID2 0x9d53
/*
* Size the onboard memory.
* This is written so as not to need arbitary delays after the write. It
* seems that the only way to do this is to use the one channel and keep
* reallocating between read and write.
*/
static void __devinit
size_dram(struct snd_emu8000 *emu)
{
int i, size;
if (emu->dram_checked)
return;
size = 0;
/* write out a magic number */
snd_emu8000_dma_chan(emu, 0, EMU8000_RAM_WRITE);
snd_emu8000_dma_chan(emu, 1, EMU8000_RAM_READ);
EMU8000_SMALW_WRITE(emu, EMU8000_DRAM_OFFSET);
EMU8000_SMLD_WRITE(emu, UNIQUE_ID1);
snd_emu8000_init_fm(emu); /* This must really be here and not 2 lines back even */
while (size < EMU8000_MAX_DRAM) {
size += 512 * 1024; /* increment 512kbytes */
/* Write a unique data on the test address.
* if the address is out of range, the data is written on
* 0x200000(=EMU8000_DRAM_OFFSET). Then the id word is
* changed by this data.
*/
/*snd_emu8000_dma_chan(emu, 0, EMU8000_RAM_WRITE);*/
EMU8000_SMALW_WRITE(emu, EMU8000_DRAM_OFFSET + (size>>1));
EMU8000_SMLD_WRITE(emu, UNIQUE_ID2);
snd_emu8000_write_wait(emu);
/*
* read the data on the just written DRAM address
* if not the same then we have reached the end of ram.
*/
/*snd_emu8000_dma_chan(emu, 0, EMU8000_RAM_READ);*/
EMU8000_SMALR_WRITE(emu, EMU8000_DRAM_OFFSET + (size>>1));
/*snd_emu8000_read_wait(emu);*/
EMU8000_SMLD_READ(emu); /* discard stale data */
if (EMU8000_SMLD_READ(emu) != UNIQUE_ID2)
break; /* we must have wrapped around */
snd_emu8000_read_wait(emu);
/*
* If it is the same it could be that the address just
* wraps back to the beginning; so check to see if the
* initial value has been overwritten.
*/
EMU8000_SMALR_WRITE(emu, EMU8000_DRAM_OFFSET);
EMU8000_SMLD_READ(emu); /* discard stale data */
if (EMU8000_SMLD_READ(emu) != UNIQUE_ID1)
break; /* we must have wrapped around */
snd_emu8000_read_wait(emu);
}
/* wait until FULL bit in SMAxW register is false */
for (i = 0; i < 10000; i++) {
if ((EMU8000_SMALW_READ(emu) & 0x80000000) == 0)
break;
schedule_timeout_interruptible(1);
if (signal_pending(current))
break;
}
snd_emu8000_dma_chan(emu, 0, EMU8000_RAM_CLOSE);
snd_emu8000_dma_chan(emu, 1, EMU8000_RAM_CLOSE);
snd_printdd("EMU8000 [0x%lx]: %d Kb on-board memory detected\n",
emu->port1, size/1024);
emu->mem_size = size;
emu->dram_checked = 1;
}
/*
* Initiailise the FM section. You have to do this to use sample RAM
* and therefore lose 2 voices.
*/
/*exported*/ void
snd_emu8000_init_fm(struct snd_emu8000 *emu)
{
unsigned long flags;
/* Initialize the last two channels for DRAM refresh and producing
the reverb and chorus effects for Yamaha OPL-3 synthesizer */
/* 31: FM left channel, 0xffffe0-0xffffe8 */
EMU8000_DCYSUSV_WRITE(emu, 30, 0x80);
EMU8000_PSST_WRITE(emu, 30, 0xFFFFFFE0); /* full left */
EMU8000_CSL_WRITE(emu, 30, 0x00FFFFE8 | (emu->fm_chorus_depth << 24));
EMU8000_PTRX_WRITE(emu, 30, (emu->fm_reverb_depth << 8));
EMU8000_CPF_WRITE(emu, 30, 0);
EMU8000_CCCA_WRITE(emu, 30, 0x00FFFFE3);
/* 32: FM right channel, 0xfffff0-0xfffff8 */
EMU8000_DCYSUSV_WRITE(emu, 31, 0x80);
EMU8000_PSST_WRITE(emu, 31, 0x00FFFFF0); /* full right */
EMU8000_CSL_WRITE(emu, 31, 0x00FFFFF8 | (emu->fm_chorus_depth << 24));
EMU8000_PTRX_WRITE(emu, 31, (emu->fm_reverb_depth << 8));
EMU8000_CPF_WRITE(emu, 31, 0x8000);
EMU8000_CCCA_WRITE(emu, 31, 0x00FFFFF3);
snd_emu8000_poke((emu), EMU8000_DATA0(emu), EMU8000_CMD(1, (30)), 0);
spin_lock_irqsave(&emu->reg_lock, flags);
while (!(inw(EMU8000_PTR(emu)) & 0x1000))
;
while ((inw(EMU8000_PTR(emu)) & 0x1000))
;
spin_unlock_irqrestore(&emu->reg_lock, flags);
snd_emu8000_poke((emu), EMU8000_DATA0(emu), EMU8000_CMD(1, (30)), 0x4828);
/* this is really odd part.. */
outb(0x3C, EMU8000_PTR(emu));
outb(0, EMU8000_DATA1(emu));
/* skew volume & cutoff */
EMU8000_VTFT_WRITE(emu, 30, 0x8000FFFF);
EMU8000_VTFT_WRITE(emu, 31, 0x8000FFFF);
}
/*
* The main initialization routine.
*/
static void __devinit
snd_emu8000_init_hw(struct snd_emu8000 *emu)
{
int i;
emu->last_reg = 0xffff; /* reset the last register index */
/* initialize hardware configuration */
EMU8000_HWCF1_WRITE(emu, 0x0059);
EMU8000_HWCF2_WRITE(emu, 0x0020);
/* disable audio; this seems to reduce a clicking noise a bit.. */
EMU8000_HWCF3_WRITE(emu, 0);
/* initialize audio channels */
init_audio(emu);
/* initialize DMA */
init_dma(emu);
/* initialize init arrays */
init_arrays(emu);
/*
* Initialize the FM section of the AWE32, this is needed
* for DRAM refresh as well
*/
snd_emu8000_init_fm(emu);
/* terminate all voices */
for (i = 0; i < EMU8000_DRAM_VOICES; i++)
EMU8000_DCYSUSV_WRITE(emu, 0, 0x807F);
/* check DRAM memory size */
size_dram(emu);
/* enable audio */
EMU8000_HWCF3_WRITE(emu, 0x4);
/* set equzlier, chorus and reverb modes */
snd_emu8000_update_equalizer(emu);
snd_emu8000_update_chorus_mode(emu);
snd_emu8000_update_reverb_mode(emu);
}
/*----------------------------------------------------------------
* Bass/Treble Equalizer
*----------------------------------------------------------------*/
static unsigned short bass_parm[12][3] = {
{0xD26A, 0xD36A, 0x0000}, /* -12 dB */
{0xD25B, 0xD35B, 0x0000}, /* -8 */
{0xD24C, 0xD34C, 0x0000}, /* -6 */
{0xD23D, 0xD33D, 0x0000}, /* -4 */
{0xD21F, 0xD31F, 0x0000}, /* -2 */
{0xC208, 0xC308, 0x0001}, /* 0 (HW default) */
{0xC219, 0xC319, 0x0001}, /* +2 */
{0xC22A, 0xC32A, 0x0001}, /* +4 */
{0xC24C, 0xC34C, 0x0001}, /* +6 */
{0xC26E, 0xC36E, 0x0001}, /* +8 */
{0xC248, 0xC384, 0x0002}, /* +10 */
{0xC26A, 0xC36A, 0x0002}, /* +12 dB */
};
static unsigned short treble_parm[12][9] = {
{0x821E, 0xC26A, 0x031E, 0xC36A, 0x021E, 0xD208, 0x831E, 0xD308, 0x0001}, /* -12 dB */
{0x821E, 0xC25B, 0x031E, 0xC35B, 0x021E, 0xD208, 0x831E, 0xD308, 0x0001},
{0x821E, 0xC24C, 0x031E, 0xC34C, 0x021E, 0xD208, 0x831E, 0xD308, 0x0001},
{0x821E, 0xC23D, 0x031E, 0xC33D, 0x021E, 0xD208, 0x831E, 0xD308, 0x0001},
{0x821E, 0xC21F, 0x031E, 0xC31F, 0x021E, 0xD208, 0x831E, 0xD308, 0x0001},
{0x821E, 0xD208, 0x031E, 0xD308, 0x021E, 0xD208, 0x831E, 0xD308, 0x0002},
{0x821E, 0xD208, 0x031E, 0xD308, 0x021D, 0xD219, 0x831D, 0xD319, 0x0002},
{0x821E, 0xD208, 0x031E, 0xD308, 0x021C, 0xD22A, 0x831C, 0xD32A, 0x0002},
{0x821E, 0xD208, 0x031E, 0xD308, 0x021A, 0xD24C, 0x831A, 0xD34C, 0x0002},
{0x821E, 0xD208, 0x031E, 0xD308, 0x0219, 0xD26E, 0x8319, 0xD36E, 0x0002}, /* +8 (HW default) */
{0x821D, 0xD219, 0x031D, 0xD319, 0x0219, 0xD26E, 0x8319, 0xD36E, 0x0002},
{0x821C, 0xD22A, 0x031C, 0xD32A, 0x0219, 0xD26E, 0x8319, 0xD36E, 0x0002} /* +12 dB */
};
/*
* set Emu8000 digital equalizer; from 0 to 11 [-12dB - 12dB]
*/
/*exported*/ void
snd_emu8000_update_equalizer(struct snd_emu8000 *emu)
{
unsigned short w;
int bass = emu->bass_level;
int treble = emu->treble_level;
if (bass < 0 || bass > 11 || treble < 0 || treble > 11)
return;
EMU8000_INIT4_WRITE(emu, 0x01, bass_parm[bass][0]);
EMU8000_INIT4_WRITE(emu, 0x11, bass_parm[bass][1]);
EMU8000_INIT3_WRITE(emu, 0x11, treble_parm[treble][0]);
EMU8000_INIT3_WRITE(emu, 0x13, treble_parm[treble][1]);
EMU8000_INIT3_WRITE(emu, 0x1b, treble_parm[treble][2]);
EMU8000_INIT4_WRITE(emu, 0x07, treble_parm[treble][3]);
EMU8000_INIT4_WRITE(emu, 0x0b, treble_parm[treble][4]);
EMU8000_INIT4_WRITE(emu, 0x0d, treble_parm[treble][5]);
EMU8000_INIT4_WRITE(emu, 0x17, treble_parm[treble][6]);
EMU8000_INIT4_WRITE(emu, 0x19, treble_parm[treble][7]);
w = bass_parm[bass][2] + treble_parm[treble][8];
EMU8000_INIT4_WRITE(emu, 0x15, (unsigned short)(w + 0x0262));
EMU8000_INIT4_WRITE(emu, 0x1d, (unsigned short)(w + 0x8362));
}
/*----------------------------------------------------------------
* Chorus mode control
*----------------------------------------------------------------*/
/*
* chorus mode parameters
*/
#define SNDRV_EMU8000_CHORUS_1 0
#define SNDRV_EMU8000_CHORUS_2 1
#define SNDRV_EMU8000_CHORUS_3 2
#define SNDRV_EMU8000_CHORUS_4 3
#define SNDRV_EMU8000_CHORUS_FEEDBACK 4
#define SNDRV_EMU8000_CHORUS_FLANGER 5
#define SNDRV_EMU8000_CHORUS_SHORTDELAY 6
#define SNDRV_EMU8000_CHORUS_SHORTDELAY2 7
#define SNDRV_EMU8000_CHORUS_PREDEFINED 8
/* user can define chorus modes up to 32 */
#define SNDRV_EMU8000_CHORUS_NUMBERS 32
struct soundfont_chorus_fx {
unsigned short feedback; /* feedback level (0xE600-0xE6FF) */
unsigned short delay_offset; /* delay (0-0x0DA3) [1/44100 sec] */
unsigned short lfo_depth; /* LFO depth (0xBC00-0xBCFF) */
unsigned int delay; /* right delay (0-0xFFFFFFFF) [1/256/44100 sec] */
unsigned int lfo_freq; /* LFO freq LFO freq (0-0xFFFFFFFF) */
};
/* 5 parameters for each chorus mode; 3 x 16bit, 2 x 32bit */
static char chorus_defined[SNDRV_EMU8000_CHORUS_NUMBERS];
static struct soundfont_chorus_fx chorus_parm[SNDRV_EMU8000_CHORUS_NUMBERS] = {
{0xE600, 0x03F6, 0xBC2C ,0x00000000, 0x0000006D}, /* chorus 1 */
{0xE608, 0x031A, 0xBC6E, 0x00000000, 0x0000017C}, /* chorus 2 */
{0xE610, 0x031A, 0xBC84, 0x00000000, 0x00000083}, /* chorus 3 */
{0xE620, 0x0269, 0xBC6E, 0x00000000, 0x0000017C}, /* chorus 4 */
{0xE680, 0x04D3, 0xBCA6, 0x00000000, 0x0000005B}, /* feedback */
{0xE6E0, 0x044E, 0xBC37, 0x00000000, 0x00000026}, /* flanger */
{0xE600, 0x0B06, 0xBC00, 0x0006E000, 0x00000083}, /* short delay */
{0xE6C0, 0x0B06, 0xBC00, 0x0006E000, 0x00000083}, /* short delay + feedback */
};
/*exported*/ int
snd_emu8000_load_chorus_fx(struct snd_emu8000 *emu, int mode, const void __user *buf, long len)
{
struct soundfont_chorus_fx rec;
if (mode < SNDRV_EMU8000_CHORUS_PREDEFINED || mode >= SNDRV_EMU8000_CHORUS_NUMBERS) {
snd_printk(KERN_WARNING "invalid chorus mode %d for uploading\n", mode);
return -EINVAL;
}
if (len < (long)sizeof(rec) || copy_from_user(&rec, buf, sizeof(rec)))
return -EFAULT;
chorus_parm[mode] = rec;
chorus_defined[mode] = 1;
return 0;
}
/*exported*/ void
snd_emu8000_update_chorus_mode(struct snd_emu8000 *emu)
{
int effect = emu->chorus_mode;
if (effect < 0 || effect >= SNDRV_EMU8000_CHORUS_NUMBERS ||
(effect >= SNDRV_EMU8000_CHORUS_PREDEFINED && !chorus_defined[effect]))
return;
EMU8000_INIT3_WRITE(emu, 0x09, chorus_parm[effect].feedback);
EMU8000_INIT3_WRITE(emu, 0x0c, chorus_parm[effect].delay_offset);
EMU8000_INIT4_WRITE(emu, 0x03, chorus_parm[effect].lfo_depth);
EMU8000_HWCF4_WRITE(emu, chorus_parm[effect].delay);
EMU8000_HWCF5_WRITE(emu, chorus_parm[effect].lfo_freq);
EMU8000_HWCF6_WRITE(emu, 0x8000);
EMU8000_HWCF7_WRITE(emu, 0x0000);
}
/*----------------------------------------------------------------
* Reverb mode control
*----------------------------------------------------------------*/
/*
* reverb mode parameters
*/
#define SNDRV_EMU8000_REVERB_ROOM1 0
#define SNDRV_EMU8000_REVERB_ROOM2 1
#define SNDRV_EMU8000_REVERB_ROOM3 2
#define SNDRV_EMU8000_REVERB_HALL1 3
#define SNDRV_EMU8000_REVERB_HALL2 4
#define SNDRV_EMU8000_REVERB_PLATE 5
#define SNDRV_EMU8000_REVERB_DELAY 6
#define SNDRV_EMU8000_REVERB_PANNINGDELAY 7
#define SNDRV_EMU8000_REVERB_PREDEFINED 8
/* user can define reverb modes up to 32 */
#define SNDRV_EMU8000_REVERB_NUMBERS 32
struct soundfont_reverb_fx {
unsigned short parms[28];
};
/* reverb mode settings; write the following 28 data of 16 bit length
* on the corresponding ports in the reverb_cmds array
*/
static char reverb_defined[SNDRV_EMU8000_CHORUS_NUMBERS];
static struct soundfont_reverb_fx reverb_parm[SNDRV_EMU8000_REVERB_NUMBERS] = {
{{ /* room 1 */
0xB488, 0xA450, 0x9550, 0x84B5, 0x383A, 0x3EB5, 0x72F4,
0x72A4, 0x7254, 0x7204, 0x7204, 0x7204, 0x4416, 0x4516,
0xA490, 0xA590, 0x842A, 0x852A, 0x842A, 0x852A, 0x8429,
0x8529, 0x8429, 0x8529, 0x8428, 0x8528, 0x8428, 0x8528,
}},
{{ /* room 2 */
0xB488, 0xA458, 0x9558, 0x84B5, 0x383A, 0x3EB5, 0x7284,
0x7254, 0x7224, 0x7224, 0x7254, 0x7284, 0x4448, 0x4548,
0xA440, 0xA540, 0x842A, 0x852A, 0x842A, 0x852A, 0x8429,
0x8529, 0x8429, 0x8529, 0x8428, 0x8528, 0x8428, 0x8528,
}},
{{ /* room 3 */
0xB488, 0xA460, 0x9560, 0x84B5, 0x383A, 0x3EB5, 0x7284,
0x7254, 0x7224, 0x7224, 0x7254, 0x7284, 0x4416, 0x4516,
0xA490, 0xA590, 0x842C, 0x852C, 0x842C, 0x852C, 0x842B,
0x852B, 0x842B, 0x852B, 0x842A, 0x852A, 0x842A, 0x852A,
}},
{{ /* hall 1 */
0xB488, 0xA470, 0x9570, 0x84B5, 0x383A, 0x3EB5, 0x7284,
0x7254, 0x7224, 0x7224, 0x7254, 0x7284, 0x4448, 0x4548,
0xA440, 0xA540, 0x842B, 0x852B, 0x842B, 0x852B, 0x842A,
0x852A, 0x842A, 0x852A, 0x8429, 0x8529, 0x8429, 0x8529,
}},
{{ /* hall 2 */
0xB488, 0xA470, 0x9570, 0x84B5, 0x383A, 0x3EB5, 0x7254,
0x7234, 0x7224, 0x7254, 0x7264, 0x7294, 0x44C3, 0x45C3,
0xA404, 0xA504, 0x842A, 0x852A, 0x842A, 0x852A, 0x8429,
0x8529, 0x8429, 0x8529, 0x8428, 0x8528, 0x8428, 0x8528,
}},
{{ /* plate */
0xB4FF, 0xA470, 0x9570, 0x84B5, 0x383A, 0x3EB5, 0x7234,
0x7234, 0x7234, 0x7234, 0x7234, 0x7234, 0x4448, 0x4548,
0xA440, 0xA540, 0x842A, 0x852A, 0x842A, 0x852A, 0x8429,
0x8529, 0x8429, 0x8529, 0x8428, 0x8528, 0x8428, 0x8528,
}},
{{ /* delay */
0xB4FF, 0xA470, 0x9500, 0x84B5, 0x333A, 0x39B5, 0x7204,
0x7204, 0x7204, 0x7204, 0x7204, 0x72F4, 0x4400, 0x4500,
0xA4FF, 0xA5FF, 0x8420, 0x8520, 0x8420, 0x8520, 0x8420,
0x8520, 0x8420, 0x8520, 0x8420, 0x8520, 0x8420, 0x8520,
}},
{{ /* panning delay */
0xB4FF, 0xA490, 0x9590, 0x8474, 0x333A, 0x39B5, 0x7204,
0x7204, 0x7204, 0x7204, 0x7204, 0x72F4, 0x4400, 0x4500,
0xA4FF, 0xA5FF, 0x8420, 0x8520, 0x8420, 0x8520, 0x8420,
0x8520, 0x8420, 0x8520, 0x8420, 0x8520, 0x8420, 0x8520,
}},
};
enum { DATA1, DATA2 };
#define AWE_INIT1(c) EMU8000_CMD(2,c), DATA1
#define AWE_INIT2(c) EMU8000_CMD(2,c), DATA2
#define AWE_INIT3(c) EMU8000_CMD(3,c), DATA1
#define AWE_INIT4(c) EMU8000_CMD(3,c), DATA2
static struct reverb_cmd_pair {
unsigned short cmd, port;
} reverb_cmds[28] = {
{AWE_INIT1(0x03)}, {AWE_INIT1(0x05)}, {AWE_INIT4(0x1F)}, {AWE_INIT1(0x07)},
{AWE_INIT2(0x14)}, {AWE_INIT2(0x16)}, {AWE_INIT1(0x0F)}, {AWE_INIT1(0x17)},
{AWE_INIT1(0x1F)}, {AWE_INIT2(0x07)}, {AWE_INIT2(0x0F)}, {AWE_INIT2(0x17)},
{AWE_INIT2(0x1D)}, {AWE_INIT2(0x1F)}, {AWE_INIT3(0x01)}, {AWE_INIT3(0x03)},
{AWE_INIT1(0x09)}, {AWE_INIT1(0x0B)}, {AWE_INIT1(0x11)}, {AWE_INIT1(0x13)},
{AWE_INIT1(0x19)}, {AWE_INIT1(0x1B)}, {AWE_INIT2(0x01)}, {AWE_INIT2(0x03)},
{AWE_INIT2(0x09)}, {AWE_INIT2(0x0B)}, {AWE_INIT2(0x11)}, {AWE_INIT2(0x13)},
};
/*exported*/ int
snd_emu8000_load_reverb_fx(struct snd_emu8000 *emu, int mode, const void __user *buf, long len)
{
struct soundfont_reverb_fx rec;
if (mode < SNDRV_EMU8000_REVERB_PREDEFINED || mode >= SNDRV_EMU8000_REVERB_NUMBERS) {
snd_printk(KERN_WARNING "invalid reverb mode %d for uploading\n", mode);
return -EINVAL;
}
if (len < (long)sizeof(rec) || copy_from_user(&rec, buf, sizeof(rec)))
return -EFAULT;
reverb_parm[mode] = rec;
reverb_defined[mode] = 1;
return 0;
}
/*exported*/ void
snd_emu8000_update_reverb_mode(struct snd_emu8000 *emu)
{
int effect = emu->reverb_mode;
int i;
if (effect < 0 || effect >= SNDRV_EMU8000_REVERB_NUMBERS ||
(effect >= SNDRV_EMU8000_REVERB_PREDEFINED && !reverb_defined[effect]))
return;
for (i = 0; i < 28; i++) {
int port;
if (reverb_cmds[i].port == DATA1)
port = EMU8000_DATA1(emu);
else
port = EMU8000_DATA2(emu);
snd_emu8000_poke(emu, port, reverb_cmds[i].cmd, reverb_parm[effect].parms[i]);
}
}
/*----------------------------------------------------------------
* mixer interface
*----------------------------------------------------------------*/
/*
* bass/treble
*/
static int mixer_bass_treble_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 11;
return 0;
}
static int mixer_bass_treble_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu8000 *emu = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = kcontrol->private_value ? emu->treble_level : emu->bass_level;
return 0;
}
static int mixer_bass_treble_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu8000 *emu = snd_kcontrol_chip(kcontrol);
unsigned long flags;
int change;
unsigned short val1;
val1 = ucontrol->value.integer.value[0] % 12;
spin_lock_irqsave(&emu->control_lock, flags);
if (kcontrol->private_value) {
change = val1 != emu->treble_level;
emu->treble_level = val1;
} else {
change = val1 != emu->bass_level;
emu->bass_level = val1;
}
spin_unlock_irqrestore(&emu->control_lock, flags);
snd_emu8000_update_equalizer(emu);
return change;
}
static struct snd_kcontrol_new mixer_bass_control =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Synth Tone Control - Bass",
.info = mixer_bass_treble_info,
.get = mixer_bass_treble_get,
.put = mixer_bass_treble_put,
.private_value = 0,
};
static struct snd_kcontrol_new mixer_treble_control =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Synth Tone Control - Treble",
.info = mixer_bass_treble_info,
.get = mixer_bass_treble_get,
.put = mixer_bass_treble_put,
.private_value = 1,
};
/*
* chorus/reverb mode
*/
static int mixer_chorus_reverb_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = kcontrol->private_value ? (SNDRV_EMU8000_CHORUS_NUMBERS-1) : (SNDRV_EMU8000_REVERB_NUMBERS-1);
return 0;
}
static int mixer_chorus_reverb_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu8000 *emu = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = kcontrol->private_value ? emu->chorus_mode : emu->reverb_mode;
return 0;
}
static int mixer_chorus_reverb_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu8000 *emu = snd_kcontrol_chip(kcontrol);
unsigned long flags;
int change;
unsigned short val1;
spin_lock_irqsave(&emu->control_lock, flags);
if (kcontrol->private_value) {
val1 = ucontrol->value.integer.value[0] % SNDRV_EMU8000_CHORUS_NUMBERS;
change = val1 != emu->chorus_mode;
emu->chorus_mode = val1;
} else {
val1 = ucontrol->value.integer.value[0] % SNDRV_EMU8000_REVERB_NUMBERS;
change = val1 != emu->reverb_mode;
emu->reverb_mode = val1;
}
spin_unlock_irqrestore(&emu->control_lock, flags);
if (change) {
if (kcontrol->private_value)
snd_emu8000_update_chorus_mode(emu);
else
snd_emu8000_update_reverb_mode(emu);
}
return change;
}
static struct snd_kcontrol_new mixer_chorus_mode_control =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Chorus Mode",
.info = mixer_chorus_reverb_info,
.get = mixer_chorus_reverb_get,
.put = mixer_chorus_reverb_put,
.private_value = 1,
};
static struct snd_kcontrol_new mixer_reverb_mode_control =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Reverb Mode",
.info = mixer_chorus_reverb_info,
.get = mixer_chorus_reverb_get,
.put = mixer_chorus_reverb_put,
.private_value = 0,
};
/*
* FM OPL3 chorus/reverb depth
*/
static int mixer_fm_depth_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 255;
return 0;
}
static int mixer_fm_depth_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu8000 *emu = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = kcontrol->private_value ? emu->fm_chorus_depth : emu->fm_reverb_depth;
return 0;
}
static int mixer_fm_depth_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu8000 *emu = snd_kcontrol_chip(kcontrol);
unsigned long flags;
int change;
unsigned short val1;
val1 = ucontrol->value.integer.value[0] % 256;
spin_lock_irqsave(&emu->control_lock, flags);
if (kcontrol->private_value) {
change = val1 != emu->fm_chorus_depth;
emu->fm_chorus_depth = val1;
} else {
change = val1 != emu->fm_reverb_depth;
emu->fm_reverb_depth = val1;
}
spin_unlock_irqrestore(&emu->control_lock, flags);
if (change)
snd_emu8000_init_fm(emu);
return change;
}
static struct snd_kcontrol_new mixer_fm_chorus_depth_control =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "FM Chorus Depth",
.info = mixer_fm_depth_info,
.get = mixer_fm_depth_get,
.put = mixer_fm_depth_put,
.private_value = 1,
};
static struct snd_kcontrol_new mixer_fm_reverb_depth_control =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "FM Reverb Depth",
.info = mixer_fm_depth_info,
.get = mixer_fm_depth_get,
.put = mixer_fm_depth_put,
.private_value = 0,
};
static struct snd_kcontrol_new *mixer_defs[EMU8000_NUM_CONTROLS] = {
&mixer_bass_control,
&mixer_treble_control,
&mixer_chorus_mode_control,
&mixer_reverb_mode_control,
&mixer_fm_chorus_depth_control,
&mixer_fm_reverb_depth_control,
};
/*
* create and attach mixer elements for WaveTable treble/bass controls
*/
static int __devinit
snd_emu8000_create_mixer(struct snd_card *card, struct snd_emu8000 *emu)
{
int i, err = 0;
if (snd_BUG_ON(!emu || !card))
return -EINVAL;
spin_lock_init(&emu->control_lock);
memset(emu->controls, 0, sizeof(emu->controls));
for (i = 0; i < EMU8000_NUM_CONTROLS; i++) {
if ((err = snd_ctl_add(card, emu->controls[i] = snd_ctl_new1(mixer_defs[i], emu))) < 0)
goto __error;
}
return 0;
__error:
for (i = 0; i < EMU8000_NUM_CONTROLS; i++) {
down_write(&card->controls_rwsem);
if (emu->controls[i])
snd_ctl_remove(card, emu->controls[i]);
up_write(&card->controls_rwsem);
}
return err;
}
/*
* free resources
*/
static int snd_emu8000_free(struct snd_emu8000 *hw)
{
release_and_free_resource(hw->res_port1);
release_and_free_resource(hw->res_port2);
release_and_free_resource(hw->res_port3);
kfree(hw);
return 0;
}
/*
*/
static int snd_emu8000_dev_free(struct snd_device *device)
{
struct snd_emu8000 *hw = device->device_data;
return snd_emu8000_free(hw);
}
/*
* initialize and register emu8000 synth device.
*/
int __devinit
snd_emu8000_new(struct snd_card *card, int index, long port, int seq_ports,
struct snd_seq_device **awe_ret)
{
struct snd_seq_device *awe;
struct snd_emu8000 *hw;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_emu8000_dev_free,
};
if (awe_ret)
*awe_ret = NULL;
if (seq_ports <= 0)
return 0;
hw = kzalloc(sizeof(*hw), GFP_KERNEL);
if (hw == NULL)
return -ENOMEM;
spin_lock_init(&hw->reg_lock);
hw->index = index;
hw->port1 = port;
hw->port2 = port + 0x400;
hw->port3 = port + 0x800;
if (!(hw->res_port1 = request_region(hw->port1, 4, "Emu8000-1")) ||
!(hw->res_port2 = request_region(hw->port2, 4, "Emu8000-2")) ||
!(hw->res_port3 = request_region(hw->port3, 4, "Emu8000-3"))) {
snd_printk(KERN_ERR "sbawe: can't grab ports 0x%lx, 0x%lx, 0x%lx\n", hw->port1, hw->port2, hw->port3);
snd_emu8000_free(hw);
return -EBUSY;
}
hw->mem_size = 0;
hw->card = card;
hw->seq_ports = seq_ports;
hw->bass_level = 5;
hw->treble_level = 9;
hw->chorus_mode = 2;
hw->reverb_mode = 4;
hw->fm_chorus_depth = 0;
hw->fm_reverb_depth = 0;
if (snd_emu8000_detect(hw) < 0) {
snd_emu8000_free(hw);
return -ENODEV;
}
snd_emu8000_init_hw(hw);
if ((err = snd_emu8000_create_mixer(card, hw)) < 0) {
snd_emu8000_free(hw);
return err;
}
if ((err = snd_device_new(card, SNDRV_DEV_CODEC, hw, &ops)) < 0) {
snd_emu8000_free(hw);
return err;
}
#if defined(CONFIG_SND_SEQUENCER) || (defined(MODULE) && defined(CONFIG_SND_SEQUENCER_MODULE))
if (snd_seq_device_new(card, index, SNDRV_SEQ_DEV_ID_EMU8000,
sizeof(struct snd_emu8000*), &awe) >= 0) {
strcpy(awe->name, "EMU-8000");
*(struct snd_emu8000 **)SNDRV_SEQ_DEVICE_ARGPTR(awe) = hw;
}
#else
awe = NULL;
#endif
if (awe_ret)
*awe_ret = awe;
return 0;
}
/*
* exported stuff
*/
EXPORT_SYMBOL(snd_emu8000_poke);
EXPORT_SYMBOL(snd_emu8000_peek);
EXPORT_SYMBOL(snd_emu8000_poke_dw);
EXPORT_SYMBOL(snd_emu8000_peek_dw);
EXPORT_SYMBOL(snd_emu8000_dma_chan);
EXPORT_SYMBOL(snd_emu8000_init_fm);
EXPORT_SYMBOL(snd_emu8000_load_chorus_fx);
EXPORT_SYMBOL(snd_emu8000_load_reverb_fx);
EXPORT_SYMBOL(snd_emu8000_update_chorus_mode);
EXPORT_SYMBOL(snd_emu8000_update_reverb_mode);
EXPORT_SYMBOL(snd_emu8000_update_equalizer);
| kofemann/linux-redpatch | sound/isa/sb/emu8000.c | C | gpl-2.0 | 36,373 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Netscape Portable Runtime (NSPR).
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
** PR Atomic operations
*/
#include "pratom.h"
#include "primpl.h"
#include <string.h>
/*
* The following is a fallback implementation that emulates
* atomic operations for platforms without atomic operations.
* If a platform has atomic operations, it should define the
* macro _PR_HAVE_ATOMIC_OPS, and the following will not be
* compiled in.
*/
#if !defined(_PR_HAVE_ATOMIC_OPS)
#if defined(_PR_PTHREADS) && !defined(_PR_DCETHREADS)
/*
* PR_AtomicDecrement() is used in NSPR's thread-specific data
* destructor. Because thread-specific data destructors may be
* invoked after a PR_Cleanup() call, we need an implementation
* of the atomic routines that doesn't need NSPR to be initialized.
*/
/*
* We use a set of locks for all the emulated atomic operations.
* By hashing on the address of the integer to be locked the
* contention between multiple threads should be lessened.
*
* The number of atomic locks can be set by the environment variable
* NSPR_ATOMIC_HASH_LOCKS
*/
/*
* lock counts should be a power of 2
*/
#define DEFAULT_ATOMIC_LOCKS 16 /* should be in sync with the number of initializers
below */
#define MAX_ATOMIC_LOCKS (4 * 1024)
static pthread_mutex_t static_atomic_locks[DEFAULT_ATOMIC_LOCKS] = {
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER };
#ifdef DEBUG
static PRInt32 static_hash_lock_counts[DEFAULT_ATOMIC_LOCKS];
static PRInt32 *hash_lock_counts = static_hash_lock_counts;
#endif
static PRUint32 num_atomic_locks = DEFAULT_ATOMIC_LOCKS;
static pthread_mutex_t *atomic_locks = static_atomic_locks;
static PRUint32 atomic_hash_mask = DEFAULT_ATOMIC_LOCKS - 1;
#define _PR_HASH_FOR_LOCK(ptr) \
((PRUint32) (((PRUptrdiff) (ptr) >> 2) ^ \
((PRUptrdiff) (ptr) >> 8)) & \
atomic_hash_mask)
void _PR_MD_INIT_ATOMIC()
{
char *eval;
int index;
PR_ASSERT(PR_FloorLog2(MAX_ATOMIC_LOCKS) ==
PR_CeilingLog2(MAX_ATOMIC_LOCKS));
PR_ASSERT(PR_FloorLog2(DEFAULT_ATOMIC_LOCKS) ==
PR_CeilingLog2(DEFAULT_ATOMIC_LOCKS));
if (((eval = getenv("NSPR_ATOMIC_HASH_LOCKS")) != NULL) &&
((num_atomic_locks = atoi(eval)) != DEFAULT_ATOMIC_LOCKS)) {
if (num_atomic_locks > MAX_ATOMIC_LOCKS)
num_atomic_locks = MAX_ATOMIC_LOCKS;
else {
num_atomic_locks = PR_FloorLog2(num_atomic_locks);
num_atomic_locks = 1L << num_atomic_locks;
}
atomic_locks = (pthread_mutex_t *) PR_Malloc(sizeof(pthread_mutex_t) *
num_atomic_locks);
if (atomic_locks) {
for (index = 0; index < num_atomic_locks; index++) {
if (pthread_mutex_init(&atomic_locks[index], NULL)) {
PR_DELETE(atomic_locks);
atomic_locks = NULL;
break;
}
}
}
#ifdef DEBUG
if (atomic_locks) {
hash_lock_counts = PR_CALLOC(num_atomic_locks * sizeof(PRInt32));
if (hash_lock_counts == NULL) {
PR_DELETE(atomic_locks);
atomic_locks = NULL;
}
}
#endif
if (atomic_locks == NULL) {
/*
* Use statically allocated locks
*/
atomic_locks = static_atomic_locks;
num_atomic_locks = DEFAULT_ATOMIC_LOCKS;
#ifdef DEBUG
hash_lock_counts = static_hash_lock_counts;
#endif
}
atomic_hash_mask = num_atomic_locks - 1;
}
PR_ASSERT(PR_FloorLog2(num_atomic_locks) ==
PR_CeilingLog2(num_atomic_locks));
}
PRInt32
_PR_MD_ATOMIC_INCREMENT(PRInt32 *val)
{
PRInt32 rv;
PRInt32 idx = _PR_HASH_FOR_LOCK(val);
pthread_mutex_lock(&atomic_locks[idx]);
rv = ++(*val);
#ifdef DEBUG
hash_lock_counts[idx]++;
#endif
pthread_mutex_unlock(&atomic_locks[idx]);
return rv;
}
PRInt32
_PR_MD_ATOMIC_ADD(PRInt32 *ptr, PRInt32 val)
{
PRInt32 rv;
PRInt32 idx = _PR_HASH_FOR_LOCK(ptr);
pthread_mutex_lock(&atomic_locks[idx]);
rv = ((*ptr) += val);
#ifdef DEBUG
hash_lock_counts[idx]++;
#endif
pthread_mutex_unlock(&atomic_locks[idx]);
return rv;
}
PRInt32
_PR_MD_ATOMIC_DECREMENT(PRInt32 *val)
{
PRInt32 rv;
PRInt32 idx = _PR_HASH_FOR_LOCK(val);
pthread_mutex_lock(&atomic_locks[idx]);
rv = --(*val);
#ifdef DEBUG
hash_lock_counts[idx]++;
#endif
pthread_mutex_unlock(&atomic_locks[idx]);
return rv;
}
PRInt32
_PR_MD_ATOMIC_SET(PRInt32 *val, PRInt32 newval)
{
PRInt32 rv;
PRInt32 idx = _PR_HASH_FOR_LOCK(val);
pthread_mutex_lock(&atomic_locks[idx]);
rv = *val;
*val = newval;
#ifdef DEBUG
hash_lock_counts[idx]++;
#endif
pthread_mutex_unlock(&atomic_locks[idx]);
return rv;
}
#else /* _PR_PTHREADS && !_PR_DCETHREADS */
/*
* We use a single lock for all the emulated atomic operations.
* The lock contention should be acceptable.
*/
static PRLock *atomic_lock = NULL;
void _PR_MD_INIT_ATOMIC(void)
{
if (atomic_lock == NULL) {
atomic_lock = PR_NewLock();
}
}
PRInt32
_PR_MD_ATOMIC_INCREMENT(PRInt32 *val)
{
PRInt32 rv;
if (!_pr_initialized) {
_PR_ImplicitInitialization();
}
PR_Lock(atomic_lock);
rv = ++(*val);
PR_Unlock(atomic_lock);
return rv;
}
PRInt32
_PR_MD_ATOMIC_ADD(PRInt32 *ptr, PRInt32 val)
{
PRInt32 rv;
if (!_pr_initialized) {
_PR_ImplicitInitialization();
}
PR_Lock(atomic_lock);
rv = ((*ptr) += val);
PR_Unlock(atomic_lock);
return rv;
}
PRInt32
_PR_MD_ATOMIC_DECREMENT(PRInt32 *val)
{
PRInt32 rv;
if (!_pr_initialized) {
_PR_ImplicitInitialization();
}
PR_Lock(atomic_lock);
rv = --(*val);
PR_Unlock(atomic_lock);
return rv;
}
PRInt32
_PR_MD_ATOMIC_SET(PRInt32 *val, PRInt32 newval)
{
PRInt32 rv;
if (!_pr_initialized) {
_PR_ImplicitInitialization();
}
PR_Lock(atomic_lock);
rv = *val;
*val = newval;
PR_Unlock(atomic_lock);
return rv;
}
#endif /* _PR_PTHREADS && !_PR_DCETHREADS */
#endif /* !_PR_HAVE_ATOMIC_OPS */
void _PR_InitAtomic(void)
{
_PR_MD_INIT_ATOMIC();
}
PR_IMPLEMENT(PRInt32)
PR_AtomicIncrement(PRInt32 *val)
{
return _PR_MD_ATOMIC_INCREMENT(val);
}
PR_IMPLEMENT(PRInt32)
PR_AtomicDecrement(PRInt32 *val)
{
return _PR_MD_ATOMIC_DECREMENT(val);
}
PR_IMPLEMENT(PRInt32)
PR_AtomicSet(PRInt32 *val, PRInt32 newval)
{
return _PR_MD_ATOMIC_SET(val, newval);
}
PR_IMPLEMENT(PRInt32)
PR_AtomicAdd(PRInt32 *ptr, PRInt32 val)
{
return _PR_MD_ATOMIC_ADD(ptr, val);
}
/*
* For platforms, which don't support the CAS (compare-and-swap) instruction
* (or an equivalent), the stack operations are implemented by use of PRLock
*/
PR_IMPLEMENT(PRStack *)
PR_CreateStack(const char *stack_name)
{
PRStack *stack;
if (!_pr_initialized) {
_PR_ImplicitInitialization();
}
if ((stack = PR_NEW(PRStack)) == NULL) {
return NULL;
}
if (stack_name) {
stack->prstk_name = (char *) PR_Malloc(strlen(stack_name) + 1);
if (stack->prstk_name == NULL) {
PR_DELETE(stack);
return NULL;
}
strcpy(stack->prstk_name, stack_name);
} else
stack->prstk_name = NULL;
#ifndef _PR_HAVE_ATOMIC_CAS
stack->prstk_lock = PR_NewLock();
if (stack->prstk_lock == NULL) {
PR_Free(stack->prstk_name);
PR_DELETE(stack);
return NULL;
}
#endif /* !_PR_HAVE_ATOMIC_CAS */
stack->prstk_head.prstk_elem_next = NULL;
return stack;
}
PR_IMPLEMENT(PRStatus)
PR_DestroyStack(PRStack *stack)
{
if (stack->prstk_head.prstk_elem_next != NULL) {
PR_SetError(PR_INVALID_STATE_ERROR, 0);
return PR_FAILURE;
}
if (stack->prstk_name)
PR_Free(stack->prstk_name);
#ifndef _PR_HAVE_ATOMIC_CAS
PR_DestroyLock(stack->prstk_lock);
#endif /* !_PR_HAVE_ATOMIC_CAS */
PR_DELETE(stack);
return PR_SUCCESS;
}
#ifndef _PR_HAVE_ATOMIC_CAS
PR_IMPLEMENT(void)
PR_StackPush(PRStack *stack, PRStackElem *stack_elem)
{
PR_Lock(stack->prstk_lock);
stack_elem->prstk_elem_next = stack->prstk_head.prstk_elem_next;
stack->prstk_head.prstk_elem_next = stack_elem;
PR_Unlock(stack->prstk_lock);
return;
}
PR_IMPLEMENT(PRStackElem *)
PR_StackPop(PRStack *stack)
{
PRStackElem *element;
PR_Lock(stack->prstk_lock);
element = stack->prstk_head.prstk_elem_next;
if (element != NULL) {
stack->prstk_head.prstk_elem_next = element->prstk_elem_next;
element->prstk_elem_next = NULL; /* debugging aid */
}
PR_Unlock(stack->prstk_lock);
return element;
}
#endif /* !_PR_HAVE_ATOMIC_CAS */
| yuyuyu101/VirtualBox-NetBSD | src/libs/xpcom18a4/nsprpub/pr/src/misc/pratom.c | C | gpl-2.0 | 10,439 |
<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Cache\Controller;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Cache\Cache;
use Joomla\CMS\Cache\CacheController;
/**
* Joomla! Cache page type object
*
* @since 11.1
*/
class PageController extends CacheController
{
/**
* ID property for the cache page object.
*
* @var integer
* @since 11.1
*/
protected $_id;
/**
* Cache group
*
* @var string
* @since 11.1
*/
protected $_group;
/**
* Cache lock test
*
* @var \stdClass
* @since 11.1
*/
protected $_locktest = null;
/**
* Get the cached page data
*
* @param boolean $id The cache data ID
* @param string $group The cache data group
*
* @return mixed Boolean false on no result, cached object otherwise
*
* @since 11.1
*/
public function get($id = false, $group = 'page')
{
// If an id is not given, generate it from the request
if (!$id)
{
$id = $this->_makeId();
}
// If the etag matches the page id ... set a no change header and exit : utilize browser cache
if (!headers_sent() && isset($_SERVER['HTTP_IF_NONE_MATCH']))
{
$etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
if ($etag == $id)
{
$browserCache = isset($this->options['browsercache']) ? $this->options['browsercache'] : false;
if ($browserCache)
{
$this->_noChange();
}
}
}
// We got a cache hit... set the etag header and echo the page data
$data = $this->cache->get($id, $group);
$this->_locktest = (object) array('locked' => null, 'locklooped' => null);
if ($data === false)
{
$this->_locktest = $this->cache->lock($id, $group);
// If locklooped is true try to get the cached data again; it could exist now.
if ($this->_locktest->locked === true && $this->_locktest->locklooped === true)
{
$data = $this->cache->get($id, $group);
}
}
if ($data !== false)
{
if ($this->_locktest->locked === true)
{
$this->cache->unlock($id, $group);
}
$data = unserialize(trim($data));
$data = Cache::getWorkarounds($data);
$this->_setEtag($id);
return $data;
}
// Set ID and group placeholders
$this->_id = $id;
$this->_group = $group;
return false;
}
/**
* Stop the cache buffer and store the cached data
*
* @param mixed $data The data to store
* @param string $id The cache data ID
* @param string $group The cache data group
* @param boolean $wrkarounds True to use wrkarounds
*
* @return boolean
*
* @since 11.1
*/
public function store($data, $id, $group = null, $wrkarounds = true)
{
if ($this->_locktest->locked === false && $this->_locktest->locklooped === true)
{
// We can not store data because another process is in the middle of saving
return false;
}
// Get page data from the application object
if (!$data)
{
$data = \JFactory::getApplication()->getBody();
// Only attempt to store if page data exists.
if (!$data)
{
return false;
}
}
// Get id and group and reset the placeholders
if (!$id)
{
$id = $this->_id;
}
if (!$group)
{
$group = $this->_group;
}
if ($wrkarounds)
{
$data = Cache::setWorkarounds(
$data,
array(
'nopathway' => 1,
'nohead' => 1,
'nomodules' => 1,
'headers' => true,
)
);
}
$result = $this->cache->store(serialize($data), $id, $group);
if ($this->_locktest->locked === true)
{
$this->cache->unlock($id, $group);
}
return $result;
}
/**
* Generate a page cache id
*
* @return string MD5 Hash
*
* @since 11.1
* @todo Discuss whether this should be coupled to a data hash or a request hash ... perhaps hashed with a serialized request
*/
protected function _makeId()
{
return Cache::makeId();
}
/**
* There is no change in page data so send an unmodified header and die gracefully
*
* @return void
*
* @since 11.1
*/
protected function _noChange()
{
$app = \JFactory::getApplication();
// Send not modified header and exit gracefully
header('HTTP/1.x 304 Not Modified', true);
$app->close();
}
/**
* Set the ETag header in the response
*
* @param string $etag The entity tag (etag) to set
*
* @return void
*
* @since 11.1
*/
protected function _setEtag($etag)
{
\JFactory::getApplication()->setHeader('ETag', $etag, true);
}
}
| vyelamanchili/v4ecc | sites/ranjeesh/libraries/src/Cache/Controller/PageController.php | PHP | gpl-2.0 | 4,636 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.