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
|
---|---|---|---|---|---|
/*
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.
*/
package com.google.security.zynamics.binnavi.standardplugins.utils;
import java.awt.Component;
import java.util.Hashtable;
import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
public final class IconNodeRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(final JTree tree, final Object value,
final boolean sel, final boolean expanded, final boolean leaf, final int row,
final boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
@SuppressWarnings("unchecked")
final Hashtable<String, Icon> icons =
(Hashtable<String, Icon>) tree.getClientProperty("JTree.icons");
final String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
} else {
setIcon(icon);
}
return this;
}
}
| paran0ids0ul/binnavi | src/main/java/com/google/security/zynamics/binnavi/standardplugins/utils/IconNodeRenderer.java | Java | apache-2.0 | 1,682 |
define(
"dojox/editor/plugins/nls/it/AutoSave", ({
"saveLabel": "Salva",
"saveSettingLabelOn": "Imposta intervallo di salvataggio automatico...",
"saveSettingLabelOff": "Disattiva salvataggio automatico",
"saveSettingdialogTitle": "Salvataggio automatico",
"saveSettingdialogDescription": "Specifica intervallo di salvataggio automatico",
"saveSettingdialogParamName": "Intervallo di salvataggio automatico",
"saveSettingdialogParamLabel": "min",
"saveSettingdialogButtonOk": "Imposta intervallo",
"saveSettingdialogButtonCancel": "Annulla",
"saveMessageSuccess": "Salvato alle ${0}",
"saveMessageFail": "Salvataggio alle ${0} non riuscito"
})
);
| Caspar12/zh.sw | zh.web.site.admin/src/main/resources/static/js/dojo/dojox/editor/plugins/nls/it/AutoSave.js.uncompressed.js | JavaScript | apache-2.0 | 658 |
//go:build !providerless
// +build !providerless
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package securitygroupclient implements the client for SecurityGroups.
package securitygroupclient // import "k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient"
| mahak/origin | vendor/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/doc.go | GO | apache-2.0 | 798 |
// Copyright 2008-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.
// ========================================================================
#ifndef OMAHA_GOOGLE_UPDATE_PRECOMPILE_H__
#define OMAHA_GOOGLE_UPDATE_PRECOMPILE_H__
#pragma runtime_checks("", off)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <shlwapi.h>
#include <tchar.h>
#pragma warning(push)
// C4310: cast truncates constant value
#pragma warning(disable : 4310)
#include "base/basictypes.h"
#pragma warning(pop)
#endif // OMAHA_GOOGLE_UPDATE_PRECOMPILE_H__
| priaonehaha/omaha | google_update/precompile.h | C | apache-2.0 | 1,108 |
(function() {
var exports = {};
var popmotion = ((function() {
var exports = {};
var __small$_12 = (function() {
var exports = {};
exports = {
defaultProps: {
unit: 'px'
}
};
return exports;
})();
var __small$_40 = (function() {
var exports = {};
/*
Utility functions
*/
"use strict";
var protectedProperties = ['scope', 'dom'],
isProtected = function (key) {
return (protectedProperties.indexOf(key) !== -1);
},
/*
Get var type as string
@param: Variable to test
@return [string]: Returns, for instance 'Object' if [object Object]
*/
varType = function (variable) {
return Object.prototype.toString.call(variable).slice(8, -1);
};
exports = {
/*
Has one object changed from the other
Compares the two provided inputs and returns true if they are different
@param [object]: Input A
@param [object]: Input B
@return [boolean]: True if different
*/
hasChanged: function (a, b) {
var hasChanged = false,
key = '';
for (key in b) {
if (a.hasOwnProperty(key) && b.hasOwnProperty(key)) {
if (a[key] !== b[key]) {
hasChanged = true;
}
} else {
hasChanged = true;
}
}
return hasChanged;
},
/*
Is this var a number?
@param: Variable to test
@return [boolean]: Returns true if typeof === 'number'
*/
isNum: function (num) {
return (typeof num === 'number');
},
/*
Is this var an object?
@param: Variable to test
@return [boolean]: Returns true if typeof === 'object'
*/
isObj: function (obj) {
return (typeof obj === 'object');
},
/*
Is this var a function ?
@param: Variable to test
@return [boolean]: Returns true if this.varType === 'Function'
*/
isFunc: function (obj) {
return (varType(obj) === 'Function');
},
/*
Is this var a string ?
@param: Variable to test
@return [boolean]: Returns true if typeof str === 'string'
*/
isString: function (str) {
return (typeof str === 'string');
},
/*
Is this a relative value assignment?
@param [string]: Variable to test
@return [boolean]: If this looks like a relative value assignment
*/
isRelativeValue: function (value) {
return (value && value.indexOf && value.indexOf('=') > 0);
},
/*
Is this var an array ?
@param: Variable to test
@return [boolean]: Returns true if this.varType === 'Array'
*/
isArray: function (arr) {
return (varType(arr) === 'Array');
},
/*
Copy object or array
Checks whether base is an array or object and makes
appropriate copy
@param [array || object]: Array or object to copy
@param [array || object]: New copy of array or object
*/
copy: function (base) {
return (this.isArray(base)) ? this.copyArray(base) : this.copyObject(base);
},
/*
Deep copy an object
Iterates over an object and creates a new copy of every item,
deep copying if it finds any objects/arrays
@param [object]: Object to copy
@param [object]: New copy of object
*/
copyObject: function (base) {
var newObject = {};
for (var key in base) {
if (base.hasOwnProperty(key)) {
newObject[key] = (this.isObj(base[key]) && !isProtected(key)) ? this.copy(base[key]) : base[key];
}
}
return newObject;
},
/*
Deep copy an array
Loops through an array and creates a new copy of every item,
deep copying if it finds any objects/arrays
@param [array]: Array to copy
@return [array]: New copy of array
*/
copyArray: function (base) {
var newArray = [],
length = base.length,
i = 0;
for (; i < length; i++) {
newArray[i] = (this.isObj(base[i])) ? this.copy(base[i]) : base[i];
}
return newArray;
},
/*
Non-destructive merge of object or array
@param [array || object]: Array or object to use as base
@param [array || object]: Array or object to overwrite base with
@return [array || object]: New array or object
*/
merge: function (base, overwrite) {
return (this.isArray(base)) ? this.copyArray(overwrite) : this.mergeObject(base, overwrite);
},
/*
Non-destructive merge of object
@param [object]: Object to use as base
@param [object]: Object to overwrite base with
@return [object]: New object
*/
mergeObject: function (base, overwrite) {
var hasBase = this.isObj(base),
newObject = hasBase ? this.copy(base) : this.copy(overwrite),
key = '';
if (hasBase) {
for (key in overwrite) {
if (overwrite.hasOwnProperty(key)) {
newObject[key] = (this.isObj(overwrite[key]) && !isProtected(key)) ? this.merge(base[key], overwrite[key]) : overwrite[key];
}
}
}
return newObject;
},
/*
Split a value into a value/unit object
"200px" -> { value: 200, unit: "px" }
@param [string]: Value to split
@return [object]: Object with value and unit props
*/
splitValUnit: function (value) {
var splitVal = value.match(/(-?\d*\.?\d*)(.*)/);
return {
value: parseFloat(splitVal[1]),
unit: splitVal[2]
};
},
/*
Create stepped version of 0-1 progress
@param [number]: Current value
@param [int]: Number of steps
@return [number]: Stepped value
*/
stepProgress: function (progress, steps) {
var segment = 1 / (steps - 1),
target = 1 - (1 / steps),
progressOfTarget = Math.min(progress / target, 1);
return Math.floor(progressOfTarget / segment) * segment;
},
/*
Generate current timestamp
@return [timestamp]: Current UNIX timestamp
*/
currentTime: function () {
return (typeof performance !== "undefined") ? performance.now() : new Date().getTime();
}
};
return exports;
})();
var __small$_24 = (function() {
var exports = {};
/*
Calculators
----------------------------------------
Simple I/O snippets
*/
"use strict";
var utils = __small$_40,
calc = {
/*
Angle between points
Translates the hypothetical line so that the 'from' coordinates
are at 0,0, then return the angle using .angleFromCenter()
@param [object]: X and Y coordinates of from point
@param [object]: X and Y cordinates of to point
@return [radian]: Angle between the two points in radians
*/
angle: function (pointA, pointB) {
var from = pointB ? pointA : {x: 0, y: 0},
to = pointB || pointA,
point = {
x: to.x - from.x,
y: to.y - from.y
};
return this.angleFromCenter(point.x, point.y);
},
/*
Angle from center
Returns the current angle, in radians, of a defined point
from a center (assumed 0,0)
@param [number]: X coordinate of second point
@param [number]: Y coordinate of second point
@return [radian]: Angle between 0, 0 and point in radians
*/
angleFromCenter: function (x, y) {
return this.radiansToDegrees(Math.atan2(y, x));
},
/*
Convert degrees to radians
@param [number]: Value in degrees
@return [number]: Value in radians
*/
degreesToRadians: function (degrees) {
return degrees * Math.PI / 180;
},
/*
Dilate
Change the progression between a and b according to dilation.
So dilation = 0.5 would change
a --------- b
to
a ---- b
@param [number]: Previous value
@param [number]: Current value
@param [number]: Dilate progress by x
@return [number]: Previous value plus the dilated difference
*/
dilate: function (a, b, dilation) {
return a + ((b - a) * dilation);
},
/*
Distance
Returns the distance between (0,0) and pointA, unless pointB
is provided, then we return the difference between the two.
@param [object/number]: x and y or just x of point A
@param [object/number]: (optional): x and y or just x of point B
@return [number]: The distance between the two points
*/
distance: function (pointA, pointB) {
return (typeof pointA === "number") ? this.distance1D(pointA, pointB) : this.distance2D(pointA, pointB);
},
/*
Distance 1D
Returns the distance between point A and point B
@param [number]: Point A
@param [number]: (optional): Point B
@return [number]: The distance between the two points
*/
distance1D: function (pointA, pointB) {
var bIsNum = (typeof pointB === 'number'),
from = bIsNum ? pointA : 0,
to = bIsNum ? pointB : pointA;
return absolute(to - from);
},
/*
Distance 2D
Returns the distance between (0,0) and point A, unless point B
is provided, then we return the difference between the two.
@param [object]: x and y of point A
@param [object]: (optional): x and y of point B
@return [number]: The distance between the two points
*/
distance2D: function (pointA, pointB) {
var bIsObj = (typeof pointB === "object"),
from = bIsObj ? pointA : {x: 0, y: 0},
to = bIsObj ? pointB : pointA,
point = {
x: absolute(to.x - from.x),
y: absolute(to.y - from.y)
};
return this.hypotenuse(point.x, point.y);
},
/*
Hypotenuse
Returns the hypotenuse, side C, given the lengths of sides A and B.
@param [number]: Length of A
@param [number]: Length of B
@return [number]: Length of C
*/
hypotenuse: function (a, b) {
var a2 = a * a,
b2 = b * b,
c2 = a2 + b2;
return Math.sqrt(c2);
},
/*
Offset between two inputs
Calculate the difference between two different inputs
@param [Point]: First input
@param [Point]: Second input
@return [Offset]: Distance metrics between two points
*/
offset: function (a, b) {
var offset = {};
for (var key in b) {
if (b.hasOwnProperty(key)) {
if (a.hasOwnProperty(key)) {
offset[key] = b[key] - a[key];
} else {
offset[key] = 0;
}
}
}
if (isNum(offset.x) && isNum(offset.y)) {
offset.angle = this.angle(a, b);
offset.distance = this.distance2D(a, b);
}
return offset;
},
/*
Point from angle and distance
@param [object]: 2D point of origin
@param [number]: Angle from origin
@param [number]: Distance from origin
@return [object]: Calculated 2D point
*/
pointFromAngleAndDistance: function (origin, angle, distance) {
var point = {};
point.x = distance * Math.cos(angle) + origin.x;
point.y = distance * Math.sin(angle) + origin.y;
return point;
},
/*
Progress within given range
Given a lower limit and an upper limit, we return the progress
(expressed as a number 0-1) represented by the given value, and
limit that progress to within 0-1.
@param [number]: Value to find progress within given range
@param [number]: Lower limit if full range given, upper if not
@param [number] (optional): Upper limit of range
@return [number]: Progress of value within range as expressed 0-1
*/
progress: function (value, limitA, limitB) {
var bIsNum = (typeof limitB === 'number'),
from = bIsNum ? limitA : 0,
to = bIsNum ? limitB : limitA,
range = to - from,
progress = (value - from) / range;
return progress;
},
/*
Convert radians to degrees
@param [number]: Value in radians
@return [number]: Value in degrees
*/
radiansToDegrees: function (radians) {
return radians * 180 / Math.PI;
},
/*
Return random number between range
@param [number] (optional): Output minimum
@param [number] (optional): Output maximum
@return [number]: Random number within range, or 0 and 1 if none provided
*/
random: function (min, max) {
min = isNum(min) ? min : 0;
max = isNum(max) ? max : 1;
return Math.random() * (max - min) + min;
},
/*
Calculate relative value
Takes the operator and value from a string, ie "+=5", and applies
to the current value to resolve a new target.
@param [number]: Current value
@param [string]: Relative value
@return [number]: New value
*/
relativeValue: function (current, rel) {
var newValue = current,
equation = rel.split('='),
operator = equation[0],
splitVal = utils.splitValUnit(equation[1]);
switch (operator) {
case '+':
newValue += splitVal.value;
break;
case '-':
newValue -= splitVal.value;
break;
case '*':
newValue *= splitVal.value;
break;
case '/':
newValue /= splitVal.value;
break;
}
if (splitVal.unit) {
newValue += splitVal.unit;
}
return newValue;
},
/*
Restrict value to range
Return value within the range of lowerLimit and upperLimit
@param [number]: Value to keep within range
@param [number]: Lower limit of range
@param [number]: Upper limit of range
@return [number]: Value as limited within given range
*/
restricted: function (value, min, max) {
var restricted = (min !== undefined) ? Math.max(value, min) : value;
restricted = (max !== undefined) ? Math.min(restricted, max) : restricted;
return restricted;
},
/*
Convert x per second to per frame velocity based on fps
@param [number]: Unit per second
@param [number]: Frame duration in ms
*/
speedPerFrame: function (xps, frameDuration) {
return (isNum(xps)) ? xps / (1000 / frameDuration) : 0;
},
/*
Convert velocity into velicity per second
@param [number]: Unit per frame
@param [number]: Frame duration in ms
*/
speedPerSecond: function (velocity, frameDuration) {
return velocity * (1000 / frameDuration);
},
/*
Value in range from progress
Given a lower limit and an upper limit, we return the value within
that range as expressed by progress (a number from 0-1)
@param [number]: The progress between lower and upper limits expressed 0-1
@param [number]: Lower limit of range, or upper if limit2 not provided
@param [number] (optional): Upper limit of range
@return [number]: Value as calculated from progress within range (not limited within range)
*/
value: function (progress, limitA, limitB) {
var bIsNum = (typeof limitB === 'number'),
from = bIsNum ? limitA : 0,
to = bIsNum ? limitB : limitA;
return (- progress * from) + (progress * to) + from;
},
/*
Eased value in range from progress
Given a lower limit and an upper limit, we return the value within
that range as expressed by progress (a number from 0-1)
@param [number]: The progress between lower and upper limits expressed 0-1
@param [number]: Lower limit of range, or upper if limit2 not provided
@param [number]: Upper limit of range
@param [function]: Easing to apply to value
@return [number]: Value as calculated from progress within range (not limited within range)
*/
valueEased: function (progress, from, to, easing) {
var easedProgress = easing(progress);
return this.value(easedProgress, from, to);
}
},
/*
Caching functions used multiple times to reduce filesize and increase performance
*/
isNum = utils.isNum,
absolute = Math.abs;
exports = calc;
return exports;
})();
var __small$_47 = (function() {
var exports = {};
"use strict";
exports = function (values, terms, delimiter, chop) {
var combined = '',
key = '',
i = 0,
numTerms = terms.length;
for (; i < numTerms; i++) {
key = terms[i];
if (values.hasOwnProperty(key)) {
combined += values[key] + delimiter;
}
}
if (chop) {
combined = combined.slice(0, -chop);
}
return combined;
};
return exports;
})();
var __small$_49 = (function() {
var exports = {};
exports = function (value, prefix) {
return prefix + '(' + value + ')';
};
return exports;
})();
var __small$_50 = (function() {
var exports = {};
"use strict";
var X = 'X',
Y = 'Y',
ALPHA = 'Alpha',
terms = {
colors: ['Red', 'Green', 'Blue', ALPHA],
positions: [X, Y, 'Z'],
dimensions: ['Top', 'Right', 'Bottom', 'Left'],
shadow: [X, Y, 'Radius', 'Spread', 'Color'],
hsl: ['Hue', 'Saturation', 'Lightness', ALPHA]
};
exports = terms;
return exports;
})();
var __small$_51 = (function() {
var exports = {};
"use strict";
exports = {
color: {
min: 0,
max: 255,
round: true
},
opacity: {
min: 0,
max: 1
},
percent: {
min: 0,
max: 100,
unit: '%'
}
};
return exports;
})();
var __small$_52 = (function() {
var exports = {};
exports = function (value) {
return (typeof value === 'string') ? value.split(' ') : [value];
};
return exports;
})();
var __small$_38 = (function() {
var exports = {};
/*
Input controller
*/
"use strict";
var calc = __small$_24,
utils = __small$_40,
History = ((function() {
var exports = {};
"use strict";
var // [number]: Default max size of history
maxHistorySize = 3,
/*
History constructor
@param [var]: Variable to store in first history slot
@param [int] (optional): Maximum size of history
*/
History = function (obj, max) {
this.max = max || maxHistorySize;
this.entries = [];
this.add(obj);
};
History.prototype = {
/*
Push new var to history
Shift out oldest entry if we've reached maximum capacity
@param [var]: Variable to push into history.entries
*/
add: function (obj) {
var currentSize = this.getSize();
this.entries.push(obj);
if (currentSize >= this.max) {
this.entries.shift();
}
},
/*
Get variable at specified index
@param [int]: Index
@return [var]: Var found at specified index
*/
get: function (i) {
i = (typeof i === 'number') ? i : this.getSize() - 1;
return this.entries[i];
},
/*
Get the second newest history entry
@return [var]: Entry found at index size - 2
*/
getPrevious: function () {
return this.get(this.getSize() - 2);
},
/*
Get current history size
@return [int]: Current length of entries.length
*/
getSize: function () {
return this.entries.length;
}
};
exports = History;
return exports;
})()),
/*
Input constructor
Syntax
newInput(name, value[, poll])
@param [string]: Name of to track
@param [number]: Initial value
@param [function] (optional): Function to poll Input data
newInput(props[, poll])
@param [object]: Object of values
@param [function] (optional): Function to poll Input data
@return [Input]
*/
Input = function () {
var pollPos = arguments.length - 1;
this.current = {};
this.offset = {};
this.velocity = {};
this.history = new History();
this.update(arguments[0], arguments[1]);
if (utils.isFunc(arguments[pollPos])) {
this.poll = arguments[pollPos];
}
};
Input.prototype = {
// [number]: Number of frames of inactivity before velocity is turned to 0
maxInactiveFrames: 2,
// [number]: Number of frames input hasn't been updated
inactiveFrames: 0,
/*
Get latest input values
@param [string] (optional): Name of specific property to return
@return [object || number]: Latest input values or, if specified, single value
*/
get: function (prop) {
var latest = this.history.get(),
val = (prop !== undefined) ? latest[prop] : latest;
return val;
},
/*
Update the input values
Syntax
input.update(name, value)
@param [string]: Name of to track
@param [number]: Initial value
input.update(props)
@param [object]: Object of values
@return [Input]
*/
update: function (arg0, arg1) {
var values = {};
if (utils.isNum(arg1)) {
values[arg0] = arg1;
} else {
values = arg0;
}
this.history.add(utils.merge(this.current, values));
return this;
},
/*
Check for input movement and update pointer object's properties
@param [number]: Timestamp of frame
@return [Input]
*/
onFrame: function (timestamp) {
var latest, hasChanged;
// Check provided timestamp against lastFrame timestamp and return input has already been updated
if (timestamp === this.lastFrame) {
return;
}
latest = (this.poll) ? this.poll() : this.history.get();
hasChanged = utils.hasChanged(this.current, latest);
// If input has changed between frames
if (hasChanged) {
this.velocity = calc.offset(this.current, latest);
this.current = latest;
this.inactiveFrames = 0;
// Or it hasn't moved and our frame limit has been reached
} else if (this.inactiveFrames >= this.maxInactiveFrames) {
this.velocity = calc.offset(this.current, this.current);
// Or input hasn't changed
} else {
this.inactiveFrames++;
}
this.lastFrame = timestamp;
return this;
}
};
exports = Input;
return exports;
})();
var __small$_59 = (function() {
var exports = {};
"use strict";
var ModManager = function () {
this._keys = [];
this._numKeys = 0;
};
ModManager.prototype = {
/*
Add module key to keys list
@param [string]: Key to add
*/
_addKey: function (name) {
this._keys.push(name);
this._numKeys++;
},
/*
Add a new module
@param [string || object]: Name of new module or multiple modules
@param [object] (optional): Module to add
*/
extend: function (name, mod) {
var multiMods = (typeof name == 'object'),
mods = multiMods ? name : {},
key = '';
// If we just have one module, coerce
if (!multiMods) {
mods[name] = mod;
}
for (key in mods) {
if (mods.hasOwnProperty(key)) {
this._addKey(key);
this[key] = mods[key];
}
}
return this;
},
each: function (callback) {
var key = '';
for (var i = 0; i < this._numKeys; i++) {
key = this._keys[i];
callback(key, this[key]);
}
}
};
exports = ModManager;
return exports;
})();
var __small$_30 = (function() {
var exports = {};
/*
Easing functions
----------------------------------------
Generates and provides easing functions based on baseFunction definitions
A call to easingFunction.get('functionName') returns a function that can be passed:
@param [number]: Progress 0-1
@param [number] (optional): Amp modifier, only accepted in some easing functions
and is used to adjust overall strength
@return [number]: Eased progress
We can generate new functions by sending an easing function through easingFunction.extend(name, method).
Which will make nameIn, nameOut and nameInOut functions available to use.
Easing functions from Robert Penner
http://www.robertpenner.com/easing/
Bezier curve interpretor created from Gaëtan Renaudeau's original BezierEasing
https://github.com/gre/bezier-easing/blob/master/index.js
https://github.com/gre/bezier-easing/blob/master/LICENSE
*/
"use strict";
var calc = __small$_24,
Bezier = ((function() {
var exports = {};
/*
Bezier function generator
Gaëtan Renaudeau's BezierEasing
https://github.com/gre/bezier-easing/blob/master/index.js
https://github.com/gre/bezier-easing/blob/master/LICENSE
You're a hero
Use
var easeOut = new Bezier(.17,.67,.83,.67),
x = easeOut(0.5); // returns 0.627...
*/
"use strict";
var NEWTON_ITERATIONS = 8,
NEWTON_MIN_SLOPE = 0.001,
SUBDIVISION_PRECISION = 0.0000001,
SUBDIVISION_MAX_ITERATIONS = 10,
K_SPLINE_TABLE_SIZE = 11,
K_SAMPLE_STEP_SIZE = 1.0 / (K_SPLINE_TABLE_SIZE - 1.0),
FLOAT_32_SUPPORTED = (typeof Float32Array !== 'undefined'),
a = function (a1, a2) {
return 1.0 - 3.0 * a2 + 3.0 * a1;
},
b = function (a1, a2) {
return 3.0 * a2 - 6.0 * a1;
},
c = function (a1) {
return 3.0 * a1;
},
getSlope = function (t, a1, a2) {
return 3.0 * a(a1, a2) * t * t + 2.0 * b(a1, a2) * t + c(a1);
},
calcBezier = function (t, a1, a2) {
return ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t;
},
/*
Bezier constructor
*/
Bezier = function (mX1, mY1, mX2, mY2) {
var sampleValues = FLOAT_32_SUPPORTED ? new Float32Array(K_SPLINE_TABLE_SIZE) : new Array(K_SPLINE_TABLE_SIZE),
_precomputed = false,
binarySubdivide = function (aX, aA, aB) {
var currentX, currentT, i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
},
newtonRaphsonIterate = function (aX, aGuessT) {
var i = 0,
currentSlope = 0.0,
currentX;
for (; i < NEWTON_ITERATIONS; ++i) {
currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) {
return aGuessT;
}
currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
},
calcSampleValues = function () {
for (var i = 0; i < K_SPLINE_TABLE_SIZE; ++i) {
sampleValues[i] = calcBezier(i * K_SAMPLE_STEP_SIZE, mX1, mX2);
}
},
getTForX = function (aX) {
var intervalStart = 0.0,
currentSample = 1,
lastSample = K_SPLINE_TABLE_SIZE - 1,
dist = 0.0,
guessForT = 0.0,
initialSlope = 0.0;
for (; currentSample != lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += K_SAMPLE_STEP_SIZE;
}
--currentSample;
dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample+1] - sampleValues[currentSample]);
guessForT = intervalStart + dist * K_SAMPLE_STEP_SIZE;
initialSlope = getSlope(guessForT, mX1, mX2);
// If slope is greater than min
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT);
// Slope is equal to min
} else if (initialSlope === 0.0) {
return guessForT;
// Slope is less than min
} else {
return binarySubdivide(aX, intervalStart, intervalStart + K_SAMPLE_STEP_SIZE);
}
},
precompute = function () {
_precomputed = true;
if (mX1 != mY1 || mX2 != mY2) {
calcSampleValues();
}
},
/*
Generated function
Returns value 0-1 based on X
*/
f = function (aX) {
var returnValue;
if (!_precomputed) {
precompute();
}
// If linear gradient, return X as T
if (mX1 === mY1 && mX2 === mY2) {
returnValue = aX;
// If at start, return 0
} else if (aX === 0) {
returnValue = 0;
// If at end, return 1
} else if (aX === 1) {
returnValue = 1;
} else {
returnValue = calcBezier(getTForX(aX), mY1, mY2);
}
return returnValue;
};
return f;
};
exports = Bezier;
return exports;
})()),
EASE_IN = 'In',
EASE_OUT = 'Out',
EASE_IN_OUT = EASE_IN + EASE_OUT,
// Generate easing function with provided power
generatePowerEasing = function (power) {
return function (progress) {
return Math.pow(progress, power);
};
},
/*
Each of these base functions is an easeIn
On init, we use EasingFunction.mirror and .reverse to generate easeInOut and
easeOut functions respectively.
*/
baseEasing = {
circ: function (progress) {
return 1 - Math.sin(Math.acos(progress));
},
back: function (progress) {
var strength = 1.5;
return (progress * progress) * ((strength + 1) * progress - strength);
}
},
/*
Mirror easing
Mirrors the provided easing function, used here for mirroring an
easeIn into an easeInOut
@param [number]: Progress, from 0 - 1, of current shift
@param [function]: The easing function to mirror
@returns [number]: The easing-adjusted delta
*/
mirrorEasing = function (progress, method) {
return (progress <= 0.5) ? method(2 * progress) / 2 : (2 - method(2 * (1 - progress))) / 2;
},
/*
Reverse easing
Reverses the output of the provided easing function, used for flipping easeIn
curve to an easeOut.
@param [number]: Progress, from 0 - 1, of current shift
@param [function]: The easing function to reverse
@returns [number]: The easing-adjusted delta
*/
reverseEasing = function (progress, method) {
return 1 - method(1 - progress);
},
/*
Add new easing function
Takes name and generates nameIn, nameOut, nameInOut, and easing functions to match
@param [string]: Base name of the easing functions to generate
@param [function]: Base easing function, as an easeIn, from which to generate Out and InOut
*/
generateVariations = function (name, method) {
var easeIn = name + EASE_IN,
easeOut = name + EASE_OUT,
easeInOut = name + EASE_IN_OUT,
baseName = easeIn,
reverseName = easeOut;
// Create the In function
easingManager[baseName] = method;
// Create the Out function by reversing the transition curve
easingManager[reverseName] = function (progress) {
return reverseEasing(progress, easingManager[baseName]);
};
// Create the InOut function by mirroring the transition curve
easingManager[easeInOut] = function (progress) {
return mirrorEasing(progress, easingManager[baseName]);
};
},
ModManager = __small$_59,
easingManager = new ModManager();
/*
Extend easing functions
*/
easingManager.extend = function (name, x1, y1, x2, y2) {
// If this is an easing function, generate variations
if (typeof x1 === 'function') {
generateVariations(name, x1);
// Otherwise it's a bezier curve, so generate new Bezier curve function
} else {
this[name] = new Bezier(x1, y1, x2, y2);
}
return this;
};
/*
Ease value within ranged parameters
@param [number]: Progress between 0 and 1
@param [number]: Value of 0 progress
@param [number]: Value of 1 progress
@param [string]: Easing to use
@param [number]: Amplify progress out of specified range
@return [number]: Value of eased progress in range
*/
easingManager.withinRange = function (progress, from, to, ease, escapeAmp) {
var progressLimited = calc.restricted(progress, 0, 1);
if (progressLimited !== progress && escapeAmp) {
ease = 'linear';
progressLimited = progressLimited + ((progress - progressLimited) * escapeAmp);
}
return calc.valueEased(progressLimited, from, to, this[ease]);
};
/*
Linear easing adjustment
The default easing method, not added with .extend as it has no Out or InOut
variation.
@param [number]: Progress, from 0-1
@return [number]: Unadjusted progress
*/
easingManager.linear = function (progress) {
return progress;
};
// Generate power easing easing
['ease', 'cubic', 'quart', 'quint'].forEach(function (easingName, i) {
baseEasing[easingName] = generatePowerEasing(i + 2);
});
// Generate in/out/inOut variations
for (var key in baseEasing) {
if (baseEasing.hasOwnProperty(key)) {
generateVariations(key, baseEasing[key]);
}
}
exports = easingManager;
return exports;
})();
var __small$_33 = (function() {
var exports = {};
"use strict";
var utils = __small$_40,
ModManager = __small$_59,
presetManager = new ModManager(),
DOT = '.',
generateKeys = function (key) {
var keys = key.split(DOT),
numKeys = keys.length,
lastKey = keys[0],
i = 1;
for (; i < numKeys; i++) {
keys[i] = lastKey += DOT + keys[i];
}
return keys;
};
/*
Get defined action
@param [string]: The name of the predefined action
*/
presetManager.getDefined = function (name) {
var props = {},
thisProp = {},
keys = generateKeys(name),
numKeys = keys.length,
i = 0;
for (; i < numKeys; i++) {
thisProp = this[keys[i]];
if (thisProp) {
props = utils.merge(props, thisProp);
}
}
return props;
};
exports = presetManager;
return exports;
})();
var __small$_28 = (function() {
var exports = {};
"use strict";
var presetManager = __small$_33,
utils = __small$_40;
exports = function (base, override) {
var props = (typeof base === 'string') ? presetManager.getDefined(base) : base;
// Override properties with second arg if it's an object
if (typeof override === 'object') {
props = utils.merge(props, override);
}
return props;
};
return exports;
})();
var __small$_34 = (function() {
var exports = {};
"use strict";
var calc = __small$_24,
utils = __small$_40,
speedPerFrame = calc.speedPerFrame,
ModManager = __small$_59,
simulationManager = new ModManager();
/*
Add core physics simulations
*/
simulationManager.extend({
/*
Velocity
The default .run() simulation.
Applies any set deceleration and acceleration to existing velocity
*/
velocity: function (value, duration) {
value.velocity = value.velocity - speedPerFrame(value.deceleration, duration) + speedPerFrame(value.acceleration, duration);
return simulationManager.friction(value, duration);
},
/*
Glide
Emulates touch device scrolling effects with exponential decay
http://ariya.ofilabs.com/2013/11/javascript-kinetic-scrolling-part-2.html
*/
glide: function (value, duration, started) {
var timeUntilFinished = - utils.currentTime() - started,
delta = - value.to * Math.exp(timeUntilFinished / value.timeConstant);
return (value.to + delta) - value.current;
},
/*
Friction
Apply friction to the current value
TODO: Make this framerate-independent
*/
friction: function (value, duration) {
var newVelocity = speedPerFrame(value.velocity, duration) * (1 - value.friction);
return calc.speedPerSecond(newVelocity, duration);
},
spring: function (value, duration) {
var distance = value.to - value.current;
value.velocity += distance * speedPerFrame(value.spring, duration);
return simulationManager.friction(value, duration);
},
bounce: function (value) {
var distance = 0,
to = value.to,
current = value.current,
bounce = value.bounce;
// If we're using glide simulation we have to flip our target too
if (value.simulate === 'glide') {
distance = to - current;
value.to = current - (distance * bounce);
}
return value.velocity *= - bounce;
},
capture: function (value, target) {
value.to = target;
value.simulate = 'spring';
value.capture = value.min = value.max = undefined;
}
});
exports = simulationManager;
return exports;
})();
var __small$_4 = (function() {
var exports = {};
/*
Play action
Translate numbers for a set amount of time, applying easing if defined
*/
"use strict";
var calc = __small$_24,
utils = __small$_40,
easingManager = __small$_30,
playAction = {
// [object] Default Action properties
actionDefaults: ((function() {
var exports = {};
exports = {
// [number]: Time of animation (if animating) in ms
duration: 400,
// [string]: Ease animation
ease: 'easeInOut',
// [number]: Multiply progress by this (.5 is half speed)
dilate: 1,
// [boolean || number]: Number of times to loop values, true for indefinite
loop: false,
// [boolean || number]: Number of times to yoyo values, true for indefinite
yoyo: false,
// [boolean || number]: Number of times to flip values, true for indefinite
flip: false
};
return exports;
})()),
// [object]: Default value properties
valueDefaults: ((function() {
var exports = {};
exports = {
// [number]: Duration of animation in ms
duration: 400,
// [number]: Duration of delay in ms
delay: 0,
// [number]: Stagger delay as factor of duration (ie 0.2 with duration of 1000ms = 200ms)
stagger: 0,
// [string]: Easing to apply
ease: 'easeInOut',
// [number]: Number of steps to execute animation
steps: 0,
// [string]: Tells Redshift when to step, at the start or end of a step. Other option is 'start' as per CSS spec
stepDirection: 'end'
};
return exports;
})()),
// [boolean] Prevent Redshift from autogenerating Element.prototype.play()
surpressMethod: true,
// [object] Methods to add to Actor.prototype
actorMethods: ((function() {
var exports = {};
"use strict";
var parseArgs = ((function() {
var exports = {};
"use strict";
var presetManager = __small$_33,
utils = __small$_40,
parsePlaylist = function () {
var args = [].slice.call(arguments),
playlist = args[0].split(' '),
playlistLength = playlist.length,
props = presetManager.getDefined(playlist[0]),
i = 1;
// If we've got multiple playlists, loop through and add each to the queue
if (playlistLength > 1) {
for (; i < playlistLength; i++) {
args.shift();
args.unshift(playlist[i]);
this.queue.add.apply(this.queue, args);
}
}
return props;
};
exports = function () {
var args = [].slice.call(arguments),
numArgs = args.length,
// If first argument is a string, get base object from presets
props = utils.isString(args[0]) ? parsePlaylist.apply(this, args) : args[0],
i = 1;
// Loop through arguments
for (; i < numArgs; i++) {
switch (typeof args[i]) {
// Override properties
case 'object':
props = utils.merge(props, args[i]);
break;
// Duration
case 'number':
props.duration = args[i];
break;
// Easing
case 'string':
props.ease = args[i];
break;
}
}
// Default .play properties
props.loopCount = props.yoyoCount = props.flipCount = 0;
props.playDirection = 1;
return props;
};
return exports;
})()),
utils = __small$_40;
exports = {
/*
Play an animation
@param [object || string]: Parameters or preset names
@param [object]: Override parameters
*/
play: function () {
this.action = 'play';
this.set(parseArgs.apply(this, arguments), 'to');
return this.start();
},
/*
Add arguments to queue
*/
addToQueue: function () {
this.queue.add.apply(this.queue, arguments);
return this;
},
/*
Check for next steps and perform, stop if not
*/
next: function () {
var nextSteps = [{
key: 'loop',
callback: this.reset
}, {
key: 'yoyo',
callback: this.reverse
}, {
key: 'flip',
callback: this.flipValues
}],
numSteps = nextSteps.length,
hasNextStep = false,
i = 0;
for (; i < numSteps; ++i) {
if (this.checkNextStep(nextSteps[i].key, nextSteps[i].callback)) {
hasNextStep = true;
break;
}
}
if (!hasNextStep && !this.playNext()) {
this.stop();
} else {
this.isActive = true;
}
return this;
},
/*
Check next step
@param [string]: Name of step ('yoyo' or 'loop')
@param [callback]: Function to run if we take this step
*/
checkNextStep: function (key, callback) {
var COUNT = 'Count',
stepTaken = false,
step = this[key],
count = this[key + COUNT],
forever = (step === true);
if (forever || utils.isNum(step)) {
++count;
this[key + COUNT] = count;
if (forever || count <= step) {
callback.call(this);
stepTaken = true;
}
}
return stepTaken;
},
/*
Next in queue
*/
playNext: function () {
var stepTaken = false,
nextInQueue = this.queue.next(this.playDirection);
if (utils.isArray(nextInQueue)) {
this.set(parseArgs.apply(this, nextInQueue), 'to')
.resetProgress();
stepTaken = true;
}
return stepTaken;
}
};
return exports;
})()),
/*
Update Action elapsed time
@param [object]: Action properties
@param [number]: Timestamp of current frame
*/
onFrameStart: function (frameDuration) {
this.elapsed += (frameDuration * this.dilate) * this.playDirection;
this.hasEnded = true;
},
/*
Calculate progress of value based on time elapsed,
value delay/duration/stagger properties
@param [object]: Value state and properties
@param [string]: Name of value being processed
@return [number]: Calculated value
*/
process: function (value, key) {
var target = value.to,
progressTarget = (this.playDirection === 1) ? 1 : 0,
newValue = value.current,
progress;
// If this value has a to property, otherwise we just return current value
if (target !== undefined) {
progress = calc.restricted(calc.progress(this.elapsed - value.delay, value.duration) - value.stagger, 0, 1);
// Mark Action as NOT ended if still in progress
if (progress !== progressTarget) {
this.hasEnded = false;
// Or, if we have ended, clear value target
} else {
value.to = undefined;
}
// Step progress if we're stepping
if (value.steps) {
progress = utils.stepProgress(progress, value.steps);
}
// Ease value
newValue = easingManager.withinRange(progress, value.origin, target, value.ease);
}
return newValue;
},
/*
Return hasEnded property
@return [boolean]: Have all Values hit 1 progress?
*/
hasEnded: function () {
return this.hasEnded;
}
};
exports = playAction;
return exports;
})();
var __small$_48 = (function() {
var exports = {};
var splitCommaDelimited = ((function() {
var exports = {};
exports = function (value) {
return (typeof value === 'string') ? value.split(/,\s*/) : [value];
};
return exports;
})()),
functionBreak = ((function() {
var exports = {};
exports = function (value) {
return value.substring(value.indexOf('(') + 1, value.lastIndexOf(')'));
};
return exports;
})());
exports = function (value, terms) {
var splitValue = {},
numTerms = terms.length,
colors = splitCommaDelimited(functionBreak(value)),
i = 0;
for (; i < numTerms; i++) {
splitValue[terms[i]] = (colors[i] !== undefined) ? colors[i] : 1;
}
return splitValue;
};
return exports;
})();
var __small$_13 = (function() {
var exports = {};
"use strict";
var createDelimited = __small$_47,
getColorValues = __small$_48,
functionCreate = __small$_49,
defaultProps = __small$_51,
terms = __small$_50.hsl;
exports = {
defaultProps: {
Hue: {
min: 0,
max: 360
},
Saturation: defaultProps.percent,
Lightness: defaultProps.percent,
Alpha: defaultProps.opacity
},
test: function (value) {
return (value && value.indexOf('hsl') > -1);
},
split: function (value) {
return getColorValues(value, terms);
},
combine: function (values) {
return functionCreate(createDelimited(values, terms, ', ', 2), 'hsla');
}
};
return exports;
})();
var __small$_14 = (function() {
var exports = {};
"use strict";
var createDelimited = __small$_47,
getColorValues = __small$_48,
functionCreate = __small$_49,
defaultProps = __small$_51,
colorDefaults = defaultProps.color,
terms = __small$_50.colors;
exports = {
defaultProps: {
Red: colorDefaults,
Green: colorDefaults,
Blue: colorDefaults,
Alpha: defaultProps.opacity
},
test: function (value) {
return (value && value.indexOf('rgb') > -1);
},
split: function (value) {
return getColorValues(value, terms);
},
combine: function (values) {
return functionCreate(createDelimited(values, terms, ', ', 2), 'rgba');
}
};
return exports;
})();
var __small$_15 = (function() {
var exports = {};
"use strict";
var rgb = __small$_14;
exports = {
defaultProps: rgb.defaultProps,
test: function (value) {
return (value && value.indexOf('#') > -1);
},
split: function (value) {
var r, g, b;
// If we have 6 characters, ie #FF0000
if (value.length > 4) {
r = value.substr(1, 2);
g = value.substr(3, 2);
b = value.substr(5, 2);
// Or we have 3 characters, ie #F00
} else {
r = value.substr(1, 1);
g = value.substr(2, 1);
b = value.substr(3, 1);
r += r;
g += g;
b += b;
}
return {
Red: parseInt(r, 16),
Green: parseInt(g, 16),
Blue: parseInt(b, 16),
Alpha: 1
};
},
combine: function (values) {
return rgb.combine(values);
}
};
return exports;
})();
var __small$_16 = (function() {
var exports = {};
"use strict";
var utils = __small$_40,
rgb = __small$_14,
hsl = __small$_13,
hex = __small$_15,
supported = [rgb, hsl, hex],
numSupported = 3,
runSupported = function (method, value) {
for (var i = 0; i < numSupported; i++) {
if (supported[i].test(value)) {
return supported[i][method](value);
}
}
};
exports = {
defaultProps: utils.merge(rgb.defaultProps, hsl.defaultProps),
test: function (value) {
return rgb.test(value) || hex.test(value) || hsl.test(value);
},
split: function (value) {
return runSupported('split', value);
},
combine: function (values) {
return (values.Red) ? rgb.combine(values) : hsl.combine(values);
}
};
return exports;
})();
"use strict";
var popmotion = ((function() {
var exports = {};
var __small$_35 = (function() {
var exports = {};
"use strict";
var ModManager = __small$_59,
valueTypeManager = new ModManager();
valueTypeManager.defaultProps = function (type, key) {
var valueType = this[type],
defaultProps = (valueType.defaultProps) ? valueType.defaultProps[key] || valueType.defaultProps : {};
return defaultProps;
};
valueTypeManager.test = function (value) {
var type = false;
this.each(function (key, mod) {
if (mod.test && mod.test(value)) {
type = key;
}
});
return type;
};
exports = valueTypeManager;
return exports;
})();
var __small$_61 = (function() {
var exports = {};
"use strict";
/*
Generate method iterator
Takes a method name and returns a function that will
loop over all the Elements in a group and fire that
method with those properties
@param [string]: Name of method
*/
exports = function (method) {
return function () {
var numElements = this.elements.length,
i = 0,
isGetter = false,
getterArray = [],
actor,
actorReturn;
for (; i < numElements; i++) {
actor = this.elements[i];
actorReturn = actor[method].apply(actor, arguments);
if (actorReturn != actor) {
isGetter = true;
getterArray.push(actorReturn);
}
}
return (isGetter) ? getterArray : this;
};
};
return exports;
})();
var __small$_32 = (function() {
var exports = {};
"use strict";
var getterSetter = ((function() {
var exports = {};
/*
Multi-var getter/setter
@param [object || string]: Name of value to get/set
@param [string || number] (optional): Single property to set
@param [function]: Getter
@param [function]: Setter
*/
exports = function (opts, prop, getter, setter) {
var typeOfOpts = typeof opts;
// Set single, if this is a string and we have a property
if (typeOfOpts == 'string' && prop) {
setter.call(this, opts, prop);
// Set multi, if we have an object
} else if (typeOfOpts == 'object') {
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
setter.call(this, key, opts[key]);
}
}
// Or get, if we have a string and no props
} else {
return getter.call(this, opts);
}
return this;
};
return exports;
})()),
generateMethodIterator = __small$_61,
ModManager = __small$_59,
routeManager = new ModManager(),
Actor,
ActorCollection;
routeManager.extend = function (name, mod) {
// Generate getter/setter
if (mod.get && mod.set) {
Actor.prototype[name] = function (key, value) {
return getterSetter.call(this, key, value, mod.get, mod.set);
};
ActorCollection.prototype[name] = generateMethodIterator(name);
}
// Call parent extend method
ModManager.prototype.extend.call(this, name, mod);
};
/*
Shard function
Run callback once for every value route
@param [function]: Function to run for each route
@param [object] (optional): Object containing keys of routes to check
*/
routeManager.shard = function (callback, validRoutes) {
var key = '',
route = '',
routeIsValid = false,
i = 0;
for (; i < this._numKeys; i++) {
key = this._keys[i];
routeIsValid = (validRoutes && validRoutes.hasOwnProperty(key));
route = routeIsValid ? validRoutes[key] : {};
// If we've been given this route, or this is the default route ('values')
if (routeIsValid || key === 'values') {
callback(this[key], key, route);
}
}
};
routeManager.setActor = function (actor) {
Actor = actor;
};
routeManager.setActorCollection = function (actorCollection) {
ActorCollection = actorCollection;
};
exports = routeManager;
return exports;
})();
var __small$_31 = (function() {
var exports = {};
"use strict";
var Actor,
ActorCollection,
utils = __small$_40,
generateMethodIterator = __small$_61,
genericActionProps = ((function() {
var exports = {};
exports = {
// [number]: Delay this action by x ms
delay: 0,
// [function]: Callback when Action process starts
onStart: undefined,
// [function]: Callback when any value changes
onChange: undefined,
// [function]: Callback every frame
onFrame: undefined,
// [function]: Callback when Action process ends
onEnd: undefined
};
return exports;
})()),
genericValueProps = ((function() {
var exports = {};
exports = {
// [number]: Current target value
to: undefined,
// [number]: Maximum permitted value during .track and .run
min: undefined,
// [number]: Minimum permitted value during .track and .run
max: undefined,
// [number]: Origin
origin: 0,
// [boolean]: Set to true when both min and max detected
hasRange: false,
// [boolean]: Round output if true
round: false,
// [string]: Name of value to listen to
link: undefined
};
return exports;
})()),
ModManager = __small$_59,
actionManager = new ModManager();
/*
Add module to ActionManager
Creates a new Action for Actors
*/
actionManager.extend = function (name, mod) {
var methodName = '';
/*
Generate new method for Actors if module doesn't have a
surpressMethod flag and Actor doesn't already have a
method with that name
*/
if (!mod.surpressMethod && !Actor.prototype[name]) {
Actor.prototype[name] = function () {
this.action = name;
this.set(mod.parse.apply(this, arguments));
return this.start();
};
ActorCollection.prototype[name] = generateMethodIterator(name);
}
// If module has methods to add to Actor.prototype
if (mod.actorMethods) {
for (methodName in mod.actorMethods) {
if (mod.actorMethods.hasOwnProperty(methodName)) {
Actor.prototype[methodName] = mod.actorMethods[methodName];
ActorCollection.prototype[methodName] = generateMethodIterator(methodName);
}
}
}
// Merge action props with defaults
mod.actionDefaults = mod.actionDefaults ? utils.merge(genericActionProps, mod.actionDefaults) : genericActionProps;
// Merge value props with defaults
mod.valueDefaults = mod.valueDefaults ? utils.merge(genericValueProps, mod.valueDefaults) : genericValueProps;
// Call parent extend method
ModManager.prototype.extend.call(this, name, mod);
};
actionManager.setActor = function (actor) {
Actor = actor;
};
actionManager.setActorCollection = function (actorCollection) {
ActorCollection = actorCollection;
};
exports = actionManager;
return exports;
})();
var __small$_39 = (function() {
var exports = {};
"use strict";
var manager = ((function() {
var exports = {};
"use strict";
var theLoop = ((function() {
var exports = {};
/*
The loop
*/
"use strict";
var Timer = ((function() {
var exports = {};
"use strict";
var utils = __small$_40,
maxElapsed = 33,
Timer = function () {
this.elapsed = 16.7;
this.current = utils.currentTime();
this.update();
};
Timer.prototype = {
update: function () {
this.prev = this.current;
this.current = utils.currentTime();
this.elapsed = Math.min(this.current - this.prev, maxElapsed);
return this.current;
},
getElapsed: function () {
return this.elapsed;
},
clock: function () {
this.current = utils.currentTime();
}
};
exports = Timer;
return exports;
})()),
tick = ((function() {
var exports = {};
"use strict";
/*
requestAnimationFrame polyfill
For IE8/9 Flinstones
Taken from Paul Irish. We've stripped out cancelAnimationFrame checks because we don't fox with that
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
MIT license
*/
var tick,
lastTime = 0,
hasWindow = (typeof window !== 'undefined');
if (!hasWindow) {
// Load rAF shim
tick = function (callback) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
} else {
tick = window.requestAnimationFrame;
}
exports = tick;
return exports;
})()),
Loop = function () {
this.timer = new Timer();
};
Loop.prototype = {
/*
[boolean]: Current status of animation loop
*/
isRunning: false,
/*
Fire all active processes once per frame
*/
frame: function () {
var self = this;
tick(function () {
var framestamp = self.timer.update(), // Currently just measuring in ms - will look into hi-res timestamps
isActive = self.callback.call(self.scope, framestamp, self.timer.getElapsed());
if (isActive) {
self.frame();
} else {
self.stop();
}
});
},
/*
Start loop
*/
start: function () {
// Make sure we're not already running a loop
if (!this.isRunning) {
this.timer.clock();
this.isRunning = true;
this.frame();
}
},
/*
Stop the loop
*/
stop: function () {
this.isRunning = false;
},
/*
Set the callback to run every frame
@param [Object]: Execution context
@param [function]: Callback to fire
*/
setCallback: function (scope, callback) {
this.scope = scope;
this.callback = callback;
}
};
exports = new Loop();
return exports;
})()),
ProcessManager = function () {
this.activeIds = [];
this.activeProcesses = {};
this.deactivateQueue = [];
theLoop.setCallback(this, this.fireActive);
};
ProcessManager.prototype = {
/*
[int]: Used for process ID
*/
processCounter: 0,
/*
[int]: Number of active processes
*/
activeCount: 0,
/*
Get the process with a given index
@param [int]: Index of process
@return [Process]
*/
getProcess: function (i) {
return this.activeProcesses[i];
},
/*
Get number of active processes
@return [int]: Number of active processes
*/
getActiveCount: function () {
return this.activeCount;
},
/*
Get active tokens
@return [array]: Active tokens
*/
getActive: function () {
return this.activeIds;
},
/*
Get the length of the deactivate queue
@return [int]: Length of queue
*/
getQueueLength: function () {
return this.deactivateQueue.length;
},
/*
Fire all active processes
@param [int]: Timestamp of executing frames
@param [int]: Time since previous frame
@return [boolean]: True if active processes found
*/
fireActive: function (framestamp, elapsed) {
var process,
activeCount = 0,
activeIds = [],
i = 0;
// Purge and check active count before execution
this.purge();
activeCount = this.getActiveCount();
activeIds = this.getActive();
// Loop through active processes and fire callback
for (; i < activeCount; i++) {
process = this.getProcess(activeIds[i]);
if (process) {
process.fire(framestamp, elapsed);
}
}
// Repurge and recheck active count after execution
this.purge();
activeCount = this.getActiveCount();
// Return true if we still have active processes, or false if none
return activeCount ? true : false;
},
/*
Register a new process
@param [Process]
@return [int]: Index of process to be used as ID
*/
register: function () {
return this.processCounter++;
},
/*
Activate a process
@param [int]: Index of active process
*/
activate: function (process, i) {
var queueIndex = this.deactivateQueue.indexOf(i),
isQueued = (queueIndex > -1),
isActive = (this.activeIds.indexOf(i) > -1);
// Remove from deactivateQueue if in there
if (isQueued) {
this.deactivateQueue.splice(queueIndex, 1);
}
// Add to active processes array if not already in there
if (!isActive) {
this.activeIds.push(i);
this.activeProcesses[i] = process;
this.activeCount++;
theLoop.start();
}
},
/*
Deactivate a process
@param [int]: Index of process to add to deactivate queue
*/
deactivate: function (i) {
this.deactivateQueue.push(i);
},
/*
Purge the deactivate queue
*/
purge: function () {
var queueLength = this.getQueueLength(),
activeIdIndex = 0,
idToDelete = 0;
while (queueLength--) {
idToDelete = this.deactivateQueue[queueLength];
activeIdIndex = this.activeIds.indexOf(idToDelete);
// If process in active list deactivate
if (activeIdIndex > -1) {
this.activeIds.splice(activeIdIndex, 1);
this.activeCount--;
delete this.activeProcesses[idToDelete];
}
}
this.deactivateQueue = [];
}
};
exports = new ProcessManager();
return exports;
})()),
/*
Process constructor
Syntax
var process = new Process(scope, callback);
var process = new Process(callback);
*/
Process = function (scope, callback) {
var hasScope = (callback !== undefined);
this.callback = hasScope ? callback : scope;
this.scope = hasScope ? scope : this;
this.id = manager.register();
// [boolean]: Is this process currently active?
this.isActive = false;
};
Process.prototype = {
/*
Fire callback
@param [timestamp]: Timestamp of currently-executed frame
@param [number]: Time since last frame
*/
fire: function (timestamp, elapsed) {
// Check timers
if (this.isActive) {
this.callback.call(this.scope, timestamp, elapsed);
}
// If we're running at an interval, deactivate again
if (this.isInterval) {
this.deactivate();
}
return this;
},
/*
Start process
@param [int]: Duration of process in ms, 0 if indefinite
@return [this]
*/
start: function (duration) {
var self = this;
this.reset();
this.activate();
if (duration) {
this.stopTimer = setTimeout(function () {
self.stop();
}, duration);
this.isStopTimerActive = true;
}
return this;
},
/*
Stop process
@return [this]
*/
stop: function () {
this.reset();
this.deactivate();
return this;
},
/*
Activate process
@return [this]
*/
activate: function () {
this.isActive = true;
manager.activate(this, this.id);
return this;
},
/*
Deactivate process
@return [this]
*/
deactivate: function () {
this.isActive = false;
manager.deactivate(this.id);
return this;
},
/*
Fire process every x ms
@param [int]: Number of ms to wait between refiring process.
@return [this]
*/
every: function (interval) {
var self = this;
this.reset();
this.isInterval = true;
this.intervalTimer = setInterval(function () {
self.activate();
}, interval);
this.isIntervalTimeActive = true;
return this;
},
/*
Clear all timers
@param
*/
reset: function () {
this.isInterval = false;
if (this.isStopTimerActive) {
clearTimeout(this.stopTimer);
}
if (this.isIntervalTimeActive) {
clearInterval(this.intervalTimer);
}
return this;
}
};
exports = Process;
return exports;
})();
var __small$_36 = (function() {
var exports = {};
"use strict";
var Process = __small$_39,
Queue = ((function() {
var exports = {};
"use strict";
var Queue = function () {
this.clear();
};
Queue.prototype = {
/*
Add a set of arguments to queue
*/
add: function () {
this.queue.push([].slice.call(arguments));
},
/*
Get next set of arguments from queue
*/
next: function (direction) {
var queue = this.queue,
returnVal = false,
index = this.index;
direction = (arguments.length) ? direction : 1;
// If our index is between 0 and the queue length, return that item
if (index >= 0 && index < queue.length) {
returnVal = queue[index];
this.index = index + direction;
// Or clear
} else {
this.clear();
}
return returnVal;
},
/*
Replace queue with empty array
*/
clear: function () {
this.queue = [];
this.index = 0;
}
};
exports = Queue;
return exports;
})()),
utils = __small$_40,
update = ((function() {
var exports = {};
"use strict";
var actionManager = __small$_31,
routeManager = __small$_32,
valueTypeManager = __small$_35,
calc = __small$_24,
defaultRoute = 'values',
update = function (framestamp, frameDuration) {
var self = this,
values = this.values,
action = actionManager[this.action],
valueAction = action,
output = this.output,
numActiveValues = this.order.length,
numActiveParents = this.parentOrder.length,
key = '',
value = {},
updatedValue = 0,
i = 0;
// Update Input and attach new values to output
if (this.input) {
output.input = this.input.onFrame(framestamp);
}
// Update Action input
if (action.onFrameStart) {
action.onFrameStart.call(this, frameDuration);
}
// Fire onStart if first frame
if (this.firstFrame) {
routeManager.shard(function (route) {
if (route.onStart) {
route.onStart.call(self, values);
}
}, output);
}
// Create default route output if not present
output[defaultRoute] = output[defaultRoute] || {};
// Update values
for (; i < numActiveValues; i++) {
// Get value and key
key = this.order[i];
value = values[key];
// Load value-specific action
valueAction = value.link ? actionManager.link : action;
// Calculate new value
updatedValue = valueAction.process.call(this, value, key, frameDuration);
// Limit if range
if (valueAction.limit) {
updatedValue = valueAction.limit(updatedValue, value);
}
// Round value if round set to true
if (value.round) {
updatedValue = Math.round(updatedValue);
}
// Update change from previous frame
value.frameChange = updatedValue - value.current;
// Calculate velocity if Action hasn't already
if (!valueAction.calculatesVelocity) {
value.velocity = calc.speedPerSecond(value.frameChange, frameDuration);
}
// Update current speed
value.speed = Math.abs(value.velocity);
// Check if changed and update
if (value.current != updatedValue) {
this.hasChanged = true;
}
// Set current
this.values[key].current = updatedValue;
// Put value in default route output
output[defaultRoute][key] = (value.unit) ? updatedValue + value.unit : updatedValue;
// Put in specific root if not a parent
if (!value.parent) {
output[value.route][value.name] = output[defaultRoute][key];
// Or add to parent output, to be combined
} else {
output[value.parent] = output[value.parent] || {};
output[value.parent][value.propName] = output[defaultRoute][key];
}
}
// Update parent values from calculated children
for (i = 0; i < numActiveParents; i++) {
key = this.parentOrder[i];
value = this.values[key];
// Update parent value current property
value.current = valueTypeManager[value.type].combine(output[key]);
// Update output
output[value.route][value.name] = output[defaultRoute][key] = value.current;
}
// Run onFrame and onChange for every output
routeManager.shard(function (route, routeName, routeOutput) {
// Fire onFrame every frame
if (route.onFrame) {
route.onFrame.call(self, routeOutput);
}
// Fire onChanged if any value has changed
if (self.hasChanged && route.onChange || self.firstFrame && route.onChange) {
route.onChange.call(self, routeOutput);
}
}, output);
// Fire onEnd if this Action has ended
if (action.hasEnded.call(this, this.hasChanged)) {
this.isActive = false;
routeManager.shard(function (route, routeName, routeOutput) {
if (route.onEnd) {
route.onEnd.call(self, routeOutput);
}
}, output);
// If is a play action, and is not active, check next action
if (!this.isActive && this.action === 'play' && this.next) {
this.next();
}
} else {
this.hasChanged = false;
}
this.firstFrame = false;
this.framestamp = framestamp;
};
exports = function () {
if (this.isActive) {
update.apply(this, arguments);
}
};
return exports;
})()),
valueOps = ((function() {
var exports = {};
"use strict";
var calc = __small$_24,
utils = __small$_40,
isNum = utils.isNum,
actionsManager = __small$_31,
valueTypesManager = __small$_35,
routeManager = __small$_32,
numericalValues = ['current', 'to', 'init', 'min', 'max'],
numNumericalValues = numericalValues.length;
exports = {
/*
Perform operation on set of values
@parma [string]: Name of operation
@param [object]: Value object
*/
all: function (op, values) {
var key = '';
for (key in values) {
if (values.hasOwnProperty(key)) {
this[op](values[key]);
}
}
return this;
},
/*
Reset the value current to its origin
@param [object]: Value object
*/
reset: function (value) {
this.retarget(value);
value.current = value.origin;
},
/*
Set value origin property to current value
@param [object]: Value object
*/
resetOrigin: function (value) {
value.origin = value.current;
},
/*
Set value to property back to target
@param [object]: Value object
*/
retarget: function (value) {
value.to = value.target;
},
/*
Swap value to and origin property
@param [object]: Value object
*/
flip: function (value) {
var newOrigin = (value.target !== undefined) ? value.target : value.current;
value.target = value.to = value.origin;
value.origin = newOrigin;
},
/*
Returns an initial value state
@param [number] (optional): Initial current
@return [object]: Default value state
*/
initialState: function (start, route) {
return {
// [number]: Current value
current: start || 0,
// [number]: Change per second
speed: 0,
// [number]: Change per second plus direction (ie can be negative)
velocity: 0,
// [number]: Amount value has changed in the most recent frame
frameChange: 0,
route: route
};
},
/*
Split value into sub-values
@param [string]: Name of value
@param [object]: Base value properties
@param [Elememt]
*/
split: function (name, value, actor, valueType) {
var splitValues = {},
splitProperty = {},
propertyName = '',
key = '',
i = 0;
for (; i < numNumericalValues; i++) {
propertyName = numericalValues[i];
if (value.hasOwnProperty(propertyName)) {
if (utils.isFunc(value[propertyName])) {
value[propertyName] = value[propertyName].call(actor);
}
splitProperty = valueType.split(value[propertyName]);
// Assign properties to each new value
for (key in splitProperty) {
if (splitProperty.hasOwnProperty(key)) {
// Create new value if it doesn't exist
splitValues[key] = splitValues[key] || utils.copy(valueTypesManager.defaultProps(value.type, key));
splitValues[key][propertyName] = splitProperty[key];
}
}
}
}
return splitValues;
},
/*
Split value into number and unit, set unit to value if present
@param [string]: Property to split
@param [object]: Value object to save unit to
*/
splitUnit: function (property, value) {
var returnVal = property,
splitUnitValue;
// Check for unit property
if (utils.isString(property)) {
splitUnitValue = utils.splitValUnit(property);
if (!isNaN(splitUnitValue.value)) {
returnVal = splitUnitValue.value;
value.unit = splitUnitValue.unit;
}
}
return returnVal;
},
/*
Resolve property
@param [string]: Name of value
@param [string || number || function]: Property
@param [object]: Parent value
@param [actor]: Parent actor
*/
resolve: function (name, property, value, actor) {
var currentValue = value.current || 0,
isNumericalValue = (numericalValues.indexOf(name) > -1);
// If this is a function, resolve
if (utils.isFunc(property)) {
property = property.call(actor, currentValue);
}
// If this is a string, check for relative values and units
if (utils.isString(property)) {
// If this is a relative value (ie '+=10')
if (property.indexOf('=') > 0) {
property = calc.relativeValue(currentValue, property);
}
// Check for unit if should be numerical property
if (isNumericalValue) {
this.splitUnit(property, value);
}
}
// If this is a numerical value, coerce
if (isNumericalValue) {
property = parseFloat(property);
}
return property;
},
/*
Process new values
*/
preprocess: function (values, actor, route, suffix, defaultValueProp) {
var preprocessedValues = {},
value = {},
splitValue = {},
childValue = {},
type = {},
existingValue = {},
isValueObj = false,
key = '',
namespacedKey = '',
propKey = '';
defaultValueProp = defaultValueProp || 'current';
for (key in values) {
if (values.hasOwnProperty(key)) {
isValueObj = utils.isObj(values[key]);
value = (isValueObj) ? values[key] : {};
namespacedKey = key + suffix;
existingValue = actor.values[namespacedKey];
value.name = key;
if (!isValueObj) {
value[defaultValueProp] = values[key];
}
// If this value doesn't have a special type, check for one
if (!value.type) {
// Check if existing value with this key
if (existingValue && existingValue.type) {
value.type = existingValue.type;
// Or if this route has a typemap
} else if (route.typeMap && route.typeMap[key]) {
value.type = route.typeMap[key];
// Otherwise, check by running tests if this is a string
} else if (utils.isString(value[defaultValueProp])) {
value.type = valueTypesManager.test(value[defaultValueProp]);
}
}
// Set value
preprocessedValues[namespacedKey] = value;
// If process has type, split or assign default props
if (value.type) {
type = valueTypesManager[value.type];
// If this has a splitter function, split
if (type.split) {
value.children = {};
splitValue = this.split(key, value, actor, type);
for (propKey in splitValue) {
if (splitValue.hasOwnProperty(propKey)) {
childValue = utils.merge(value, splitValue[propKey]);
childValue.parent = key + suffix;
childValue.name = key;
childValue.propName = propKey;
delete childValue.type;
delete childValue.children;
preprocessedValues[key + propKey + suffix] = childValue;
}
}
} else {
preprocessedValues[namespacedKey] = utils.merge(valueTypesManager.defaultProps(value.type, key), value);
}
}
}
}
return preprocessedValues;
},
/*
Process new values
*/
process: function (values, actor, namespace, defaultValueProp) {
var route = routeManager[namespace],
namespaceSuffix = (namespace === 'values') ? '' : '.' + namespace,
preprocessedValues = this.preprocess(values, actor, route, namespaceSuffix, defaultValueProp),
key = '',
propKey = '',
preprocessedValue = {},
thisValue = {},
defaultProps = {},
hasChildren = false,
prop;
for (key in preprocessedValues) {
if (preprocessedValues.hasOwnProperty(key)) {
preprocessedValue = preprocessedValues[key];
thisValue = actor.values[key] || this.initialState(this.resolve('init', preprocessedValue.init, {}, actor), namespace);
hasChildren = (preprocessedValue.children !== undefined);
thisValue.action = preprocessedValue.link ? 'link' : actor.action;
defaultProps = actionsManager[thisValue.action].valueDefaults;
// Inherit properties from Actor
for (propKey in defaultProps) {
if (defaultProps.hasOwnProperty(propKey)) {
thisValue[propKey] = (actor.hasOwnProperty(propKey)) ? actor[propKey] : defaultProps[propKey];
}
}
// Loop through all properties and resolve
for (propKey in preprocessedValue) {
if (preprocessedValue.hasOwnProperty(propKey)) {
prop = preprocessedValue[propKey];
// If property is *not* undefined or a number, resolve
if (prop !== undefined && !isNum(prop) && !hasChildren) {
prop = this.resolve(propKey, prop, thisValue, actor);
}
thisValue[propKey] = prop;
// Set internal target if this property is 'to'
if (propKey === 'to') {
thisValue.target = thisValue.to;
}
}
}
thisValue.origin = thisValue.current;
thisValue.hasRange = (isNum(thisValue.min) && isNum(thisValue.max)) ? true : false;
actor.values[key] = thisValue;
actor.updateOrder(key, utils.isString(thisValue.link), hasChildren);
}
}
}
};
return exports;
})()),
actionManager = __small$_31,
routeManager = __small$_32,
Actor = function (element) {
this.element = element || false;
this.values = {};
this.output = {};
this.queue = new Queue();
this.process = new Process(this, update);
this.clearOrder();
};
Actor.prototype = {
/*
Set Action values and properties
@param [object]: Element properties
@param [string] (option): Name of default value property
*/
set: function (props, defaultValueProp) {
var self = this;
// Reset Element properties and write new props
this.clearOrder();
this.resetProps();
this.setProps(props);
// Loop over routes and process value definitions
routeManager.shard(function (route, routeName, values) {
// Create output object for this route if none exists
self.output[routeName] = self.output[routeName] || {};
// Set values
self.setValues(values, routeName, defaultValueProp);
}, props);
return this;
},
/*
Start currently defined Action
*/
start: function () {
this.resetProgress();
this.activate();
if (this.action !== 'track' && this.input && this.input.stop) {
this.input.stop();
}
return this;
},
/*
Stop current Action
*/
stop: function () {
this.queue.clear();
this.pause();
return this;
},
/*
Pause current Action
*/
pause: function () {
this.isActive = false;
this.process.stop();
return this;
},
/*
Resume paused Action
*/
resume: function () {
this.framestamp = this.started = utils.currentTime();
this.isActive = true;
this.process.start();
return this;
},
/*
Toggle current Action
*/
toggle: function () {
if (this.isActive) {
this.pause();
} else {
this.resume();
}
return this;
},
/*
Activate Element Action
*/
activate: function () {
this.isActive = true;
this.started = utils.currentTime() + this.delay;
this.framestamp = this.started;
this.firstFrame = true;
this.process.start();
},
reset: function () {
this.resetProgress();
valueOps.all('reset', this.values);
return this;
},
/*
Reset Action progress
*/
resetProgress: function () {
this.elapsed = (this.playDirection === 1) ? 0 : this.duration;
this.started = utils.currentTime();
return this;
},
/*
Loop through all values and create origin points
*/
resetOrigins: function () {
valueOps.all('resetOrigin', this.values);
return this;
},
/*
Reverse Action progress and values
*/
reverse: function () {
this.playDirection *= -1;
valueOps.all('retarget', this.values);
return this;
},
/*
Swap value origins and to
*/
flipValues: function () {
this.elapsed = this.duration - this.elapsed;
valueOps.all('flip', this.values);
return this;
},
/*
Set properties
@param [object]: Properties to set
*/
setProps: function (props) {
var key = '';
for (key in props) {
// Set if this isn't a route
if (props.hasOwnProperty(key) && !routeManager.hasOwnProperty(key)) {
this[key] = props[key];
}
}
},
/*
Reset properties to Action defaults
*/
resetProps: function () {
this.setProps(actionManager[this.action].actionDefaults);
return this;
},
/*
Set values
@param [object || string || number]: Value
@param [string] (optional): Name of route
@param [string] (optional): Default property to set
*/
setValues: function (values, namespace, defaultValueProp) {
valueOps.process(values, this, namespace, defaultValueProp);
return this;
},
/*
Update order of value keys
@param [string]: Key of value
@param [boolean]: Whether to move value to back
*/
updateOrder: function (key, moveToBack, hasChildren) {
var order = !hasChildren ? this.order : this.parentOrder,
position = order.indexOf(key);
// If key isn't in list, or moveToBack is set to true, add key
if (position === -1 || moveToBack) {
order.push(key);
// If key already exists, remove
if (position !== -1) {
order.splice(position, 1);
}
}
return this;
},
/*
Clear value key update order
*/
clearOrder: function () {
this.order = [];
this.parentOrder = [];
return this;
},
// [boolean]: Is this Element currently active?
get isActive() {
return this._isActive;
},
/*
Set Element active status
If active is being set to true, set hasChanged to true, too
@param [boolean]: New active status
*/
set isActive(status) {
if (status === true) {
this.hasChanged = status;
}
this._isActive = status;
}
};
// Register Actor with actionManager, so when a new Action is set,
// We get a new method on Actor
actionManager.setActor(Actor);
routeManager.setActor(Actor);
exports = Actor;
return exports;
})();
var __small$_37 = (function() {
var exports = {};
"use strict";
var Actor = __small$_36,
generateMethodIterator = __small$_61,
utils = __small$_40,
actionManager = __small$_31,
routeManager = __small$_32,
DEFAULT_STAGGER_EASE = 'linear',
/*
ActorCollection constructor
@param [array]: Array of Actors, or valid Actor elements
*/
ActorCollection = function (elements) {
// Add initial elements
this.clear();
if (elements) {
this.add(elements);
}
// Create stagger Actor
this._stagger = new Actor();
};
ActorCollection.prototype = {
/*
Clear current Actors
*/
clear: function () {
this.elements = [];
return this;
},
/*
Stagger the execution of Element methods
@param [number || object]: Interval between Elements or stagger options
@param [string || function]: Name of method to execute or a callback
@args ... (optional): Optional arguments to send to callback
*/
stagger: function (props, method) {
var self = this,
args = [].slice.call(arguments),
numElements = this.elements.length,
propsIsNum = utils.isNum(props),
interval = propsIsNum ? props : props.interval,
staggerProps = propsIsNum ? {} : props,
i = -1,
callback = utils.isString(method) ?
function (actor) {
actor[method].apply(actor, args);
} : method;
args.splice(0, 2);
staggerProps.values = {
i: {
current: 0,
duration: interval * numElements,
ease: propsIsNum ? DEFAULT_STAGGER_EASE : props.ease || DEFAULT_STAGGER_EASE,
steps: numElements,
round: true,
to: numElements - 1
}
};
staggerProps.onChange = function (output) {
var newIndex = output.i,
gapIndex = i + 1;
// If our new index is only one more than the previous index, fire immedietly
if (newIndex === i + 1) {
callback(self.elements[gapIndex], gapIndex);
// Or loop through the distance to fire all indecies. Increase delay.
} else {
for (; gapIndex <= newIndex; gapIndex++) {
callback(self.elements[gapIndex], gapIndex);
}
}
i = newIndex;
};
this._stagger.play(staggerProps);
return this;
},
/*
Add a group of Actors to our Collection
@param [array]: Array of Actors, or valid Actor elements
*/
add: function (elements) {
var numNewElements = elements.length,
i = 0,
newElement;
for (; i < numNewElements; i++) {
newElement = (elements[i] instanceof Actor) ? elements[i] : new Actor(elements[i]);
this.elements.push(newElement);
}
return this;
}
};
// Initialise ActorCollection methods
(function () {
for (var method in Actor.prototype) {
if (Actor.prototype.hasOwnProperty(method)) {
ActorCollection.prototype[method] = generateMethodIterator(method);
}
}
})();
actionManager.setActorCollection(ActorCollection);
routeManager.setActorCollection(ActorCollection);
exports = ActorCollection;
return exports;
})();
"use strict";
var select = ((function() {
var exports = {};
"use strict";
var ActorCollection = __small$_37;
/*
Create an ActorCollection based on a selection of DOM nodes
@param [string || NodeList || jQuery object]:
If string, treated as selector.
If not, treated as preexisting NodeList || jQuery object.
*/
exports = function (selector) {
var nodes = (typeof selector === 'string') ? document.querySelectorAll(selector) : selector,
elements = [];
// If jQuery selection, get array of Elements
if (nodes.get) {
elements = nodes.get();
// Or convert NodeList to array
} else if (nodes.length) {
elements = [].slice.call(nodes);
// Or if it's just an Element, put into array
} else {
elements.push(nodes);
}
return new ActorCollection(elements, { type: 'dom' });
};
return exports;
})()),
actionManager = __small$_31,
easingManager = __small$_30,
presetManager = __small$_33,
routeManager = __small$_32,
simulationManager = __small$_34,
valueTypeManager = __small$_35,
calc = __small$_24,
Actor = __small$_36,
ActorCollection = __small$_37,
Input = __small$_38,
Process = __small$_39,
Popmotion = {
Actor: Actor,
ActorCollection: ActorCollection,
Input: Input,
Process: Process,
select: function (items) {
return select(items);
},
addAction: function () {
actionManager.extend.apply(actionManager, arguments);
return this;
},
addEasing: function () {
easingManager.extend.apply(easingManager, arguments);
return this;
},
addPreset: function () {
presetManager.extend.apply(presetManager, arguments);
return this;
},
addSimulation: function () {
simulationManager.extend.apply(simulationManager, arguments);
return this;
},
addValueType: function () {
valueTypeManager.extend.apply(valueTypeManager, arguments);
return this;
},
addRoute: function () {
routeManager.extend.apply(routeManager, arguments);
return this;
},
calc: calc
};
exports = Popmotion;
return exports;
})());
popmotion
/*
Core route
*/
.addRoute('values', ((function() {
var exports = {};
/*
Values route (Redshift default)
Handles raw values and outputs to user-defined callbacks
*/
"use strict";
var valuesRoute = {},
fireCallback = function (name, output, actor) {
if (actor[name]) {
actor[name].call(actor, output);
}
};
['onStart', 'onFrame', 'onChange', 'onEnd'].forEach(function (key) {
valuesRoute[key] = function (output) {
fireCallback(key, output, this);
};
});
exports = valuesRoute;
return exports;
})()))
/*
Core Actions
*/
.addAction('play', __small$_4)
.addAction('run', ((function() {
var exports = {};
/*
Run physics simulation
*/
"use strict";
var calc = __small$_24,
simulate = ((function() {
var exports = {};
"use strict";
var simulations = __small$_34;
exports = function (simulation, value, duration, started) {
var velocity = simulations[simulation](value, duration, started);
return (Math.abs(velocity) >= value.stopSpeed) ? velocity : 0;
};
return exports;
})());
exports = {
// [object] Default Action properties
actionDefaults: ((function() {
var exports = {};
exports = {
// [int]: Number of frames Action has been inactive
inactiveFrames: 0,
// [number]: Number of frames of no change before Action is declared inactive
maxInactiveFrames: 3
};
return exports;
})()),
// [object] Default value properties
valueDefaults: ((function() {
var exports = {};
exports = {
// [string]: Simulation to .run
simulate: 'velocity',
// [number]: Deceleration to apply to value, in units per second
deceleration: 0,
// [number]: Acceleration to apply to value, in units per second
acceleration: 0,
// [number]: Factor to multiply velocity by on bounce
bounce: 0,
// [number]: Spring strength during 'string'
spring: 80,
// [number]: Timeconstant of glide
timeConstant: 395,
// [number]: Stop simulation under this speed
stopSpeed: 5,
// [boolean]: Capture with spring physics on limit breach
capture: false,
// [number]: Friction to apply per frame
friction: 0
};
return exports;
})()),
parse: __small$_28,
// [boolean]: Tell Redshift this rubix calculates a new velocity itself
calculatesVelocity: true,
/*
Simulate the Value's per-frame movement
@param [Value]: Current value
@param [string]: Key of current value
@param [number]: Duration of frame in ms
@return [number]: Calculated value
*/
process: function (value, key, frameDuration) {
value.velocity = simulate(value.simulate, value, frameDuration, this.started);
return value.current + calc.speedPerFrame(value.velocity, frameDuration);
},
/*
Has this action ended?
Use a framecounter to see if Action has changed in the last x frames
and declare ended if not
@param [boolean]: Has Action changed?
@return [boolean]: Has Action ended?
*/
hasEnded: function (hasChanged) {
this.inactiveFrames = hasChanged ? 0 : this.inactiveFrames + 1;
return (this.inactiveFrames > this.maxInactiveFrames);
},
/*
Limit output to value range, if any
If velocity is at or more than range, and value has a bounce property,
run the bounce simulation
@param [number]: Calculated output
@param [Value]: Current Value
@return [number]: Limit-adjusted output
*/
limit: function (output, value) {
var isOutsideMax = (output >= value.max),
isOutsideMin = (output <= value.min),
isOutsideRange = isOutsideMax || isOutsideMin;
if (isOutsideRange) {
output = calc.restricted(output, value.min, value.max);
if (value.bounce) {
value.velocity = simulate('bounce', value);
} else if (value.capture) {
simulate('capture', value, isOutsideMax ? value.max : value.min);
}
}
return output;
}
};
return exports;
})()))
.addAction('fire', ((function() {
var exports = {};
/*
Return current value and immedietly end
*/
"use strict";
exports = {
parse: __small$_28,
/*
Process new value
Return existing current
@param [Value]: Current value
*/
process: function (value) {
return value.current;
},
/*
Has Action ended?
Returns true to end immedietly
@return [boolean]: true
*/
hasEnded: function () {
return true;
}
};
return exports;
})()))
.addAction('track', ((function() {
var exports = {};
/*
Track user input
*/
"use strict";
var calc = __small$_24,
genericParser = __small$_28,
Pointer = ((function() {
var exports = {};
"use strict";
var Input = __small$_38,
currentPointer, // Sort this out for multitouch
TOUCHMOVE = 'touchmove',
MOUSEMOVE = 'mousemove',
/*
Convert event into point
Scrape the x/y coordinates from the provided event
@param [event]: Original pointer event
@param [boolean]: True if touch event
@return [object]: x/y coordinates of event
*/
eventToPoint = function (event, isTouchEvent) {
var touchChanged = isTouchEvent ? event.changedTouches[0] : false;
return {
x: touchChanged ? touchChanged.clientX : event.pageX,
y: touchChanged ? touchChanged.clientY : event.pageY
};
},
/*
Get actual event
Checks for jQuery's .originalEvent if present
@param [event | jQuery event]
@return [event]: The actual JS event
*/
getActualEvent = function (event) {
return event.originalEvent || event;
},
/*
Pointer constructor
*/
Pointer = function (e) {
var event = getActualEvent(e), // In case of jQuery event
isTouch = (event.touches) ? true : false,
startPoint = eventToPoint(event, isTouch);
this.update(startPoint);
this.isTouch = isTouch;
this.bindEvents();
},
proto = Pointer.prototype = new Input();
/*
Bind move event
*/
proto.bindEvents = function () {
this.moveEvent = this.isTouch ? TOUCHMOVE : MOUSEMOVE;
currentPointer = this;
document.documentElement.addEventListener(this.moveEvent, this.onMove);
};
/*
Unbind move event
*/
proto.unbindEvents = function () {
document.documentElement.removeEventListener(this.moveEvent, this.onMove);
};
/*
Pointer onMove event handler
@param [event]: Pointer move event
*/
proto.onMove = function (e) {
var newPoint = eventToPoint(e, currentPointer.isTouch);
e = getActualEvent(e);
e.preventDefault();
currentPointer.update(newPoint);
};
proto.stop = function () {
this.unbindEvents();
};
exports = Pointer;
return exports;
})());
exports = {
valueDefaults: ((function() {
var exports = {};
exports = {
amp: 1,
// [number]: Factor of movement outside of maximum range (ie 0.5 will move half as much as 1)
escapeAmp: 0
};
return exports;
})()),
/*
Parse Input arguments
*/
parse: function () {
var args = [].slice.call(arguments),
input = args.pop(),
props = genericParser.apply(this, args);
// Create Pointer if this isn't an Input
props.input = (!input.current) ? new Pointer(input) : input;
// Set input origin if not user-defined
if (!props.inputOrigin) {
props.inputOrigin = props.input.get();
}
return props;
},
/*
Update input offset
*/
onFrameStart: function () {
this.inputOffset = calc.offset(this.inputOrigin, this.input.current);
},
/*
Move Value relative to Input movement
@param [Value]: Current value
@param [string]: Key of current value
@return [number]: Calculated value
*/
process: function (value, key) {
return (this.inputOffset.hasOwnProperty(key)) ? value.origin + this.inputOffset[key] : value.current;
},
/*
Has this Action ended?
@return [boolean]: False to make user manually finish .track()
*/
hasEnded: function () {
return false;
}
};
return exports;
})()))
.addAction('link', ((function() {
var exports = {};
/*
Link the calculations of on Value into the output of another.
Activate by setting the link property of one value with the name
of either an Input property or another Value.
Map the linked value with mapLink and provide a corressponding mapTo
array to translate values from one into the other. For instance:
{
link: 'x',
mapLink: [0, 100, 200],
mapTo: [-100, 0, -100]
}
An output value of 50 from 'x' will translate to -50 for this Value
*/
"use strict";
var calc = __small$_24,
STRING = 'string',
/*
Translate our mapLink value into mapTo
@param [number]: Calculated value from linked value
@param [Value || object]: Linked value or empty object if we're linking to input
@param [array]: List of numbers relating to linked value
@param [array]: List of numbers relating to this value
*/
findMappedValue = function (newValue, linkedValue, toValue, mapLink, mapTo) {
var mapLength = mapLink.length,
i = 1,
lastLinkValue,
thisLinkValue,
lastToValue,
thisToValue;
for (; i < mapLength; i++) {
// Assign values from array, or if they're strings, look for them in linkedValue
lastLinkValue = (typeof mapLink[i - 1] === STRING) ? linkedValue[mapLink[i - 1]] : mapLink[i - 1];
thisLinkValue = (typeof mapLink[i] === STRING) ? linkedValue[mapLink[i]] : mapLink[i];
lastToValue = (typeof mapTo[i - 1] === STRING) ? toValue[mapTo[i - 1]] : mapTo[i - 1];
thisToValue = (typeof mapTo[i] === STRING) ? toValue[mapTo[i]] : mapTo[i];
// Check if we've gone past our calculated value, or if we're at the end of the array
if (newValue < thisLinkValue || i === mapLength - 1) {
newValue = calc.value(calc.restricted(calc.progress(newValue, lastLinkValue, thisLinkValue), 0, 1), lastToValue, thisToValue);
break;
}
}
return newValue;
};
exports = {
valueDefaults: ((function() {
var exports = {};
exports = {
// [array]: Linear range of values (eg [-100, -50, 50, 100]) of linked value to map to .mapTo
mapLink: undefined,
// [array]: Non-linear range of values (eg [0, 1, 1, 0]) to map to .mapLink - here the linked value being 75 would result in a value of 0.5
mapTo: undefined,
// [number]: Factor of input movement to direct output
amp: 1
}
return exports;
})()),
surpressMethod: true,
/*
Process this value
First check if this value exists as a Value, if not
check within Input (if we have one)
@param [Value]: Current value
@param [string]: Key of current value
@return [number]: Calculated value
*/
process: function (value, key) {
var values = this.values,
newValue = value.current,
linkKey = value.link,
linkedValue = values[linkKey] ? values[linkKey] : {},
inputOffset = this.inputOffset;
// Then check values in Input
if (inputOffset && inputOffset.hasOwnProperty(linkKey)) {
newValue = value.origin + (inputOffset[linkKey] * value.amp);
// First look at Action and check value isn't linking itself
} else if (linkedValue.current !== undefined && key !== linkKey) {
newValue = linkedValue.current;
}
// If we have mapLink and mapTo properties, translate the new value
if (value.mapLink && value.mapTo) {
newValue = findMappedValue(newValue, linkedValue, value, value.mapLink, value.mapTo);
}
return newValue;
},
limit: function (output, value) {
return calc.restricted(output, value.min, value.max);
}
};
return exports;
})()))
/*
Seek Action - depedent on 'play' Action
*/
.addAction('seek', ((function() {
var exports = {};
/*
Return current value and immedietly end
*/
"use strict";
var play = __small$_4;
exports = {
surpressMethod: true,
actorMethods: {
seek: function (seekTo) {
this.elapsed = this.duration * seekTo;
if (!this.isActive) {
this.action = 'seek';
this.activate();
}
return this;
}
},
/*
Process new value
Return existing current
@param [string]: Name of value
@param [Value]: Current value
*/
process: play.process,
/*
Has Action ended?
Returns true to end animation, and sets rubix to 'play'
@return [boolean]: true
*/
hasEnded: function () {
this.rubix = 'play';
return true;
}
};
return exports;
})()))
/*
Optional value type support
*/
.addValueType({
alpha: ((function() {
var exports = {};
exports = {
defaultProps: {
min: 0,
max: 1
}
};
return exports;
})()),
angle: ((function() {
var exports = {};
exports = {
defaultProps: {
unit: 'deg'
}
};
return exports;
})()),
px: __small$_12,
hsl: __small$_13,
rgb: __small$_14,
hex: __small$_15,
color: __small$_16,
positions: ((function() {
var exports = {};
"use strict";
var createDelimited = __small$_47,
pxDefaults = __small$_12.defaultProps,
splitSpaceDelimited = __small$_52,
terms = __small$_50.positions;
exports = {
defaultProps: pxDefaults,
/*
Split positions in format "X Y Z"
@param [string]: Position values
"20% 30% 0" -> {20%, 30%, 0}
"20% 30%" -> {20%, 30%}
"20%" -> {20%, 20%}
*/
split: function (value) {
var positions = splitSpaceDelimited(value),
numPositions = positions.length,
splitValue = {
X: positions[0],
Y: (numPositions > 1) ? positions[1] : positions[0]
};
if (numPositions > 2) {
splitValue.Z = positions[2];
}
return splitValue;
},
combine: function (values) {
return createDelimited(values, terms, ' ');
}
};
return exports;
})()),
dimensions: ((function() {
var exports = {};
"use strict";
var terms = __small$_50.dimensions,
pxDefaults = __small$_12.defaultProps,
createDelimited = __small$_47,
splitSpaceDelimited = __small$_52;
exports = {
defaultProps: pxDefaults,
/*
Split dimensions in format "Top Right Bottom Left"
@param [string]: Dimension values
"20px 0 30px 40px" -> {20px, 0, 30px, 40px}
"20px 0 30px" -> {20px, 0, 30px, 0}
"20px 0" -> {20px, 0, 20px, 0}
"20px" -> {20px, 20px, 20px, 20px}
@return [object]: Object with T/R/B/L metrics
*/
split: function (value) {
var dimensions = splitSpaceDelimited(value),
numDimensions = dimensions.length,
jumpBack = (numDimensions !== 1) ? 2 : 1,
i = 0,
j = 0,
splitValue = {};
for (; i < 4; i++) {
splitValue[terms[i]] = dimensions[j];
// Jump back (to start) counter if we've reached the end of our values
j++;
j = (j === numDimensions) ? j - jumpBack : j;
}
return splitValue;
},
combine: function (values) {
return createDelimited(values, terms, ' ');
}
};
return exports;
})()),
shadow: ((function() {
var exports = {};
"use strict";
var color = __small$_16,
utils = __small$_40,
pxDefaults = __small$_12.defaultProps,
terms = __small$_50.shadow,
splitSpaceDelimited = __small$_52,
createDelimited = __small$_47,
shadowTerms = terms.slice(0,4);
exports = {
defaultProps: utils.merge(color.defaultProps, {
X: pxDefaults,
Y: pxDefaults,
Radius: pxDefaults,
Spread: pxDefaults
}),
/*
Split shadow properties "X Y Radius Spread Color"
@param [string]: Shadow property
@return [object]
*/
split: function (value) {
var bits = splitSpaceDelimited(value),
numBits = bits.length,
hasReachedColor = false,
colorProp = '',
thisBit,
i = 0,
splitValue = {};
for (; i < numBits; i++) {
thisBit = bits[i];
// If we've reached the color property, append to color string
if (hasReachedColor || color.test(thisBit)) {
hasReachedColor = true;
colorProp += thisBit;
} else {
splitValue[terms[i]] = thisBit;
}
}
return utils.merge(splitValue, color.split(colorProp));
},
combine: function (values) {
return createDelimited(values, shadowTerms, ' ') + color.combine(values);
}
};
return exports;
})())
})
/*
CSS/Attr route - dependent on core value types being present
*/
.addRoute('css', ((function() {
var exports = {};
/*
DOM CSS route
==============================================
*/
"use strict";
var build = ((function() {
var exports = {};
"use strict";
var transformDictionary = ((function() {
var exports = {};
"use strict";
var positionTerms = __small$_50.positions,
numPositionTerms = positionTerms.length,
TRANSFORM_PERSPECTIVE = 'transformPerspective',
SCALE = 'scale',
ROTATE = 'rotate',
terms = {
funcs: ['translate', SCALE, ROTATE, 'skew', TRANSFORM_PERSPECTIVE],
props: {} // objects are faster at direct lookups
};
// Create transform terms
(function () {
var funcs = terms.funcs,
props = terms.props,
numFuncs = funcs.length,
i = 0,
createProps = function (funcName) {
var j = 0;
for (; j < numPositionTerms; j++) {
props[funcName + positionTerms[j]] = true;
}
};
// Manually add skew and transform perspective
props[ROTATE] = props[SCALE] = props[TRANSFORM_PERSPECTIVE] = true;
// Loop over each function name and create function/property terms
for (; i < numFuncs; i++) {
createProps(funcs[i]);
}
})();
exports = terms;
return exports;
})()),
transformProps = transformDictionary.props,
TRANSFORM = 'transform',
TRANSLATE_Z = 'translateZ';
exports = function (output, cache) {
var css = {},
key = '',
transform = '',
transformHasZ = false,
rule = '';
// Loop through output, check for transform properties and cache
for (key in output) {
if (output.hasOwnProperty(key)) {
rule = output[key];
// If this is a transform property, add to transform string
if (transformProps[key]) {
transform += key + '(' + rule + ')';
transformHasZ = (key === TRANSLATE_Z) ? true : transformHasZ;
// Or just assign directly if different from cache
} else if (cache[key] !== rule) {
cache[key] = css[key] = rule;
}
}
}
// If we have transform properties, add translateZ
if (transform !== '' && transform !== cache[TRANSFORM]) {
if (!transformHasZ) {
transform += ' ' + TRANSLATE_Z + '(0px)';
}
cache[TRANSFORM] = css[TRANSFORM] = transform;
}
return css;
};
return exports;
})()),
styleDom = ((function() {
var exports = {};
"use strict";
var styleDOM = function () {
var prefixes = ['Webkit','Moz','O','ms', ''],
prefixesLength = prefixes.length,
cache = {},
/*
Test style property for prefixed version
@param [string]: Style property
@return [string]: Cached property name
*/
testPrefix = function (key) {
var testElement = document.body;
cache[key] = key;
for (var i = 0; i < prefixesLength; i++) {
var prefixed = prefixes[i] + key.charAt(0).toUpperCase() + key.slice(1);
if (testElement.style.hasOwnProperty(prefixed)) {
cache[key] = prefixed;
}
}
return cache[key];
};
/*
Style DOM functions
*/
return {
/*
Get DOM styles
@param [DOM Element]: Element to get styles from
@param [string]: Name of style to read
*/
get: function (element, name) {
return window.getComputedStyle(element, null)[cache[name] || testPrefix(name)];
},
/*
Set DOM styles
@param [DOM Element]: Element to set styles on
@param [object]: Name of style to set
@param [string]: New rule
*/
set: function (element, name, rule) {
element.style[cache[name] || testPrefix(name)] = rule;
}
};
};
exports = new styleDOM();
return exports;
})()),
typeMap = ((function() {
var exports = {};
"use strict";
var COLOR = 'color',
POSITIONS = 'positions',
DIMENSIONS = 'dimensions',
SHADOW = 'shadow',
ANGLE = 'angle',
ALPHA = 'alpha',
PX = 'px';
exports = {
// Color properties
color: COLOR,
backgroundColor: COLOR,
borderColor: COLOR,
borderTopColor: COLOR,
borderRightColor: COLOR,
borderBottomColor: COLOR,
borderLeftColor: COLOR,
outlineColor: COLOR,
fill: COLOR,
stroke: COLOR,
// Dimensions
margin: DIMENSIONS,
padding: DIMENSIONS,
width: PX,
height: PX,
// Positions
backgroundPosition: POSITIONS,
perspectiveOrigin: POSITIONS,
transformOrigin: POSITIONS,
// Shadows
textShadow: SHADOW,
boxShadow: SHADOW,
// Transform properties
rotate: ANGLE,
rotateX: ANGLE,
rotateY: ANGLE,
rotateZ: ANGLE,
skewX: ANGLE,
skewY: ANGLE,
translateX: PX,
translateY: PX,
translateZ: PX,
perspective: PX,
opacity: ALPHA
};
return exports;
})()),
CSS_CACHE = '_cssCache';
exports = {
typeMap: typeMap,
onChange: function (output) {
this[CSS_CACHE] = this[CSS_CACHE] || {};
this.css(build(output, this[CSS_CACHE]));
},
get: function (key) {
return styleDom.get(this.element, key);
},
set: function (key, value) {
styleDom.set(this.element, key, value);
}
};
return exports;
})()))
.addRoute('attr', ((function() {
var exports = {};
/*
DOM Attr route
==============================================
*/
"use strict";
exports = {
onChange: function (output) {
for (var key in output) {
if (output.hasOwnProperty(key)) {
this.element.setAttribute(key, output[key]);
}
}
},
get: function (key) {
return this.element.getAttribute(key);
},
set: function (key, value) {
this.element.setAttribute(key, value);
}
};
return exports;
})()))
/*
SVG route - dependent on DOM CSS route
*/
.addRoute('path', ((function() {
var exports = {};
/*
SVG Path route
==============================================
Dependent on CSS Route
*/
"use strict";
var createStyles = ((function() {
var exports = {};
"use strict";
var lookup = ((function() {
var exports = {};
var STROKE = 'stroke',
DASH = STROKE + '-dash', // stoke-width
DASH_ARRAY = DASH + 'array';
exports = {
opacity: STROKE + '-opacity',
width: STROKE + '-width',
offset: DASH + 'offset',
length: DASH_ARRAY,
spacing: DASH_ARRAY,
miterlimit: STROKE + '-miterlimit'
};
return exports;
})()),
/*
Convert percentage to pixels
@param [number]: Percentage of total length
@param [number]: Total length
*/
percentToPixels = function (percentage, length) {
return (parseFloat(percentage) / 100) * length + 'px';
};
/*
Create styles
@param [object]: SVG Path properties
@param [object]: Length of path
@returns [object]: Key/value pairs of valid CSS properties
*/
exports = function (props, pathLength) {
var hasArray = false,
svgProperty = '',
arrayStyles = {
length: 0,
spacing: pathLength + 'px'
},
pathStyles = {};
// Loop over each property and create related css property
for (var key in props) {
if (props.hasOwnProperty(key)) {
svgProperty = lookup[key] || key;
switch (key) {
case 'length':
case 'spacing':
hasArray = true;
arrayStyles[key] = percentToPixels(props[key], pathLength);
break;
case 'offset':
pathStyles[svgProperty] = percentToPixels(-props[key], pathLength);
break;
default:
pathStyles[svgProperty] = props[key];
}
}
}
if (hasArray) {
pathStyles[lookup.length] = arrayStyles.length + ' ' + arrayStyles.spacing;
}
return pathStyles;
};
return exports;
})());
exports = {
typeMap: {
stroke: 'color'
},
onStart: function () {
if (this.element) {
this.pathLength = this.element.getTotalLength();
}
},
onChange: function (output) {
this.css(createStyles(output, this.pathLength));
}
};
return exports;
})()));
exports = popmotion;
return exports;
})()),
UIref = window.ui;
window.ui = window.popmotion = popmotion;
/*
If noConflict is run, the original reference to window.UI is
restored and Popmotion is loaded to window.Popmotion
*/
window.ui.noConflict = function () {
window.ui = UIref;
};
return exports;
})(); | sreym/cdnjs | ajax/libs/popmotion/0.0.21/popmotion.global.js | JavaScript | mit | 126,199 |
require "spec_helper"
describe Mongoid::Persistence::Atomic::Inc do
let(:collection) do
stub
end
before do
person.stubs(:collection).returns(collection)
end
describe "#inc" do
let(:reloaded) do
person.reload
end
context "when incrementing a field with a value" do
let(:person) do
Person.new(:age => 100)
end
before do
collection.expects(:update).with(
person._selector, { "$inc" => { :age => 2 } }, { :safe => false }
)
end
let!(:inced) do
person.inc(:age, 2)
end
it "increments by the provided value" do
person.age.should == 102
end
it "returns the new value" do
inced.should == 102
end
it "resets the dirty attributes" do
person.changes["age"].should be_nil
end
end
context "when incrementing a nil field" do
let(:person) do
Person.new
end
before do
collection.expects(:update).with(
person._selector, { "$inc" => { :score => 2 } }, { :safe => false }
)
end
let!(:inced) do
person.inc(:score, 2)
end
it "sets the value to the provided number" do
person.score.should == 2
end
it "returns the new value" do
inced.should == 2
end
it "resets the dirty attributes" do
person.changes["score"].should be_nil
end
end
context "when incrementing a non existant field" do
let(:person) do
Person.new
end
before do
collection.expects(:update).with(
person._selector, { "$inc" => { :high_score => 5 } }, { :safe => false }
)
end
let!(:inced) do
person.inc(:high_score, 5)
end
it "sets the value to the provided number" do
person.high_score.should == 5
end
it "returns the new value" do
inced.should == 5
end
it "resets the dirty attributes" do
person.changes["high_score"].should be_nil
end
end
end
end
| chrisconley/mongoid | spec/unit/mongoid/persistence/atomic/inc_spec.rb | Ruby | mit | 2,089 |
define("ace/mode/ini_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var escapeRe = "\\\\(?:[\\\\0abtrn;#=:]|x[a-fA-F\\d]{4})";
var IniHighlightRules = function() {
this.$rules = {
start: [{
token: 'punctuation.definition.comment.ini',
regex: '#.*',
push_: [{
token: 'comment.line.number-sign.ini',
regex: '$|^',
next: 'pop'
}, {
defaultToken: 'comment.line.number-sign.ini'
}]
}, {
token: 'punctuation.definition.comment.ini',
regex: ';.*',
push_: [{
token: 'comment.line.semicolon.ini',
regex: '$|^',
next: 'pop'
}, {
defaultToken: 'comment.line.semicolon.ini'
}]
}, {
token: ['keyword.other.definition.ini', 'text', 'punctuation.separator.key-value.ini'],
regex: '\\b([a-zA-Z0-9_.-]+)\\b(\\s*)(=)'
}, {
token: ['punctuation.definition.entity.ini', 'constant.section.group-title.ini', 'punctuation.definition.entity.ini'],
regex: '^(\\[)(.*?)(\\])'
}, {
token: 'punctuation.definition.string.begin.ini',
regex: "'",
push: [{
token: 'punctuation.definition.string.end.ini',
regex: "'",
next: 'pop'
}, {
token: "constant.language.escape",
regex: escapeRe
}, {
defaultToken: 'string.quoted.single.ini'
}]
}, {
token: 'punctuation.definition.string.begin.ini',
regex: '"',
push: [{
token: "constant.language.escape",
regex: escapeRe
}, {
token: 'punctuation.definition.string.end.ini',
regex: '"',
next: 'pop'
}, {
defaultToken: 'string.quoted.double.ini'
}]
}]
};
this.normalizeRules();
};
IniHighlightRules.metaData = {
fileTypes: ['ini', 'conf'],
keyEquivalent: '^~I',
name: 'Ini',
scopeName: 'source.ini'
};
oop.inherits(IniHighlightRules, TextHighlightRules);
exports.IniHighlightRules = IniHighlightRules;
});
define("ace/mode/folding/ini",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /^\s*\[([^\])]*)]\s*(?:$|[;#])/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var re = this.foldingStartMarker;
var line = session.getLine(row);
var m = line.match(re);
if (!m) return;
var startName = m[1] + ".";
var startColumn = line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
line = session.getLine(row);
if (/^\s*$/.test(line))
continue;
m = line.match(re);
if (m && m[1].lastIndexOf(startName, 0) !== 0)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
}).call(FoldMode.prototype);
});
define("ace/mode/ini",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/ini_highlight_rules","ace/mode/folding/ini"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var IniHighlightRules = require("./ini_highlight_rules").IniHighlightRules;
var FoldMode = require("./folding/ini").FoldMode;
var Mode = function() {
this.HighlightRules = IniHighlightRules;
this.foldingRules = new FoldMode();
this.$behaviour = this.$defaultBehaviour;
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = ";";
this.blockComment = null;
this.$id = "ace/mode/ini";
}).call(Mode.prototype);
exports.Mode = Mode;
});
| chickencoder/chickencoder.github.io | yodacode/vendor/ace/mode-ini.js | JavaScript | mit | 4,673 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Security.Permissions;
using Microsoft.Azure.Commands.Automation.Model;
using Microsoft.Azure.Commands.Automation.Common;
using System.Collections;
namespace Microsoft.Azure.Commands.Automation.Cmdlet
{
/// <summary>
/// Create a new Module for automation.
/// </summary>
[Cmdlet(VerbsCommon.New, "AzureAutomationModule")]
[OutputType(typeof(Module))]
public class NewAzureAutomationModule : AzureAutomationBaseCmdlet
{
/// <summary>
/// Gets or sets the module name.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The module name.")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Gets or sets the contentLink
/// </summary>
[Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The ContentLink.")]
[ValidateNotNullOrEmpty]
public Uri ContentLink { get; set; }
/// <summary>
/// Gets or sets the module tags.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The module tags.")]
[Alias("Tag")]
public IDictionary Tags { get; set; }
/// <summary>
/// Execute this cmdlet.
/// </summary>
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
protected override void AutomationExecuteCmdlet()
{
var createdModule = this.AutomationClient.CreateModule(this.AutomationAccountName, ContentLink, Name, Tags);
this.WriteObject(createdModule);
}
}
}
| zhencui/azure-powershell | src/ServiceManagement/Automation/Commands.Automation/Cmdlet/NewAzureAutomationModule.cs | C# | apache-2.0 | 2,576 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0005_auto_20140924_1039'),
]
operations = [
migrations.AlterModelOptions(
name='page',
options={'ordering': ('path',), 'verbose_name': 'page', 'verbose_name_plural': 'pages', 'permissions': (('view_page', 'Can view page'), ('publish_page', 'Can publish page'), ('edit_static_placeholder', 'Can edit static placeholders'))},
),
migrations.RemoveField(
model_name='cmsplugin',
name='level',
),
migrations.RemoveField(
model_name='cmsplugin',
name='lft',
),
migrations.RemoveField(
model_name='cmsplugin',
name='rght',
),
migrations.RemoveField(
model_name='cmsplugin',
name='tree_id',
),
migrations.RemoveField(
model_name='page',
name='level',
),
migrations.RemoveField(
model_name='page',
name='lft',
),
migrations.RemoveField(
model_name='page',
name='rght',
),
migrations.RemoveField(
model_name='page',
name='tree_id',
),
migrations.AlterField(
model_name='cmsplugin',
name='depth',
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name='cmsplugin',
name='numchild',
field=models.PositiveIntegerField(default=0, editable=False),
),
migrations.AlterField(
model_name='cmsplugin',
name='path',
field=models.CharField(unique=True, max_length=255, editable=False),
),
]
| Glasgow2015/team-10 | env/lib/python2.7/site-packages/cms/migrations/0006_auto_20140924_1110.py | Python | apache-2.0 | 1,918 |
require "cmd/tap"
require "formula_versions"
require "migrator"
require "formulary"
require "descriptions"
module Homebrew
def update
unless ARGV.named.empty?
abort <<-EOS.undent
This command updates brew itself, and does not take formula names.
Use `brew upgrade <formula>`.
EOS
end
# ensure git is installed
Utils.ensure_git_installed!
# ensure GIT_CONFIG is unset as we need to operate on .git/config
ENV.delete("GIT_CONFIG")
cd HOMEBREW_REPOSITORY
git_init_if_necessary
# migrate to new directories based tap structure
migrate_taps
report = Report.new
master_updater = Updater.new(HOMEBREW_REPOSITORY)
master_updater.pull!
report.update(master_updater.report)
# rename Taps directories
# this procedure will be removed in the future if it seems unnecessasry
rename_taps_dir_if_necessary
Tap.each do |tap|
next unless tap.git?
tap.path.cd do
updater = Updater.new(tap.path)
begin
updater.pull!
rescue
onoe "Failed to update tap: #{tap}"
else
report.update(updater.report) do |_key, oldval, newval|
oldval.concat(newval)
end
end
end
end
# automatically tap any migrated formulae's new tap
report.select_formula(:D).each do |f|
next unless (dir = HOMEBREW_CELLAR/f).exist?
migration = TAP_MIGRATIONS[f]
next unless migration
tap_user, tap_repo = migration.split "/"
install_tap tap_user, tap_repo
# update tap for each Tab
tabs = dir.subdirs.map { |d| Tab.for_keg(Keg.new(d)) }
next if tabs.first.source["tap"] != "Homebrew/homebrew"
tabs.each { |tab| tab.source["tap"] = "#{tap_user}/homebrew-#{tap_repo}" }
tabs.each(&:write)
end if load_tap_migrations
load_formula_renames
report.update_renamed
# Migrate installed renamed formulae from core and taps.
report.select_formula(:R).each do |oldname, newname|
if oldname.include?("/")
user, repo, oldname = oldname.split("/", 3)
newname = newname.split("/", 3).last
else
user = "homebrew"
repo = "homebrew"
end
next unless (dir = HOMEBREW_CELLAR/oldname).directory? && !dir.subdirs.empty?
begin
f = Formulary.factory("#{user}/#{repo}/#{newname}")
rescue FormulaUnavailableError, *FormulaVersions::IGNORED_EXCEPTIONS
end
next unless f
begin
migrator = Migrator.new(f)
migrator.migrate
rescue Migrator::MigratorDifferentTapsError
end
end
if report.empty?
puts "Already up-to-date."
else
puts "Updated Homebrew from #{master_updater.initial_revision[0, 8]} to #{master_updater.current_revision[0, 8]}."
report.dump
end
Descriptions.update_cache(report)
end
private
def git_init_if_necessary
if Dir[".git/*"].empty?
safe_system "git", "init"
safe_system "git", "config", "core.autocrlf", "false"
safe_system "git", "config", "remote.origin.url", "https://github.com/Homebrew/homebrew.git"
safe_system "git", "config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"
safe_system "git", "fetch", "origin"
safe_system "git", "reset", "--hard", "origin/master"
end
if `git remote show origin -n` =~ /Fetch URL: \S+mxcl\/homebrew/
safe_system "git", "remote", "set-url", "origin", "https://github.com/Homebrew/homebrew.git"
safe_system "git", "remote", "set-url", "--delete", "origin", ".*mxcl\/homebrew.*"
end
rescue Exception
FileUtils.rm_rf ".git"
raise
end
def rename_taps_dir_if_necessary
Dir.glob("#{HOMEBREW_LIBRARY}/Taps/*/") do |tapd|
begin
if File.directory?(tapd + "/.git")
tapd_basename = File.basename(tapd)
if tapd_basename.include?("-")
# only replace the *last* dash: yes, tap filenames suck
user, repo = tapd_basename.reverse.sub("-", "/").reverse.split("/")
FileUtils.mkdir_p("#{HOMEBREW_LIBRARY}/Taps/#{user.downcase}")
FileUtils.mv(tapd, "#{HOMEBREW_LIBRARY}/Taps/#{user.downcase}/homebrew-#{repo.downcase}")
if tapd_basename.count("-") >= 2
opoo "Homebrew changed the structure of Taps like <someuser>/<sometap>. "\
+ "So you may need to rename #{HOMEBREW_LIBRARY}/Taps/#{user.downcase}/homebrew-#{repo.downcase} manually."
end
else
opoo "Homebrew changed the structure of Taps like <someuser>/<sometap>. "\
"#{tapd} is incorrect name format. You may need to rename it like <someuser>/<sometap> manually."
end
end
rescue => ex
onoe ex.message
next # next tap directory
end
end
end
def load_tap_migrations
load "tap_migrations.rb"
rescue LoadError
false
end
def load_formula_renames
load "formula_renames.rb"
rescue LoadError
false
end
end
class Updater
attr_reader :initial_revision, :current_revision, :repository
def initialize(repository)
@repository = repository
@stashed = false
end
def pull!(options = {})
quiet = []
quiet << "--quiet" unless ARGV.verbose?
unless system "git", "diff", "--quiet"
unless options[:silent]
puts "Stashing your changes:"
system "git", "status", "--short", "--untracked-files"
end
safe_system "git", "stash", "save", "--include-untracked", *quiet
@stashed = true
end
# The upstream repository's default branch may not be master;
# check refs/remotes/origin/HEAD to see what the default
# origin branch name is, and use that. If not set, fall back to "master".
begin
@upstream_branch = `git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null`
@upstream_branch = @upstream_branch.chomp.sub('refs/remotes/origin/', '')
rescue ErrorDuringExecution
@upstream_branch = "master"
end
begin
@initial_branch = `git symbolic-ref --short HEAD 2>/dev/null`.chomp
rescue ErrorDuringExecution
@initial_branch = ""
end
if @initial_branch != @upstream_branch && !@initial_branch.empty?
safe_system "git", "checkout", @upstream_branch, *quiet
end
@initial_revision = read_current_revision
# ensure we don't munge line endings on checkout
safe_system "git", "config", "core.autocrlf", "false"
args = ["pull"]
args << "--ff"
args << ((ARGV.include? "--rebase") ? "--rebase" : "--no-rebase")
args += quiet
args << "origin"
# the refspec ensures that the default upstream branch gets updated
args << "refs/heads/#{@upstream_branch}:refs/remotes/origin/#{@upstream_branch}"
reset_on_interrupt { safe_system "git", *args }
@current_revision = read_current_revision
if @initial_branch != "master" && !@initial_branch.empty?
safe_system "git", "checkout", @initial_branch, *quiet
end
if @stashed
safe_system "git", "stash", "pop", *quiet
unless options[:silent]
puts "Restored your changes:"
system "git", "status", "--short", "--untracked-files"
end
@stashed = false
end
end
def reset_on_interrupt
ignore_interrupts { yield }
ensure
if $?.signaled? && $?.termsig == 2 # SIGINT
safe_system "git", "checkout", @initial_branch unless @initial_branch.empty?
safe_system "git", "reset", "--hard", @initial_revision
safe_system "git", "stash", "pop" if @stashed
end
end
def report
map = Hash.new { |h, k| h[k] = [] }
if initial_revision && initial_revision != current_revision
wc_revision = read_current_revision
diff.each_line do |line|
status, *paths = line.split
src = paths.first
dst = paths.last
next unless File.extname(dst) == ".rb"
next unless paths.any? { |p| File.dirname(p) == formula_directory }
case status
when "A", "D"
map[status.to_sym] << repository.join(src)
when "M"
file = repository.join(src)
begin
formula = Formulary.factory(file)
new_version = if wc_revision == current_revision
formula.pkg_version
else
FormulaVersions.new(formula).formula_at_revision(@current_revision, &:pkg_version)
end
old_version = FormulaVersions.new(formula).formula_at_revision(@initial_revision, &:pkg_version)
next if new_version == old_version
rescue FormulaUnavailableError, *FormulaVersions::IGNORED_EXCEPTIONS => e
onoe e if ARGV.homebrew_developer?
end
map[:M] << file
when /^R\d{0,3}/
map[:D] << repository.join(src) if File.dirname(src) == formula_directory
map[:A] << repository.join(dst) if File.dirname(dst) == formula_directory
end
end
end
map
end
private
def formula_directory
if repository == HOMEBREW_REPOSITORY
"Library/Formula"
elsif repository.join("Formula").directory?
"Formula"
elsif repository.join("HomebrewFormula").directory?
"HomebrewFormula"
else
"."
end
end
def read_current_revision
`git rev-parse -q --verify HEAD`.chomp
end
def diff
Utils.popen_read(
"git", "diff-tree", "-r", "--name-status", "--diff-filter=AMDR",
"-M85%", initial_revision, current_revision
)
end
def `(cmd)
out = super
unless $?.success?
$stderr.puts(out) unless out.empty?
raise ErrorDuringExecution.new(cmd)
end
ohai(cmd, out) if ARGV.verbose?
out
end
end
class Report
def initialize
@hash = {}
end
def fetch(*args, &block)
@hash.fetch(*args, &block)
end
def update(*args, &block)
@hash.update(*args, &block)
end
def empty?
@hash.empty?
end
def dump
# Key Legend: Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R)
dump_formula_report :A, "New Formulae"
dump_formula_report :M, "Updated Formulae"
dump_formula_report :R, "Renamed Formulae"
dump_formula_report :D, "Deleted Formulae"
end
def update_renamed
renamed_formulae = []
fetch(:D, []).each do |path|
case path.to_s
when HOMEBREW_TAP_PATH_REGEX
user = $1
repo = $2.sub("homebrew-", "")
oldname = path.basename(".rb").to_s
next unless newname = Tap.new(user, repo).formula_renames[oldname]
else
oldname = path.basename(".rb").to_s
next unless newname = FORMULA_RENAMES[oldname]
end
if fetch(:A, []).include?(newpath = path.dirname.join("#{newname}.rb"))
renamed_formulae << [path, newpath]
end
end
unless renamed_formulae.empty?
@hash[:A] -= renamed_formulae.map(&:last) if @hash[:A]
@hash[:D] -= renamed_formulae.map(&:first) if @hash[:D]
@hash[:R] = renamed_formulae
end
end
def select_formula(key)
fetch(key, []).map do |path, newpath|
if path.to_s =~ HOMEBREW_TAP_PATH_REGEX
tap = "#{$1}/#{$2.sub("homebrew-", "")}"
if newpath
["#{tap}/#{path.basename(".rb")}", "#{tap}/#{newpath.basename(".rb")}"]
else
"#{tap}/#{path.basename(".rb")}"
end
elsif newpath
["#{path.basename(".rb")}", "#{newpath.basename(".rb")}"]
else
path.basename(".rb").to_s
end
end.sort
end
def dump_formula_report(key, title)
formula = select_formula(key)
formula.map! { |oldname, newname| "#{oldname} -> #{newname}" } if key == :R
unless formula.empty?
ohai title
puts_columns formula
end
end
end
| imjerrybao/homebrew | Library/Homebrew/cmd/update.rb | Ruby | bsd-2-clause | 11,741 |
require "formula"
class Geomview < Formula
homepage "http://www.geomview.org"
url "https://downloads.sourceforge.net/project/geomview/geomview/1.9.5/geomview-1.9.5.tar.gz"
sha1 "26186046dc18ab3872e7104745ae474908ee54d1"
depends_on :x11
depends_on "lesstif"
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
end
end
| jtrag/homebrew | Library/Formula/geomview.rb | Ruby | bsd-2-clause | 481 |
#include "catch.hpp"
#include <iterator>
#include <osmium/io/file.hpp>
TEST_CASE("FileFormats") {
SECTION("default_file_format") {
osmium::io::File f;
REQUIRE(osmium::io::file_format::unknown == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
REQUIRE_THROWS_AS(f.check(), std::runtime_error);
}
SECTION("stdin_stdout_empty") {
osmium::io::File f {""};
REQUIRE(osmium::io::file_format::unknown == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
REQUIRE_THROWS_AS(f.check(), std::runtime_error);
}
SECTION("stdin_stdout_dash") {
osmium::io::File f {"-"};
REQUIRE(osmium::io::file_format::unknown == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
REQUIRE_THROWS_AS(f.check(), std::runtime_error);
}
SECTION("stdin_stdout_bz2") {
osmium::io::File f {"-", "osm.bz2"};
REQUIRE("" == f.filename());
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::bzip2 == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_osm") {
osmium::io::File f {"test.osm"};
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_pbf") {
osmium::io::File f {"test.pbf"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_osm_pbf") {
osmium::io::File f {"test.osm.pbf"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_opl") {
osmium::io::File f {"test.opl"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_osm_opl") {
osmium::io::File f {"test.osm.opl"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_osm_gz") {
osmium::io::File f {"test.osm.gz"};
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::gzip == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_opl_bz2") {
osmium::io::File f {"test.osm.opl.bz2"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::bzip2 == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_osc_gz") {
osmium::io::File f {"test.osc.gz"};
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::gzip == f.compression());
REQUIRE(true == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_opl_gz") {
osmium::io::File f {"test.osh.opl.gz"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::gzip == f.compression());
REQUIRE(true == f.has_multiple_object_versions());
f.check();
}
SECTION("detect_file_format_by_suffix_osh_pbf") {
osmium::io::File f {"test.osh.pbf"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(true == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osm") {
osmium::io::File f {"test", "osm"};
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_pbf") {
osmium::io::File f {"test", "pbf"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osm_pbf") {
osmium::io::File f {"test", "osm.pbf"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_opl") {
osmium::io::File f {"test", "opl"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osm_opl") {
osmium::io::File f {"test", "osm.opl"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osm_gz") {
osmium::io::File f {"test", "osm.gz"};
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::gzip == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osm_opl_bz2") {
osmium::io::File f {"test", "osm.opl.bz2"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::bzip2 == f.compression());
REQUIRE(false == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osc_gz") {
osmium::io::File f {"test", "osc.gz"};
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::gzip == f.compression());
REQUIRE(true == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osh_opl_gz") {
osmium::io::File f {"test", "osh.opl.gz"};
REQUIRE(osmium::io::file_format::opl == f.format());
REQUIRE(osmium::io::file_compression::gzip == f.compression());
REQUIRE(true == f.has_multiple_object_versions());
f.check();
}
SECTION("override_file_format_by_suffix_osh_pbf") {
osmium::io::File f {"test", "osh.pbf"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(true == f.has_multiple_object_versions());
f.check();
}
SECTION("format_options_pbf_history") {
osmium::io::File f {"test", "pbf,history=true"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE(true == f.has_multiple_object_versions());
f.check();
}
SECTION("format_options_pbf_foo") {
osmium::io::File f {"test.osm", "pbf,foo=bar"};
REQUIRE(osmium::io::file_format::pbf == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE("bar" == f.get("foo"));
f.check();
}
SECTION("format_options_xml_abc_something") {
osmium::io::File f {"test.bla", "xml,abc,some=thing"};
REQUIRE(osmium::io::file_format::xml == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE("true" == f.get("abc"));
REQUIRE("thing" == f.get("some"));
REQUIRE(2 == std::distance(f.begin(), f.end()));
f.check();
}
SECTION("unknown_format_foo_bar") {
osmium::io::File f {"test.foo.bar"};
REQUIRE(osmium::io::file_format::unknown == f.format());
REQUIRE(osmium::io::file_compression::none == f.compression());
REQUIRE_THROWS_AS(f.check(), std::runtime_error);
}
SECTION("unknown_format_foo") {
osmium::io::File f {"test", "foo"};
REQUIRE_THROWS_AS(f.check(), std::runtime_error);
}
SECTION("unknown_format_osm_foo") {
osmium::io::File f {"test", "osm.foo"};
REQUIRE_THROWS_AS(f.check(), std::runtime_error);
}
SECTION("unknown_format_bla_equals_foo") {
osmium::io::File f {"test", "bla=foo"};
REQUIRE_THROWS_AS(f.check(), std::runtime_error);
}
}
| agruss/osrm-backend | third_party/libosmium/test/t/io/test_file_formats.cpp | C++ | bsd-2-clause | 9,572 |
/*
* Based on simplePagination - Copyright (c) 2012 Flavius Matis - http://flaviusmatis.github.com/simplePagination.js/ (MIT)
*/
(function(addon) {
var component;
if (jQuery && UIkit) {
component = addon(jQuery, UIkit);
}
if (typeof define == "function" && define.amd) {
define("uikit-pagination", ["uikit"], function(){
return component || addon(jQuery, UIkit);
});
}
})(function($, UI){
"use strict";
UI.component('pagination', {
defaults: {
items : 1,
itemsOnPage : 1,
pages : 0,
displayedPages : 3,
edges : 3,
currentPage : 1,
lblPrev : false,
lblNext : false,
onSelectPage : function() {}
},
boot: function() {
// init code
UI.ready(function(context) {
UI.$("[data-@-pagination]", context).each(function(){
var ele = UI.$(this);
if (!ele.data("pagination")) {
var obj = UI.pagination(ele, UI.Utils.options(ele.attr("data-@-pagination")));
}
});
});
},
init: function() {
var $this = this;
this.pages = this.options.pages ? this.options.pages : Math.ceil(this.options.items / this.options.itemsOnPage) ? Math.ceil(this.options.items / this.options.itemsOnPage) : 1;
this.currentPage = this.options.currentPage - 1;
this.halfDisplayed = this.options.displayedPages / 2;
this.on("click", "a[data-page]", function(e){
e.preventDefault();
$this.selectPage($(this).data("page"));
});
this._render();
},
_getInterval: function() {
return {
start: Math.ceil(this.currentPage > this.halfDisplayed ? Math.max(Math.min(this.currentPage - this.halfDisplayed, (this.pages - this.options.displayedPages)), 0) : 0),
end : Math.ceil(this.currentPage > this.halfDisplayed ? Math.min(this.currentPage + this.halfDisplayed, this.pages) : Math.min(this.options.displayedPages, this.pages))
};
},
render: function(pages) {
this.pages = pages ? pages : this.pages;
this._render();
},
selectPage: function(pageIndex, pages) {
this.currentPage = pageIndex;
this.render(pages);
this.options.onSelectPage.apply(this, [pageIndex]);
this.trigger('select.uk.pagination', [pageIndex, this]);
},
_render: function() {
var o = this.options, interval = this._getInterval(), i;
this.element.empty();
// Generate Prev link
if (o.lblPrev) this._append(o.currentPage - 1, {text: o.lblPrev});
// Generate start edges
if (interval.start > 0 && o.edges > 0) {
var end = Math.min(o.edges, interval.start);
for (i = 0; i < end; i++) this._append(i);
if (o.edges < interval.start && (interval.start - o.edges != 1)) {
this.element.append('<li><span>...</span></li>');
} else if (interval.start - o.edges == 1) {
this._append(o.edges);
}
}
// Generate interval links
for (i = interval.start; i < interval.end; i++) this._append(i);
// Generate end edges
if (interval.end < this.pages && o.edges > 0) {
if (this.pages - o.edges > interval.end && (this.pages - o.edges - interval.end != 1)) {
this.element.append('<li><span>...</span></li>');
} else if (this.pages - o.edges - interval.end == 1) {
this._append(interval.end++);
}
var begin = Math.max(this.pages - o.edges, interval.end);
for (i = begin; i < this.pages; i++) this._append(i);
}
// Generate Next link (unless option is set for at front)
if (o.lblNext) this._append(o.currentPage + 1, {text: o.lblNext});
},
_append: function(pageIndex, opts) {
var $this = this, item, link, options;
pageIndex = pageIndex < 0 ? 0 : (pageIndex < this.pages ? pageIndex : this.pages - 1);
options = $.extend({ text: pageIndex + 1 }, opts);
item = (pageIndex == this.currentPage) ? '<li class="@-active"><span>' + (options.text) + '</span></li>'
: '<li><a href="#page-'+(pageIndex+1)+'" data-page="'+pageIndex+'">'+options.text+'</a></li>';
this.element.append(UI.prefix(item));
}
});
return UI.pagination;
});
| mubassirhayat/uikit | src/js/components/pagination.js | JavaScript | mit | 4,944 |
{# Output tablular data. Note that it's up to you to output the thead manually. This just output the data. #}
<table>
<tbody>
{% for key, row in <%- value %> %}
<tr>
{% for key, cell in row %}
<td>
{{ cell }}
</td>
{% endfor %}
</tr>
{% endfor%}
</tbody>
</table>
| micahmicah/monica-bravo | libs/widgets/tabular.html | HTML | mit | 336 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "base/string_util.h"
#include "crypto/sha2.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
bool VectorContains(const std::vector<std::string>& data,
const std::string& str) {
return std::find(data.begin(), data.end(), str) != data.end();
}
}
// Tests that we generate the required host/path combinations for testing
// according to the Safe Browsing spec.
// See section 6.2 in
// http://code.google.com/p/google-safe-browsing/wiki/Protocolv2Spec.
TEST(SafeBrowsingUtilTest, UrlParsing) {
std::vector<std::string> hosts, paths;
GURL url("http://a.b.c/1/2.html?param=1");
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(hosts.size(), static_cast<size_t>(2));
EXPECT_EQ(paths.size(), static_cast<size_t>(4));
EXPECT_EQ(hosts[0], "b.c");
EXPECT_EQ(hosts[1], "a.b.c");
EXPECT_TRUE(VectorContains(paths, "/1/2.html?param=1"));
EXPECT_TRUE(VectorContains(paths, "/1/2.html"));
EXPECT_TRUE(VectorContains(paths, "/1/"));
EXPECT_TRUE(VectorContains(paths, "/"));
url = GURL("http://a.b.c.d.e.f.g/1.html");
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(hosts.size(), static_cast<size_t>(5));
EXPECT_EQ(paths.size(), static_cast<size_t>(2));
EXPECT_EQ(hosts[0], "f.g");
EXPECT_EQ(hosts[1], "e.f.g");
EXPECT_EQ(hosts[2], "d.e.f.g");
EXPECT_EQ(hosts[3], "c.d.e.f.g");
EXPECT_EQ(hosts[4], "a.b.c.d.e.f.g");
EXPECT_TRUE(VectorContains(paths, "/1.html"));
EXPECT_TRUE(VectorContains(paths, "/"));
url = GURL("http://a.b/saw-cgi/eBayISAPI.dll/");
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(paths.size(), static_cast<size_t>(3));
EXPECT_TRUE(VectorContains(paths, "/saw-cgi/eBayISAPI.dll/"));
EXPECT_TRUE(VectorContains(paths, "/saw-cgi/"));
EXPECT_TRUE(VectorContains(paths, "/"));
}
// Tests the url canonicalization according to the Safe Browsing spec.
// See section 6.1 in
// http://code.google.com/p/google-safe-browsing/wiki/Protocolv2Spec.
TEST(SafeBrowsingUtilTest, CanonicalizeUrl) {
struct {
const char* input_url;
const char* expected_canonicalized_hostname;
const char* expected_canonicalized_path;
const char* expected_canonicalized_query;
} tests[] = {
{
"http://host/%25%32%35",
"host",
"/%25",
""
}, {
"http://host/%25%32%35%25%32%35",
"host",
"/%25%25",
""
}, {
"http://host/%2525252525252525",
"host",
"/%25",
""
}, {
"http://host/asdf%25%32%35asd",
"host",
"/asdf%25asd",
""
}, {
"http://host/%%%25%32%35asd%%",
"host",
"/%25%25%25asd%25%25",
""
}, {
"http://host/%%%25%32%35asd%%",
"host",
"/%25%25%25asd%25%25",
""
}, {
"http://www.google.com/",
"www.google.com",
"/",
""
}, {
"http://%31%36%38%2e%31%38%38%2e%39%39%2e%32%36/%2E%73%65%63%75%72%65/%77"
"%77%77%2E%65%62%61%79%2E%63%6F%6D/",
"168.188.99.26",
"/.secure/www.ebay.com/",
""
}, {
"http://195.127.0.11/uploads/%20%20%20%20/.verify/.eBaysecure=updateuserd"
"ataxplimnbqmn-xplmvalidateinfoswqpcmlx=hgplmcx/",
"195.127.0.11",
"/uploads/%20%20%20%20/.verify/.eBaysecure=updateuserdataxplimnbqmn-xplmv"
"alidateinfoswqpcmlx=hgplmcx/",
""
}, {
"http://host.com/%257Ea%2521b%2540c%2523d%2524e%25f%255E00%252611%252A"
"22%252833%252944_55%252B",
"host.com",
"/~a!b@c%23d$e%25f^00&11*22(33)44_55+",
""
}, {
"http://3279880203/blah",
"195.127.0.11",
"/blah",
""
}, {
"http://www.google.com/blah/..",
"www.google.com",
"/",
""
}, {
"http://www.google.com/blah#fraq",
"www.google.com",
"/blah",
""
}, {
"http://www.GOOgle.com/",
"www.google.com",
"/",
""
}, {
"http://www.google.com.../",
"www.google.com",
"/",
""
}, {
"http://www.google.com/q?",
"www.google.com",
"/q",
""
}, {
"http://www.google.com/q?r?",
"www.google.com",
"/q",
"r?"
}, {
"http://www.google.com/q?r?s",
"www.google.com",
"/q",
"r?s"
}, {
"http://evil.com/foo#bar#baz",
"evil.com",
"/foo",
""
}, {
"http://evil.com/foo;",
"evil.com",
"/foo;",
""
}, {
"http://evil.com/foo?bar;",
"evil.com",
"/foo",
"bar;"
}, {
"http://notrailingslash.com",
"notrailingslash.com",
"/",
""
}, {
"http://www.gotaport.com:1234/",
"www.gotaport.com",
"/",
""
}, {
" http://www.google.com/ ",
"www.google.com",
"/",
""
}, {
"http:// leadingspace.com/",
"%20leadingspace.com",
"/",
""
}, {
"http://%20leadingspace.com/",
"%20leadingspace.com",
"/",
""
}, {
"https://www.securesite.com/",
"www.securesite.com",
"/",
""
}, {
"http://host.com/ab%23cd",
"host.com",
"/ab%23cd",
""
}, {
"http://host%3e.com//twoslashes?more//slashes",
"host>.com",
"/twoslashes",
"more//slashes"
}, {
"http://host.com/abc?val=xyz#anything",
"host.com",
"/abc",
"val=xyz"
}, {
"http://abc:[email protected]/xyz",
"host.com",
"/xyz",
""
}, {
"http://host%3e.com/abc/%2e%2e%2fdef",
"host>.com",
"/def",
""
}, {
"http://.......host...com.....//abc/////def%2F%2F%2Fxyz",
"host.com",
"/abc/def/xyz",
""
}, {
"ftp://host.com/foo?bar",
"host.com",
"/foo",
"bar"
}, {
"data:text/html;charset=utf-8,%0D%0A",
"",
"",
""
}, {
"javascript:alert()",
"",
"",
""
}, {
"mailto:[email protected]",
"",
"",
""
},
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
SCOPED_TRACE(StringPrintf("Test: %s", tests[i].input_url));
GURL url(tests[i].input_url);
std::string canonicalized_hostname;
std::string canonicalized_path;
std::string canonicalized_query;
safe_browsing_util::CanonicalizeUrl(url, &canonicalized_hostname,
&canonicalized_path, &canonicalized_query);
EXPECT_EQ(tests[i].expected_canonicalized_hostname,
canonicalized_hostname);
EXPECT_EQ(tests[i].expected_canonicalized_path,
canonicalized_path);
EXPECT_EQ(tests[i].expected_canonicalized_query,
canonicalized_query);
}
}
TEST(SafeBrowsingUtilTest, GetUrlHashIndex) {
GURL url("http://www.evil.com/phish.html");
SBFullHashResult full_hash;
crypto::SHA256HashString(url.host() + url.path(),
&full_hash.hash,
sizeof(SBFullHash));
std::vector<SBFullHashResult> full_hashes;
full_hashes.push_back(full_hash);
EXPECT_EQ(safe_browsing_util::GetUrlHashIndex(url, full_hashes), 0);
url = GURL("http://www.evil.com/okay_path.html");
EXPECT_EQ(safe_browsing_util::GetUrlHashIndex(url, full_hashes), -1);
}
TEST(SafeBrowsingUtilTest, ListIdListNameConversion) {
std::string list_name;
EXPECT_FALSE(safe_browsing_util::GetListName(safe_browsing_util::INVALID,
&list_name));
EXPECT_TRUE(safe_browsing_util::GetListName(safe_browsing_util::MALWARE,
&list_name));
EXPECT_EQ(list_name, std::string(safe_browsing_util::kMalwareList));
EXPECT_EQ(safe_browsing_util::MALWARE,
safe_browsing_util::GetListId(list_name));
EXPECT_TRUE(safe_browsing_util::GetListName(safe_browsing_util::PHISH,
&list_name));
EXPECT_EQ(list_name, std::string(safe_browsing_util::kPhishingList));
EXPECT_EQ(safe_browsing_util::PHISH,
safe_browsing_util::GetListId(list_name));
EXPECT_TRUE(safe_browsing_util::GetListName(safe_browsing_util::BINURL,
&list_name));
EXPECT_EQ(list_name, std::string(safe_browsing_util::kBinUrlList));
EXPECT_EQ(safe_browsing_util::BINURL,
safe_browsing_util::GetListId(list_name));
EXPECT_TRUE(safe_browsing_util::GetListName(safe_browsing_util::BINHASH,
&list_name));
EXPECT_EQ(list_name, std::string(safe_browsing_util::kBinHashList));
EXPECT_EQ(safe_browsing_util::BINHASH,
safe_browsing_util::GetListId(list_name));
}
// Since the ids are saved in file, we need to make sure they don't change.
// Since only the last bit of each id is saved in file together with
// chunkids, this checks only last bit.
TEST(SafeBrowsingUtilTest, ListIdVerification) {
EXPECT_EQ(0, safe_browsing_util::MALWARE % 2);
EXPECT_EQ(1, safe_browsing_util::PHISH % 2);
EXPECT_EQ(0, safe_browsing_util::BINURL %2);
EXPECT_EQ(1, safe_browsing_util::BINHASH % 2);
}
TEST(SafeBrowsingUtilTest, StringToSBFullHashAndSBFullHashToString) {
// 31 chars plus the last \0 as full_hash.
const std::string hash_in = "12345678902234567890323456789012";
SBFullHash hash_out;
safe_browsing_util::StringToSBFullHash(hash_in, &hash_out);
EXPECT_EQ(0x34333231, hash_out.prefix);
EXPECT_EQ(0, memcmp(hash_in.data(), hash_out.full_hash, sizeof(SBFullHash)));
std::string hash_final = safe_browsing_util::SBFullHashToString(hash_out);
EXPECT_EQ(hash_in, hash_final);
}
| qtekfun/htcDesire820Kernel | external/chromium/chrome/browser/safe_browsing/safe_browsing_util_unittest.cc | C++ | gpl-2.0 | 10,010 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/**
* QuickSearchDefaults class, outputs default values for setting up quicksearch
*
* @copyright 2004-2007 SugarCRM Inc.
* @license http://www.sugarcrm.com/crm/products/sugar-professional-eula.html SugarCRM Professional End User License
* @since Class available since Release 4.0
*/
class QuickSearchDefaults
{
var $form_name = 'EditView';
/**
* getQuickSearchDefaults
*
* This is a static function to get an instance of QuickSearchDefaults object
*
* @param array $lookup Array with custom files and class names for custom QuickSearchDefaults classes, optional
* @return QuickSearchDefaults
*/
static public function getQuickSearchDefaults(array $lookup = array())
{
$lookup['custom/include/QuickSearchDefaults.php'] = 'QuickSearchDefaultsCustom';
foreach ($lookup as $file => $class)
{
if (file_exists($file))
{
require_once($file);
return new $class();
}
}
return new QuickSearchDefaults();
}
function setFormName($name = 'EditView') {
$this->form_name = $name;
}
function getQSParent($parent = 'Accounts') {
global $app_strings;
$qsParent = array(
'form' => $this->form_name,
'method' => 'query',
'modules' => array($parent),
'group' => 'or',
'field_list' => array('name', 'id'),
'populate_list' => array('parent_name', 'parent_id'),
'required_list' => array('parent_id'),
'conditions' => array(array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'')),
'order' => 'name',
'limit' => '30',
'no_match_text' => $app_strings['ERR_SQS_NO_MATCH']
);
return $qsParent;
}
function getQSAccount($nameKey, $idKey, $billingKey = null, $shippingKey = null, $additionalFields = null) {
global $app_strings;
$field_list = array('name', 'id');
$populate_list = array($nameKey, $idKey);
if($billingKey != null) {
$field_list = array_merge($field_list, array('billing_address_street', 'billing_address_city',
'billing_address_state', 'billing_address_postalcode', 'billing_address_country'));
$populate_list = array_merge($populate_list, array($billingKey . "_address_street", $billingKey . "_address_city",
$billingKey . "_address_state", $billingKey . "_address_postalcode", $billingKey . "_address_country"));
} //if
if($shippingKey != null) {
$field_list = array_merge($field_list, array('shipping_address_street', 'shipping_address_city',
'shipping_address_state', 'shipping_address_postalcode', 'shipping_address_country'));
$populate_list = array_merge($populate_list, array($shippingKey . "_address_street", $shippingKey . "_address_city",
$shippingKey . "_address_state", $shippingKey . "_address_postalcode", $shippingKey . "_address_country"));
}
if(!empty($additionalFields) && is_array($additionalFields)) {
$field_list = array_merge($field_list, array_keys($additionalFields));
$populate_list = array_merge($populate_list, array_values($additionalFields));
}
$qsParent = array(
'form' => $this->form_name,
'method' => 'query',
'modules' => array('Accounts'),
'group' => 'or',
'field_list' => $field_list,
'populate_list' => $populate_list,
'conditions' => array(array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'')),
'required_list' => array($idKey),
'order' => 'name',
'limit' => '30',
'no_match_text' => $app_strings['ERR_SQS_NO_MATCH']
);
return $qsParent;
}
/**
* getQSContact
* This is a customized method to handle returning in JSON notation the QuickSearch formats
* for searching the Contacts module for a contact name. The method takes into account
* the locale settings (s = salutation, f = first name, l = last name) that are permissible.
* It should be noted though that any other characters present in the formatting will render
* this widget non-functional.
* @return The JSON format of a QuickSearch definition for the Contacts module
*/
function getQSContact($name, $idName) {
global $app_strings, $locale;
$qsContact = array('form' => $this->form_name,
'method'=>'get_contact_array',
'modules'=>array('Contacts'),
'field_list' => array('salutation', 'first_name', 'last_name', 'id'),
'populate_list' => array($name, $idName, $idName, $idName),
'required_list' => array($idName),
'group' => 'or',
'conditions' => array(
array('name'=>'first_name', 'op'=>'like_custom','end'=>'%','value'=>''),
array('name'=>'last_name', 'op'=>'like_custom','end'=>'%','value'=>'')
),
'order'=>'last_name',
'limit'=>'30',
'no_match_text'=> $app_strings['ERR_SQS_NO_MATCH']);
return $qsContact;
}
function getQSUser($p_name = 'assigned_user_name', $p_id ='assigned_user_id') {
global $app_strings;
$qsUser = array('form' => $this->form_name,
'method' => 'get_user_array', // special method
'field_list' => array('user_name', 'id'),
'populate_list' => array($p_name, $p_id),
'required_list' => array($p_id),
'conditions' => array(array('name'=>'user_name','op'=>'like_custom','end'=>'%','value'=>'')),
'limit' => '30','no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
return $qsUser;
}
function getQSCampaigns($c_name = 'campaign_name', $c_id = 'campaign_id') {
global $app_strings;
$qsCampaign = array('form' => $this->form_name,
'method' => 'query',
'modules'=> array('Campaigns'),
'group' => 'or',
'field_list' => array('name', 'id'),
'populate_list' => array($c_name, $c_id),
'conditions' => array(array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'')),
'required_list' => array('campaign_id'),
'order' => 'name',
'limit' => '30',
'no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
return $qsCampaign;
}
/**
* Loads Quick Search Object for any object (if suitable method is defined)
*
* @param string $module the given module we want to load the vardefs for
* @param string $object the given object we wish to load the vardefs for
* @param string $relationName the name of the relation between entities
* @param type $nameField the name of the field to populate
* @param type $idField the id of the field to populate
*/
function loadQSObject($module, $object, $relationName, $nameField, $idField)
{
$result = array();
VardefManager::loadVardef($module, $object);
if (isset($GLOBALS['dictionary'][$object]['relationships']) && array_key_exists($relationName, $GLOBALS['dictionary'][$object]['relationships']))
{
if (method_exists($this, 'getQS' . $module))
{
$result = $this->{'getQS' . $module};
} elseif (method_exists($this, 'getQS' . $object))
{
$result = $this->{'getQS' . $object};
}
} else
{
if (method_exists($this, 'getQS' . $module))
{
$result = $this->{'getQS' . $module}($nameField, $idField);
} elseif (method_exists($this, 'getQS' . $object))
{
$result = $this->{'getQS' . $object}($nameField, $idField);
}
}
return $result;
}
// BEGIN QuickSearch functions for 4.5.x backwards compatibility support
function getQSScripts() {
global $sugar_version, $sugar_config, $theme;
$qsScripts = '<script type="text/javascript">sqsWaitGif = "' . SugarThemeRegistry::current()->getImageURL('sqsWait.gif') . '";</script>
<script type="text/javascript" src="'. getJSPath('include/javascript/quicksearch.js') . '"></script>';
return $qsScripts;
}
function getQSScriptsNoServer() {
return $this->getQSScripts();
}
function getQSScriptsJSONAlreadyDefined() {
global $sugar_version, $sugar_config, $theme;
$qsScriptsJSONAlreadyDefined = '<script type="text/javascript">sqsWaitGif = "' . SugarThemeRegistry::current()->getImageURL('sqsWait.gif') . '";</script><script type="text/javascript" src="' . getJSPath('include/javascript/quicksearch.js') . '"></script>';
return $qsScriptsJSONAlreadyDefined;
}
// END QuickSearch functions for 4.5.x backwards compatibility support
}
?>
| blackstark/site | www/sugar/include/QuickSearchDefaults.php | PHP | gpl-2.0 | 11,892 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "app/sql/connection.h"
#include "app/sql/statement.h"
#include "base/file_util.h"
#include "base/memory/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/sqlite/sqlite3.h"
class StatementErrorHandler : public sql::ErrorDelegate {
public:
StatementErrorHandler() : error_(SQLITE_OK) {}
virtual int OnError(int error, sql::Connection* connection,
sql::Statement* stmt) {
error_ = error;
const char* sql_txt = stmt ? stmt->GetSQLStatement() : NULL;
sql_text_ = sql_txt ? sql_txt : "no statement available";
return error;
}
int error() const { return error_; }
void reset_error() {
sql_text_.clear();
error_ = SQLITE_OK;
}
const char* sql_statement() const { return sql_text_.c_str(); }
private:
int error_;
std::string sql_text_;
};
class SQLStatementTest : public testing::Test {
public:
SQLStatementTest() : error_handler_(new StatementErrorHandler) {}
void SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
ASSERT_TRUE(db_.Open(temp_dir_.path().AppendASCII("SQLStatementTest.db")));
// The |error_handler_| will be called if any sqlite statement operation
// returns an error code.
db_.set_error_delegate(error_handler_);
}
void TearDown() {
// If any error happened the original sql statement can be found in
// error_handler_->sql_statement().
EXPECT_EQ(SQLITE_OK, error_handler_->error());
db_.Close();
}
sql::Connection& db() { return db_; }
int sqlite_error() const { return error_handler_->error(); }
void reset_error() const { error_handler_->reset_error(); }
private:
ScopedTempDir temp_dir_;
sql::Connection db_;
scoped_refptr<StatementErrorHandler> error_handler_;
};
TEST_F(SQLStatementTest, Assign) {
sql::Statement s;
EXPECT_FALSE(s); // bool conversion operator.
EXPECT_TRUE(!s); // ! operator.
EXPECT_FALSE(s.is_valid());
s.Assign(db().GetUniqueStatement("CREATE TABLE foo (a, b)"));
EXPECT_TRUE(s);
EXPECT_FALSE(!s);
EXPECT_TRUE(s.is_valid());
}
TEST_F(SQLStatementTest, Run) {
ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
ASSERT_TRUE(db().Execute("INSERT INTO foo (a, b) VALUES (3, 12)"));
sql::Statement s(db().GetUniqueStatement("SELECT b FROM foo WHERE a=?"));
EXPECT_FALSE(s.Succeeded());
// Stepping it won't work since we haven't bound the value.
EXPECT_FALSE(s.Step());
// Run should fail since this produces output, and we should use Step(). This
// gets a bit wonky since sqlite says this is OK so succeeded is set.
s.Reset();
s.BindInt(0, 3);
EXPECT_FALSE(s.Run());
EXPECT_EQ(SQLITE_ROW, db().GetErrorCode());
EXPECT_TRUE(s.Succeeded());
// Resetting it should put it back to the previous state (not runnable).
s.Reset();
EXPECT_FALSE(s.Succeeded());
// Binding and stepping should produce one row.
s.BindInt(0, 3);
EXPECT_TRUE(s.Step());
EXPECT_TRUE(s.Succeeded());
EXPECT_EQ(12, s.ColumnInt(0));
EXPECT_FALSE(s.Step());
EXPECT_TRUE(s.Succeeded());
}
TEST_F(SQLStatementTest, BasicErrorCallback) {
ASSERT_TRUE(db().Execute("CREATE TABLE foo (a INTEGER PRIMARY KEY, b)"));
EXPECT_EQ(SQLITE_OK, sqlite_error());
// Insert in the foo table the primary key. It is an error to insert
// something other than an number. This error causes the error callback
// handler to be called with SQLITE_MISMATCH as error code.
sql::Statement s(db().GetUniqueStatement("INSERT INTO foo (a) VALUES (?)"));
EXPECT_TRUE(s.is_valid());
s.BindCString(0, "bad bad");
EXPECT_FALSE(s.Run());
EXPECT_EQ(SQLITE_MISMATCH, sqlite_error());
reset_error();
}
| xdajog/samsung_sources_i927 | external/chromium/app/sql/statement_unittest.cc | C++ | gpl-2.0 | 3,841 |
<?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\Bridge\Doctrine\Security\User;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Wrapper around a Doctrine ObjectManager.
*
* Provides easy to use provisioning for Doctrine entity users.
*
* @author Fabien Potencier <[email protected]>
* @author Johannes M. Schmitt <[email protected]>
*/
class EntityUserProvider implements UserProviderInterface
{
private $registry;
private $managerName;
private $classOrAlias;
private $class;
private $property;
public function __construct(ManagerRegistry $registry, $classOrAlias, $property = null, $managerName = null)
{
$this->registry = $registry;
$this->managerName = $managerName;
$this->classOrAlias = $classOrAlias;
$this->property = $property;
}
/**
* {@inheritdoc}
*/
public function loadUserByUsername($username)
{
$repository = $this->getRepository();
if (null !== $this->property) {
$user = $repository->findOneBy(array($this->property => $username));
} else {
if (!$repository instanceof UserLoaderInterface) {
throw new \InvalidArgumentException(sprintf('The Doctrine repository "%s" must implement Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface.', get_class($repository)));
}
$user = $repository->loadUserByUsername($username);
}
if (null === $user) {
throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
}
return $user;
}
/**
* {@inheritdoc}
*/
public function refreshUser(UserInterface $user)
{
$class = $this->getClass();
if (!$user instanceof $class) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
$repository = $this->getRepository();
if ($repository instanceof UserProviderInterface) {
$refreshedUser = $repository->refreshUser($user);
} else {
// The user must be reloaded via the primary key as all other data
// might have changed without proper persistence in the database.
// That's the case when the user has been changed by a form with
// validation errors.
if (!$id = $this->getClassMetadata()->getIdentifierValues($user)) {
throw new \InvalidArgumentException('You cannot refresh a user '.
'from the EntityUserProvider that does not contain an identifier. '.
'The user object has to be serialized with its own identifier '.
'mapped by Doctrine.'
);
}
$refreshedUser = $repository->find($id);
if (null === $refreshedUser) {
throw new UsernameNotFoundException(sprintf('User with id %s not found', json_encode($id)));
}
}
return $refreshedUser;
}
/**
* {@inheritdoc}
*/
public function supportsClass($class)
{
return $class === $this->getClass() || is_subclass_of($class, $this->getClass());
}
private function getObjectManager()
{
return $this->registry->getManager($this->managerName);
}
private function getRepository()
{
return $this->getObjectManager()->getRepository($this->classOrAlias);
}
private function getClass()
{
if (null === $this->class) {
$class = $this->classOrAlias;
if (false !== strpos($class, ':')) {
$class = $this->getClassMetadata()->getName();
}
$this->class = $class;
}
return $this->class;
}
private function getClassMetadata()
{
return $this->getObjectManager()->getClassMetadata($this->classOrAlias);
}
}
| ivleneb/wptest | vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php | PHP | gpl-3.0 | 4,401 |
<!DOCTYPE html>
<html class="reftest-wait">
<title>WebVTT rendering, ::cue(), background properties</title>
<link rel="match" href="background_properties-ref.html">
<style>
html { overflow:hidden }
body { margin:0 }
::cue(*) {
font-family: Ahem, sans-serif;
background-color: #0f0;
background-image: url('../../media/background.gif');
background-repeat: repeat-x;
background-position: top left;
color: green;
}
</style>
<script src="/common/reftest-wait.js"></script>
<video width="320" height="180" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();">
<source src="/media/white.webm" type="video/webm">
<source src="/media/white.mp4" type="video/mp4">
<track src="../../support/test.vtt">
<script>
document.getElementsByTagName('track')[0].track.mode = 'showing';
</script>
</video>
</html>
| charlesvdv/servo | tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/selectors/cue_function/background_properties.html | HTML | mpl-2.0 | 864 |
class AddUrlToAccounts < ActiveRecord::Migration[4.2]
def change
add_column :accounts, :url, :string, null: true, default: nil
end
end
| salvadorpla/mastodon | db/migrate/20160223165855_add_url_to_accounts.rb | Ruby | agpl-3.0 | 143 |
/*! SWFMini - a SWFObject 2.2 cut down version for webshims
*
* based on SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfmini = function() {
var wasRemoved = function(){webshims.error('This method was removed from swfmini');};
var UNDEF = "undefined",
OBJECT = "object",
webshims = window.webshims,
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
isDomLoaded = false,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
})();
}
}
function createElement(el) {
return doc.createElement(el);
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
webshims.ready('DOM', callDomLoadFunctions);
webshims.loader.addModule('swfmini-embed', {d: ['swfmini']});
var loadEmbed = hasPlayerVersion('9.0.0') ?
function(){
webshims.loader.loadList(['swfmini-embed']);
return true;
} :
webshims.$.noop
;
if(!Modernizr.video){
loadEmbed();
} else {
webshims.ready('WINDOWLOAD', loadEmbed);
}
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: wasRemoved,
getObjectById: wasRemoved,
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var args = arguments;
if(loadEmbed()){
webshims.ready('swfmini-embed', function(){
swfmini.embedSWF.apply(swfmini, args);
});
} else if(callbackFn) {
callbackFn({success:false, id:replaceElemIdStr});
}
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: wasRemoved,
removeSWF: wasRemoved,
createCSS: wasRemoved,
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: wasRemoved,
// For internal usage only
expressInstallCallback: wasRemoved
};
}();
webshims.isReady('swfmini', true);
;// Copyright 2009-2012 by contributors, MIT License
// vim: ts=4 sts=4 sw=4 expandtab
(function () {
setTimeout(function(){
webshims.isReady('es5', true);
});
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
* Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/
*/
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var _Array_slice_ = prototypeOfArray.slice;
var array_splice = Array.prototype.splice;
var array_push = Array.prototype.push;
var array_unshift = Array.prototype.unshift;
// Having a toString local variable name breaks in Opera so use _toString.
var _toString = prototypeOfObject.toString;
var isFunction = function (val) {
return prototypeOfObject.toString.call(val) === '[object Function]';
};
var isRegex = function (val) {
return prototypeOfObject.toString.call(val) === '[object RegExp]';
};
var isArray = function isArray(obj) {
return _toString.call(obj) === "[object Array]";
};
var isArguments = function isArguments(value) {
var str = _toString.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = !isArray(str)
&& value !== null
&& typeof value === 'object'
&& typeof value.length === 'number'
&& value.length >= 0
&& isFunction(value.callee);
}
return isArgs;
};
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
function Empty() {}
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (!isFunction(target)) {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = _Array_slice_.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var binder = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var result = target.apply(
this,
args.concat(_Array_slice_.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
args.concat(_Array_slice_.call(arguments))
);
}
};
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
var boundLength = Math.max(0, target.length - args.length);
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push("$" + i);
}
// XXX Build a dynamic function with desired amount of arguments is the only
// way to set the length property of a function.
// In environments where Content Security Policies enabled (Chrome extensions,
// for ex.) all use of eval or Function costructor throws an exception.
// However in all of these environments Function.prototype.bind exists
// and so this code will never be executed.
var bound = Function("binder", "return function (" + boundArgs.join(",") + "){return binder.apply(this,arguments)}")(binder);
if (target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
// Clean up dangling references.
Empty.prototype = null;
}
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
};
}
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var owns = call.bind(prototypeOfObject.hasOwnProperty);
// If JS engine supports accessors creating shortcuts.
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.12
var spliceWorksWithEmptyObject = (function () {
var obj = {};
Array.prototype.splice.call(obj, 0, 0, 1);
return obj.length === 1;
}());
var omittingSecondSpliceArgIsNoop = [1].splice(0).length === 0;
var spliceNoopReturnsEmptyArray = (function () {
var a = [1, 2];
var result = a.splice();
return a.length === 2 && isArray(result) && result.length === 0;
}());
if (spliceNoopReturnsEmptyArray) {
// Safari 5.0 bug where .split() returns undefined
Array.prototype.splice = function splice(start, deleteCount) {
if (arguments.length === 0) { return []; }
else { return array_splice.apply(this, arguments); }
};
}
if (!omittingSecondSpliceArgIsNoop || !spliceWorksWithEmptyObject) {
Array.prototype.splice = function splice(start, deleteCount) {
if (arguments.length === 0) { return []; }
var args = arguments;
this.length = Math.max(toInteger(this.length), 0);
if (arguments.length > 0 && typeof deleteCount !== 'number') {
args = _Array_slice_.call(arguments);
if (args.length < 2) { args.push(toInteger(deleteCount)); }
else { args[1] = toInteger(deleteCount); }
}
return array_splice.apply(this, args);
};
}
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.13
// Return len+argCount.
// [bugfix, ielt8]
// IE < 8 bug: [].unshift(0) === undefined but should be "1"
if ([].unshift(0) !== 1) {
Array.prototype.unshift = function () {
array_unshift.apply(this, arguments);
return this.length;
};
}
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
Array.isArray = isArray;
}
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
// Check failure of by-index access of string characters (IE < 9)
// and failure of `0 in boxedString` (Rhino)
var boxedString = Object("a");
var splitString = boxedString[0] !== "a" || !(0 in boxedString);
var properlyBoxesContext = function properlyBoxed(method) {
// Check node 0.6.21 bug where third parameter is not boxed
var properlyBoxesNonStrict = true;
var properlyBoxesStrict = true;
if (method) {
method.call('foo', function (_, __, context) {
if (typeof context !== 'object') { properlyBoxesNonStrict = false; }
});
method.call([1], function () {
'use strict';
properlyBoxesStrict = typeof this === 'string';
}, 'x');
}
return !!method && properlyBoxesNonStrict && properlyBoxesStrict;
};
if (!Array.prototype.forEach || !properlyBoxesContext(Array.prototype.forEach)) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
object,
thisp = arguments[1],
i = -1,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object
// context
fun.call(thisp, self[i], i, object);
}
}
};
}
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map || !properlyBoxesContext(Array.prototype.map)) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
result[i] = fun.call(thisp, self[i], i, object);
}
}
return result;
};
}
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
if (!Array.prototype.filter || !properlyBoxesContext(Array.prototype.filter)) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = [],
value,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (fun.call(thisp, value, i, object)) {
result.push(value);
}
}
}
return result;
};
}
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
if (!Array.prototype.every || !properlyBoxesContext(Array.prototype.every)) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some || !properlyBoxesContext(Array.prototype.some)) {
Array.prototype.some = function some(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, object)) {
return true;
}
}
return false;
};
}
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
var reduceCoercesToObject = false;
if (Array.prototype.reduce) {
reduceCoercesToObject = typeof Array.prototype.reduce.call('es5', function (_, __, ___, list) { return list; }) === 'object';
}
if (!Array.prototype.reduce || !reduceCoercesToObject) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value and an empty array
if (!length && arguments.length === 1) {
throw new TypeError("reduce of empty array with no initial value");
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length) {
throw new TypeError("reduce of empty array with no initial value");
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = fun.call(void 0, result, self[i], i, object);
}
}
return result;
};
}
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
var reduceRightCoercesToObject = false;
if (Array.prototype.reduceRight) {
reduceRightCoercesToObject = typeof Array.prototype.reduceRight.call('es5', function (_, __, ___, list) { return list; }) === 'object';
}
if (!Array.prototype.reduceRight || !reduceRightCoercesToObject) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value, empty array
if (!length && arguments.length === 1) {
throw new TypeError("reduceRight of empty array with no initial value");
}
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0) {
throw new TypeError("reduceRight of empty array with no initial value");
}
} while (true);
}
if (i < 0) {
return result;
}
do {
if (i in self) {
result = fun.call(void 0, result, self[i], i, object);
}
} while (i--);
return result;
};
}
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) !== -1)) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = toInteger(arguments[1]);
}
// handle negative indices
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) !== -1)) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = splitString && _toString.call(this) === "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = Math.min(i, toInteger(arguments[1]));
}
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i]) {
return i;
}
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
var keysWorksWithArguments = Object.keys && (function () {
return Object.keys(arguments).length === 2;
}(1, 2));
if (!Object.keys) {
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'),
hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'),
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
Object.keys = function keys(object) {
var isFn = isFunction(object),
isArgs = isArguments(object),
isObject = object !== null && typeof object === 'object',
isString = isObject && _toString.call(object) === '[object String]';
if (!isObject && !isFn && !isArgs) {
throw new TypeError("Object.keys called on a non-object");
}
var theKeys = [];
var skipProto = hasProtoEnumBug && isFn;
if (isString || isArgs) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && owns(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var ctor = object.constructor,
skipConstructor = ctor && ctor.prototype === object;
for (var j = 0; j < dontEnumsLength; j++) {
var dontEnum = dontEnums[j];
if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) {
theKeys.push(dontEnum);
}
}
}
return theKeys;
};
} else if (!keysWorksWithArguments) {
// Safari 5.0 bug
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArguments(object)) {
return originalKeys(Array.prototype.slice.call(object));
} else {
return originalKeys(object);
}
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
var negativeDate = -62198755200000,
negativeYearString = "-000001";
if (
!Date.prototype.toISOString ||
(new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1)
) {
Date.prototype.toISOString = function toISOString() {
var result, length, value, year, month;
if (!isFinite(this)) {
throw new RangeError("Date.prototype.toISOString called on non-finite value.");
}
year = this.getUTCFullYear();
month = this.getUTCMonth();
// see https://github.com/es-shims/es5-shim/issues/111
year += Math.floor(month / 12);
month = (month % 12 + 12) % 12;
// the date time string format is specified in 15.9.1.15.
result = [month + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = (
(year < 0 ? "-" : (year > 9999 ? "+" : "")) +
("00000" + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6)
);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two
// digits.
if (value < 10) {
result[length] = "0" + value;
}
}
// pad milliseconds to have three digits.
return (
year + "-" + result.slice(0, 2).join("-") +
"T" + result.slice(2).join(":") + "." +
("000" + this.getUTCMilliseconds()).slice(-3) + "Z"
);
};
}
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
var dateToJSONIsSupported = false;
try {
dateToJSONIsSupported = (
Date.prototype.toJSON &&
new Date(NaN).toJSON() === null &&
new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 &&
Date.prototype.toJSON.call({ // generic
toISOString: function () {
return true;
}
})
);
} catch (e) {
}
if (!dateToJSONIsSupported) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be toPrimitive(O, hint Number).
var o = Object(this),
tv = toPrimitive(o),
toISO;
// 3. If tv is a Number and is not finite, return null.
if (typeof tv === "number" && !isFinite(tv)) {
return null;
}
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
toISO = o.toISOString;
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof toISO !== "function") {
throw new TypeError("toISOString property is not callable");
}
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return toISO.call(o);
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
var supportsExtendedYears = Date.parse('+033658-09-27T01:46:40.000Z') === 1e15;
var acceptsInvalidDates = !isNaN(Date.parse('2012-04-04T24:00:00.500Z')) || !isNaN(Date.parse('2012-11-31T23:59:59.000Z'));
var doesNotParseY2KNewYear = isNaN(Date.parse("2000-01-01T00:00:00.000Z"));
if (!Date.parse || doesNotParseY2KNewYear || acceptsInvalidDates || !supportsExtendedYears) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function (NativeDate) {
// Date.length === 7
function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length === 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
}
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp("^" +
"(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign +
// 6-digit extended year
"(?:-(\\d{2})" + // optional month capture
"(?:-(\\d{2})" + // optional day capture
"(?:" + // capture hours:minutes:seconds.milliseconds
"T(\\d{2})" + // hours capture
":(\\d{2})" + // minutes capture
"(?:" + // optional :seconds.milliseconds
":(\\d{2})" + // seconds capture
"(?:(\\.\\d{1,}))?" + // milliseconds capture
")?" +
"(" + // capture UTC offset component
"Z|" + // UTC capture
"(?:" + // offset specifier +/-hours:minutes
"([-+])" + // sign capture
"(\\d{2})" + // hours offset capture
":(\\d{2})" + // minutes offset capture
")" +
")?)?)?)?" +
"$");
var months = [
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
];
function dayFromMonth(year, month) {
var t = month > 1 ? 1 : 0;
return (
months[month] +
Math.floor((year - 1969 + t) / 4) -
Math.floor((year - 1901 + t) / 100) +
Math.floor((year - 1601 + t) / 400) +
365 * (year - 1970)
);
}
function toUTC(t) {
return Number(new NativeDate(1970, 0, 1, 0, 0, 0, t));
}
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate) {
Date[key] = NativeDate[key];
}
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle simplified ISO 8601 strings
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
// parse months, days, hours, minutes, seconds, and milliseconds
// provide default values if necessary
// parse the UTC offset component
var year = Number(match[1]),
month = Number(match[2] || 1) - 1,
day = Number(match[3] || 1) - 1,
hour = Number(match[4] || 0),
minute = Number(match[5] || 0),
second = Number(match[6] || 0),
millisecond = Math.floor(Number(match[7] || 0) * 1000),
// When time zone is missed, local offset should be used
// (ES 5.1 bug)
// see https://bugs.ecmascript.org/show_bug.cgi?id=112
isLocalTime = Boolean(match[4] && !match[8]),
signOffset = match[9] === "-" ? 1 : -1,
hourOffset = Number(match[10] || 0),
minuteOffset = Number(match[11] || 0),
result;
if (
hour < (
minute > 0 || second > 0 || millisecond > 0 ?
24 : 25
) &&
minute < 60 && second < 60 && millisecond < 1000 &&
month > -1 && month < 12 && hourOffset < 24 &&
minuteOffset < 60 && // detect invalid offsets
day > -1 &&
day < (
dayFromMonth(year, month + 1) -
dayFromMonth(year, month)
)
) {
result = (
(dayFromMonth(year, month) + day) * 24 +
hour +
hourOffset * signOffset
) * 60;
result = (
(result + minute + minuteOffset * signOffset) * 60 +
second
) * 1000 + millisecond;
if (isLocalTime) {
result = toUTC(result);
}
if (-8.64e15 <= result && result <= 8.64e15) {
return result;
}
}
return NaN;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
//
// Number
// ======
//
// ES5.1 15.7.4.5
// http://es5.github.com/#x15.7.4.5
if (!Number.prototype.toFixed || (0.00008).toFixed(3) !== '0.000' || (0.9).toFixed(0) === '0' || (1.255).toFixed(2) !== '1.25' || (1000000000000000128).toFixed(0) !== "1000000000000000128") {
// Hide these variables and functions
(function () {
var base, size, data, i;
base = 1e7;
size = 6;
data = [0, 0, 0, 0, 0, 0];
function multiply(n, c) {
var i = -1;
while (++i < size) {
c += n * data[i];
data[i] = c % base;
c = Math.floor(c / base);
}
}
function divide(n) {
var i = size, c = 0;
while (--i >= 0) {
c += data[i];
data[i] = Math.floor(c / n);
c = (c % n) * base;
}
}
function numToString() {
var i = size;
var s = '';
while (--i >= 0) {
if (s !== '' || i === 0 || data[i] !== 0) {
var t = String(data[i]);
if (s === '') {
s = t;
} else {
s += '0000000'.slice(0, 7 - t.length) + t;
}
}
}
return s;
}
function pow(x, n, acc) {
return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc)));
}
function log(x) {
var n = 0;
while (x >= 4096) {
n += 12;
x /= 4096;
}
while (x >= 2) {
n += 1;
x /= 2;
}
return n;
}
Number.prototype.toFixed = function toFixed(fractionDigits) {
var f, x, s, m, e, z, j, k;
// Test for NaN and round fractionDigits down
f = Number(fractionDigits);
f = f !== f ? 0 : Math.floor(f);
if (f < 0 || f > 20) {
throw new RangeError("Number.toFixed called with invalid number of decimals");
}
x = Number(this);
// Test for NaN
if (x !== x) {
return "NaN";
}
// If it is too big or small, return the string value of the number
if (x <= -1e21 || x >= 1e21) {
return String(x);
}
s = "";
if (x < 0) {
s = "-";
x = -x;
}
m = "0";
if (x > 1e-21) {
// 1e-21 < x < 1e21
// -70 < log2(x) < 70
e = log(x * pow(2, 69, 1)) - 69;
z = (e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1));
z *= 0x10000000000000; // Math.pow(2, 52);
e = 52 - e;
// -18 < e < 122
// x = z / 2 ^ e
if (e > 0) {
multiply(0, z);
j = f;
while (j >= 7) {
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << (-e), 0);
m = numToString() + '0.00000000000000000000'.slice(2, 2 + f);
}
}
if (f > 0) {
k = m.length;
if (k <= f) {
m = s + '0.0000000000000000000'.slice(0, f - k + 2) + m;
} else {
m = s + m.slice(0, k - f) + '.' + m.slice(k - f);
}
} else {
m = s + m;
}
return m;
};
}());
}
//
// String
// ======
//
// ES5 15.5.4.14
// http://es5.github.com/#x15.5.4.14
// [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
// Many browsers do not split properly with regular expressions or they
// do not perform the split correctly under obscure conditions.
// See http://blog.stevenlevithan.com/archives/cross-browser-split
// I've tested in many browsers and this seems to cover the deviant ones:
// 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
// '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
// 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
// [undefined, "t", undefined, "e", ...]
// ''.split(/.?/) should be [], not [""]
// '.'.split(/()()/) should be ["."], not ["", "", "."]
var string_split = String.prototype.split;
if (
'ab'.split(/(?:ab)*/).length !== 2 ||
'.'.split(/(.?)(.?)/).length !== 4 ||
'tesst'.split(/(s)*/)[1] === "t" ||
'test'.split(/(?:)/, -1).length !== 4 ||
''.split(/.?/).length ||
'.'.split(/()()/).length > 1
) {
(function () {
var compliantExecNpcg = /()??/.exec("")[1] === void 0; // NPCG: nonparticipating capturing group
String.prototype.split = function (separator, limit) {
var string = this;
if (separator === void 0 && limit === 0) {
return [];
}
// If `separator` is not a regex, use native split
if (_toString.call(separator) !== "[object RegExp]") {
return string_split.call(this, separator, limit);
}
var output = [],
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.extended ? "x" : "") + // Proposed for ES6
(separator.sticky ? "y" : ""), // Firefox 3+
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
separator = new RegExp(separator.source, flags + "g");
string += ""; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // Math.pow(2, 32) - 1
* If 0, Infinity, or NaN: 0
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
* If other: Type-convert, then use the above rules
*/
limit = limit === void 0 ?
-1 >>> 0 : // Math.pow(2, 32) - 1
ToUint32(limit);
while (match = separator.exec(string)) {
// `separator.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0].length;
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === void 0) {
match[i] = void 0;
}
}
});
}
if (match.length > 1 && match.index < string.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // Avoid an infinite loop
}
}
if (lastLastIndex === string.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(string.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
}());
// [bugfix, chrome]
// If separator is undefined, then the result array contains just one String,
// which is the this value (converted to a String). If limit is not undefined,
// then the output array is truncated so that it contains no more than limit
// elements.
// "0".split(undefined, 0) -> []
} else if ("0".split(void 0, 0).length) {
String.prototype.split = function split(separator, limit) {
if (separator === void 0 && limit === 0) { return []; }
return string_split.call(this, separator, limit);
};
}
var str_replace = String.prototype.replace;
var replaceReportsGroupsCorrectly = (function () {
var groups = [];
'x'.replace(/x(.)?/g, function (match, group) {
groups.push(group);
});
return groups.length === 1 && typeof groups[0] === 'undefined';
}());
if (!replaceReportsGroupsCorrectly) {
String.prototype.replace = function replace(searchValue, replaceValue) {
var isFn = isFunction(replaceValue);
var hasCapturingGroups = isRegex(searchValue) && (/\)[*?]/).test(searchValue.source);
if (!isFn || !hasCapturingGroups) {
return str_replace.call(this, searchValue, replaceValue);
} else {
var wrappedReplaceValue = function (match) {
var length = arguments.length;
var originalLastIndex = searchValue.lastIndex;
searchValue.lastIndex = 0;
var args = searchValue.exec(match);
searchValue.lastIndex = originalLastIndex;
args.push(arguments[length - 2], arguments[length - 1]);
return replaceValue.apply(this, args);
};
return str_replace.call(this, searchValue, wrappedReplaceValue);
}
};
}
// ECMA-262, 3rd B.2.3
// Not an ECMAScript standard, although ECMAScript 3rd Edition has a
// non-normative section suggesting uniform semantics and it should be
// normalized across all browsers
// [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
if ("".substr && "0b".substr(-1) !== "b") {
var string_substr = String.prototype.substr;
/**
* Get the substring of a string
* @param {integer} start where to start the substring
* @param {integer} length how many characters to return
* @return {string}
*/
String.prototype.substr = function substr(start, length) {
return string_substr.call(
this,
start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start,
length
);
};
}
// ES5 15.5.4.20
// whitespace from: http://es5.github.io/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
var zeroWidth = '\u200b';
if (!String.prototype.trim || ws.trim() || !zeroWidth.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
if (this === void 0 || this === null) {
throw new TypeError("can't convert " + this + " to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
};
}
// ES-5 15.1.2.2
if (parseInt(ws + '08') !== 8 || parseInt(ws + '0x16') !== 22) {
parseInt = (function (origParseInt) {
var hexRegex = /^0[xX]/;
return function parseIntES5(str, radix) {
str = String(str).trim();
if (!Number(radix)) {
radix = hexRegex.test(str) ? 16 : 10;
}
return origParseInt(str, radix);
};
}(parseInt));
}
//
// Util
// ======
//
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
function toInteger(n) {
n = +n;
if (n !== n) { // isNaN
n = 0;
} else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
}
function isPrimitive(input) {
var type = typeof input;
return (
input === null ||
type === "undefined" ||
type === "boolean" ||
type === "number" ||
type === "string"
);
}
function toPrimitive(input) {
var val, valueOf, toStr;
if (isPrimitive(input)) {
return input;
}
valueOf = input.valueOf;
if (isFunction(valueOf)) {
val = valueOf.call(input);
if (isPrimitive(val)) {
return val;
}
}
toStr = input.toString;
if (isFunction(toStr)) {
val = toStr.call(input);
if (isPrimitive(val)) {
return val;
}
}
throw new TypeError();
}
// ES5 9.9
// http://es5.github.com/#x9.9
var toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert " + o + " to object");
}
return Object(o);
};
var ToUint32 = function ToUint32(x) {
return x >>> 0;
};
})();
(function($, shims){
var defineProperty = 'defineProperty';
var advancedObjectProperties = !!(Object.create && Object.defineProperties && Object.getOwnPropertyDescriptor);
//safari5 has defineProperty-interface, but it can't be used on dom-object
//only do this test in non-IE browsers, because this hurts dhtml-behavior in some IE8 versions
if (advancedObjectProperties && Object[defineProperty] && Object.prototype.__defineGetter__) {
(function(){
try {
var foo = document.createElement('foo');
Object[defineProperty](foo, 'bar', {
get: function(){
return true;
}
});
advancedObjectProperties = !!foo.bar;
}
catch (e) {
advancedObjectProperties = false;
}
foo = null;
})();
}
Modernizr.objectAccessor = !!((advancedObjectProperties || (Object.prototype.__defineGetter__ && Object.prototype.__lookupSetter__)));
Modernizr.advancedObjectProperties = advancedObjectProperties;
if((!advancedObjectProperties || !Object.create || !Object.defineProperties || !Object.getOwnPropertyDescriptor || !Object.defineProperty)){
var call = Function.prototype.call;
var prototypeOfObject = Object.prototype;
var owns = call.bind(prototypeOfObject.hasOwnProperty);
shims.objectCreate = function(proto, props, opts, no__proto__){
var o;
var f = function(){};
f.prototype = proto;
o = new f();
if(!no__proto__ && !('__proto__' in o) && !Modernizr.objectAccessor){
o.__proto__ = proto;
}
if(props){
shims.defineProperties(o, props);
}
if(opts){
o.options = $.extend(true, {}, o.options || {}, opts);
opts = o.options;
}
if(o._create && $.isFunction(o._create)){
o._create(opts);
}
return o;
};
shims.defineProperties = function(object, props){
for (var name in props) {
if (owns(props, name)) {
shims.defineProperty(object, name, props[name]);
}
}
return object;
};
var descProps = ['configurable', 'enumerable', 'writable'];
shims.defineProperty = function(proto, property, descriptor){
if(typeof descriptor != "object" || descriptor === null){return proto;}
if(owns(descriptor, "value")){
proto[property] = descriptor.value;
return proto;
}
if(proto.__defineGetter__){
if (typeof descriptor.get == "function") {
proto.__defineGetter__(property, descriptor.get);
}
if (typeof descriptor.set == "function"){
proto.__defineSetter__(property, descriptor.set);
}
}
return proto;
};
shims.getPrototypeOf = function (object) {
return Object.getPrototypeOf && Object.getPrototypeOf(object) || object.__proto__ || object.constructor && object.constructor.prototype;
};
//based on http://www.refactory.org/s/object_getownpropertydescriptor/view/latest
shims.getOwnPropertyDescriptor = function(obj, prop){
if (typeof obj !== "object" && typeof obj !== "function" || obj === null){
throw new TypeError("Object.getOwnPropertyDescriptor called on a non-object");
}
var descriptor;
if(Object.defineProperty && Object.getOwnPropertyDescriptor){
try{
descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return descriptor;
} catch(e){}
}
descriptor = {
configurable: true,
enumerable: true,
writable: true,
value: undefined
};
var getter = obj.__lookupGetter__ && obj.__lookupGetter__(prop),
setter = obj.__lookupSetter__ && obj.__lookupSetter__(prop)
;
if (!getter && !setter) { // not an accessor so return prop
if(!owns(obj, prop)){
return;
}
descriptor.value = obj[prop];
return descriptor;
}
// there is an accessor, remove descriptor.writable; populate descriptor.get and descriptor.set
delete descriptor.writable;
delete descriptor.value;
descriptor.get = descriptor.set = undefined;
if(getter){
descriptor.get = getter;
}
if(setter){
descriptor.set = setter;
}
return descriptor;
};
}
webshims.isReady('es5', true);
})(webshims.$, webshims);
;
//this might was already extended by ES5 shim feature
(function($){
"use strict";
var webshims = window.webshims;
if(webshims.defineProperties){return;}
var defineProperty = 'defineProperty';
var has = Object.prototype.hasOwnProperty;
var descProps = ['configurable', 'enumerable', 'writable'];
var extendUndefined = function(prop){
for(var i = 0; i < 3; i++){
if(prop[descProps[i]] === undefined && (descProps[i] !== 'writable' || prop.value !== undefined)){
prop[descProps[i]] = true;
}
}
};
var extendProps = function(props){
if(props){
for(var i in props){
if(has.call(props, i)){
extendUndefined(props[i]);
}
}
}
};
if(Object.create){
webshims.objectCreate = function(proto, props, opts){
extendProps(props);
var o = Object.create(proto, props);
if(opts){
o.options = $.extend(true, {}, o.options || {}, opts);
opts = o.options;
}
if(o._create && $.isFunction(o._create)){
o._create(opts);
}
return o;
};
}
if(Object[defineProperty]){
webshims[defineProperty] = function(obj, prop, desc){
extendUndefined(desc);
return Object[defineProperty](obj, prop, desc);
};
}
if(Object.defineProperties){
webshims.defineProperties = function(obj, props){
extendProps(props);
return Object.defineProperties(obj, props);
};
}
webshims.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
webshims.getPrototypeOf = Object.getPrototypeOf;
})(window.webshims.$);
//DOM-Extension helper
webshims.register('dom-extend', function($, webshims, window, document, undefined){
"use strict";
var supportHrefNormalized = !('hrefNormalized' in $.support) || $.support.hrefNormalized;
var supportGetSetAttribute = !('getSetAttribute' in $.support) || $.support.getSetAttribute;
var has = Object.prototype.hasOwnProperty;
webshims.assumeARIA = supportGetSetAttribute || Modernizr.canvas || Modernizr.video || Modernizr.boxsizing;
if($('<input type="email" />').attr('type') == 'text' || $('<form />').attr('novalidate') === "" || ('required' in $('<input />')[0].attributes)){
webshims.error("IE browser modes are busted in IE10+. Please test your HTML/CSS/JS with a real IE version or at least IETester or similiar tools");
}
if('debug' in webshims){
webshims.error('Use webshims.setOptions("debug", true||false||"noCombo"); to debug flag');
}
if (!webshims.cfg.no$Switch) {
var switch$ = function(){
if (window.jQuery && (!window.$ || window.jQuery == window.$) && !window.jQuery.webshims) {
webshims.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'.");
if (window.$) {
window.$ = webshims.$;
}
window.jQuery = webshims.$;
}
if(webshims.M != Modernizr){
webshims.error("Modernizr was included more than once. Make sure to include it only once! Webshims and other scripts might not work properly.");
for(var i in Modernizr){
if(!(i in webshims.M)){
webshims.M[i] = Modernizr[i];
}
}
Modernizr = webshims.M;
}
};
switch$();
setTimeout(switch$, 90);
webshims.ready('DOM', switch$);
$(switch$);
webshims.ready('WINDOWLOAD', switch$);
}
//shortcus
var modules = webshims.modules;
var listReg = /\s*,\s*/;
//proxying attribute
var olds = {};
var havePolyfill = {};
var hasPolyfillMethod = {};
var extendedProps = {};
var extendQ = {};
var modifyProps = {};
var oldVal = $.fn.val;
var singleVal = function(elem, name, val, pass, _argless){
return (_argless) ? oldVal.call($(elem)) : oldVal.call($(elem), val);
};
//jquery mobile and jquery ui
if(!$.widget){
(function(){
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
if(!$.widget){
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
}
_cleanData( elems );
};
})();
}
$.fn.val = function(val){
var elem = this[0];
if(arguments.length && val == null){
val = '';
}
if(!arguments.length){
if(!elem || elem.nodeType !== 1){return oldVal.call(this);}
return $.prop(elem, 'value', val, 'val', true);
}
if($.isArray(val)){
return oldVal.apply(this, arguments);
}
var isFunction = $.isFunction(val);
return this.each(function(i){
elem = this;
if(elem.nodeType === 1){
if(isFunction){
var genVal = val.call( elem, i, $.prop(elem, 'value', undefined, 'val', true));
if(genVal == null){
genVal = '';
}
$.prop(elem, 'value', genVal, 'val') ;
} else {
$.prop(elem, 'value', val, 'val');
}
}
});
};
$.fn.onTrigger = function(evt, fn){
return this.on(evt, fn).each(fn);
};
$.fn.onWSOff = function(evt, fn, trigger, evtDel){
if(!evtDel){
evtDel = document;
}
$(evtDel)[trigger ? 'onTrigger' : 'on'](evt, fn);
this.on('remove', function(e){
if(!e.originalEvent){
$(evtDel).off(evt, fn);
}
});
return this;
};
var idCount = 0;
var dataID = '_webshims'+ (Math.round(Math.random() * 1000));
var elementData = function(elem, key, val){
elem = elem.jquery ? elem[0] : elem;
if(!elem){return val || {};}
var data = $.data(elem, dataID);
if(val !== undefined){
if(!data){
data = $.data(elem, dataID, {});
}
if(key){
data[key] = val;
}
}
return key ? data && data[key] : data;
};
[{name: 'getNativeElement', prop: 'nativeElement'}, {name: 'getShadowElement', prop: 'shadowElement'}, {name: 'getShadowFocusElement', prop: 'shadowFocusElement'}].forEach(function(data){
$.fn[data.name] = function(){
var elems = [];
this.each(function(){
var shadowData = elementData(this, 'shadowData');
var elem = shadowData && shadowData[data.prop] || this;
if($.inArray(elem, elems) == -1){
elems.push(elem);
}
});
return this.pushStack(elems);
};
});
function clone(elem, dataAndEvents, uniqueIds){
var cloned = $.clone( elem, dataAndEvents, false );
$(cloned.querySelectorAll('.'+webshims.shadowClass)).detach();
if(uniqueIds){
idCount++;
$(cloned.querySelectorAll('[id]')).prop('id', function(i, id){
return id +idCount;
});
} else {
$(cloned.querySelectorAll('audio[id^="ID-"], video[id^="ID-"], label[id^="ID-"]')).removeAttr('id');
}
return cloned;
}
$.fn.clonePolyfill = function(dataAndEvents, uniqueIds){
dataAndEvents = dataAndEvents || false;
return this
.map(function() {
var cloned = clone( this, dataAndEvents, uniqueIds );
setTimeout(function(){
if($.contains(document.body, cloned)){
$(cloned).updatePolyfill();
}
});
return cloned;
})
;
};
//add support for $('video').trigger('play') in case extendNative is set to false
if(!webshims.cfg.extendNative && !webshims.cfg.noTriggerOverride){
(function(oldTrigger){
$.event.trigger = function(event, data, elem, onlyHandlers){
if(!hasPolyfillMethod[event] || onlyHandlers || !elem || elem.nodeType !== 1){
return oldTrigger.apply(this, arguments);
}
var ret, isOrig, origName;
var origFn = elem[event];
var polyfilledFn = $.prop(elem, event);
var changeFn = polyfilledFn && origFn != polyfilledFn;
if(changeFn){
origName = '__ws'+event;
isOrig = (event in elem) && has.call(elem, event);
elem[event] = polyfilledFn;
elem[origName] = origFn;
}
ret = oldTrigger.apply(this, arguments);
if (changeFn) {
if(isOrig){
elem[event] = origFn;
} else {
delete elem[event];
}
delete elem[origName];
}
return ret;
};
})($.event.trigger);
}
['removeAttr', 'prop', 'attr'].forEach(function(type){
olds[type] = $[type];
$[type] = function(elem, name, value, pass, _argless){
var isVal = (pass == 'val');
var oldMethod = !isVal ? olds[type] : singleVal;
if( !elem || !havePolyfill[name] || elem.nodeType !== 1 || (!isVal && pass && type == 'attr' && $.attrFn[name]) ){
return oldMethod(elem, name, value, pass, _argless);
}
var nodeName = (elem.nodeName || '').toLowerCase();
var desc = extendedProps[nodeName];
var curType = (type == 'attr' && (value === false || value === null)) ? 'removeAttr' : type;
var propMethod;
var oldValMethod;
var ret;
if(!desc){
desc = extendedProps['*'];
}
if(desc){
desc = desc[name];
}
if(desc){
propMethod = desc[curType];
}
if(propMethod){
if(name == 'value'){
oldValMethod = propMethod.isVal;
propMethod.isVal = isVal;
}
if(curType === 'removeAttr'){
return propMethod.value.call(elem);
} else if(value === undefined){
return (propMethod.get) ?
propMethod.get.call(elem) :
propMethod.value
;
} else if(propMethod.set) {
if(type == 'attr' && value === true){
value = name;
}
ret = propMethod.set.call(elem, value);
}
if(name == 'value'){
propMethod.isVal = oldValMethod;
}
} else {
ret = oldMethod(elem, name, value, pass, _argless);
}
if((value !== undefined || curType === 'removeAttr') && modifyProps[nodeName] && modifyProps[nodeName][name]){
var boolValue;
if(curType == 'removeAttr'){
boolValue = false;
} else if(curType == 'prop'){
boolValue = !!(value);
} else {
boolValue = true;
}
modifyProps[nodeName][name].forEach(function(fn){
if(!fn.only || (fn.only = 'prop' && type == 'prop') || (fn.only == 'attr' && type != 'prop')){
fn.call(elem, value, boolValue, (isVal) ? 'val' : curType, type);
}
});
}
return ret;
};
extendQ[type] = function(nodeName, prop, desc){
if(!extendedProps[nodeName]){
extendedProps[nodeName] = {};
}
if(!extendedProps[nodeName][prop]){
extendedProps[nodeName][prop] = {};
}
var oldDesc = extendedProps[nodeName][prop][type];
var getSup = function(propType, descriptor, oDesc){
var origProp;
if(descriptor && descriptor[propType]){
return descriptor[propType];
}
if(oDesc && oDesc[propType]){
return oDesc[propType];
}
if(type == 'prop' && prop == 'value'){
return function(value){
var elem = this;
return (desc.isVal) ?
singleVal(elem, prop, value, false, (arguments.length === 0)) :
olds[type](elem, prop, value)
;
};
}
if(type == 'prop' && propType == 'value' && desc.value.apply){
origProp = '__ws'+prop;
hasPolyfillMethod[prop] = true;
return function(value){
var sup = this[origProp] || olds[type](this, prop);
if(sup && sup.apply){
sup = sup.apply(this, arguments);
}
return sup;
};
}
return function(value){
return olds[type](this, prop, value);
};
};
extendedProps[nodeName][prop][type] = desc;
if(desc.value === undefined){
if(!desc.set){
desc.set = desc.writeable ?
getSup('set', desc, oldDesc) :
(webshims.cfg.useStrict && prop == 'prop') ?
function(){throw(prop +' is readonly on '+ nodeName);} :
function(){webshims.info(prop +' is readonly on '+ nodeName);}
;
}
if(!desc.get){
desc.get = getSup('get', desc, oldDesc);
}
}
['value', 'get', 'set'].forEach(function(descProp){
if(desc[descProp]){
desc['_sup'+descProp] = getSup(descProp, oldDesc);
}
});
};
});
var extendNativeValue = (function(){
var UNKNOWN = webshims.getPrototypeOf(document.createElement('foobar'));
//see also: https://github.com/lojjic/PIE/issues/40 | https://prototype.lighthouseapp.com/projects/8886/tickets/1107-ie8-fatal-crash-when-prototypejs-is-loaded-with-rounded-cornershtc
var isExtendNativeSave = Modernizr.advancedObjectProperties && Modernizr.objectAccessor;
return function(nodeName, prop, desc){
var elem , elemProto;
if( isExtendNativeSave && (elem = document.createElement(nodeName)) && (elemProto = webshims.getPrototypeOf(elem)) && UNKNOWN !== elemProto && ( !elem[prop] || !has.call(elem, prop) ) ){
var sup = elem[prop];
desc._supvalue = function(){
if(sup && sup.apply){
return sup.apply(this, arguments);
}
return sup;
};
elemProto[prop] = desc.value;
} else {
desc._supvalue = function(){
var data = elementData(this, 'propValue');
if(data && data[prop] && data[prop].apply){
return data[prop].apply(this, arguments);
}
return data && data[prop];
};
initProp.extendValue(nodeName, prop, desc.value);
}
desc.value._supvalue = desc._supvalue;
};
})();
var initProp = (function(){
var initProps = {};
webshims.addReady(function(context, contextElem){
var nodeNameCache = {};
var getElementsByName = function(name){
if(!nodeNameCache[name]){
nodeNameCache[name] = $(context.getElementsByTagName(name));
if(contextElem[0] && $.nodeName(contextElem[0], name)){
nodeNameCache[name] = nodeNameCache[name].add(contextElem);
}
}
};
$.each(initProps, function(name, fns){
getElementsByName(name);
if(!fns || !fns.forEach){
webshims.warn('Error: with '+ name +'-property. methods: '+ fns);
return;
}
fns.forEach(function(fn){
nodeNameCache[name].each(fn);
});
});
nodeNameCache = null;
});
var tempCache;
var emptyQ = $([]);
var createNodeNameInit = function(nodeName, fn){
if(!initProps[nodeName]){
initProps[nodeName] = [fn];
} else {
initProps[nodeName].push(fn);
}
if($.isDOMReady){
(tempCache || $( document.getElementsByTagName(nodeName) )).each(fn);
}
};
var elementExtends = {};
return {
createTmpCache: function(nodeName){
if($.isDOMReady){
tempCache = tempCache || $( document.getElementsByTagName(nodeName) );
}
return tempCache || emptyQ;
},
flushTmpCache: function(){
tempCache = null;
},
content: function(nodeName, prop){
createNodeNameInit(nodeName, function(){
var val = $.attr(this, prop);
if(val != null){
$.attr(this, prop, val);
}
});
},
createElement: function(nodeName, fn){
createNodeNameInit(nodeName, fn);
},
extendValue: function(nodeName, prop, value){
createNodeNameInit(nodeName, function(){
$(this).each(function(){
var data = elementData(this, 'propValue', {});
data[prop] = this[prop];
this[prop] = value;
});
});
}
};
})();
var createPropDefault = function(descs, removeType){
if(descs.defaultValue === undefined){
descs.defaultValue = '';
}
if(!descs.removeAttr){
descs.removeAttr = {
value: function(){
descs[removeType || 'prop'].set.call(this, descs.defaultValue);
descs.removeAttr._supvalue.call(this);
}
};
}
if(!descs.attr){
descs.attr = {};
}
};
$.extend(webshims, {
getID: (function(){
var ID = new Date().getTime();
return function(elem){
elem = $(elem);
var id = elem.prop('id');
if(!id){
ID++;
id = 'ID-'+ ID;
elem.eq(0).prop('id', id);
}
return id;
};
})(),
shadowClass: 'wsshadow-'+(Date.now()),
implement: function(elem, type){
var data = elementData(elem, 'implemented') || elementData(elem, 'implemented', {});
if(data[type]){
webshims.warn(type +' already implemented for element #'+elem.id);
return false;
}
data[type] = true;
return true;
},
extendUNDEFProp: function(obj, props){
$.each(props, function(name, prop){
if( !(name in obj) ){
obj[name] = prop;
}
});
},
getOptions: (function(){
var normalName = /\-([a-z])/g;
var regs = {};
var nameRegs = {};
var regFn = function(f, upper){
return upper.toLowerCase();
};
var nameFn = function(f, dashed){
return dashed.toUpperCase();
};
return function(elem, name, bases, stringAllowed){
if(nameRegs[name]){
name = nameRegs[name];
} else {
nameRegs[name] = name.replace(normalName, nameFn);
name = nameRegs[name];
}
var data = elementData(elem, 'cfg'+name);
var dataName;
var cfg = {};
if(data){
return data;
}
data = $(elem).data();
if(data && typeof data[name] == 'string'){
if(stringAllowed){
return elementData(elem, 'cfg'+name, data[name]);
}
webshims.error('data-'+ name +' attribute has to be a valid JSON, was: '+ data[name]);
}
if(!bases){
bases = [true, {}];
} else if(!Array.isArray(bases)){
bases = [true, {}, bases];
} else {
bases.unshift(true, {});
}
if(data && typeof data[name] == 'object'){
bases.push(data[name]);
}
if(!regs[name]){
regs[name] = new RegExp('^'+ name +'([A-Z])');
}
for(dataName in data){
if(regs[name].test(dataName)){
cfg[dataName.replace(regs[name], regFn)] = data[dataName];
}
}
bases.push(cfg);
return elementData(elem, 'cfg'+name, $.extend.apply($, bases));
};
})(),
//http://www.w3.org/TR/html5/common-dom-interfaces.html#reflect
createPropDefault: createPropDefault,
data: elementData,
moveToFirstEvent: function(elem, eventType, bindType){
var events = ($._data(elem, 'events') || {})[eventType];
var fn;
if(events && events.length > 1){
fn = events.pop();
if(!bindType){
bindType = 'bind';
}
if(bindType == 'bind' && events.delegateCount){
events.splice( events.delegateCount, 0, fn);
} else {
events.unshift( fn );
}
}
elem = null;
},
addShadowDom: (function(){
var resizeTimer;
var lastHeight;
var lastWidth;
var $window = $(window);
var docObserve = {
init: false,
runs: 0,
test: function(){
var height = docObserve.getHeight();
var width = docObserve.getWidth();
if(height != docObserve.height || width != docObserve.width){
docObserve.height = height;
docObserve.width = width;
docObserve.handler({type: 'docresize'});
docObserve.runs++;
if(docObserve.runs < 9){
setTimeout(docObserve.test, 90);
}
} else {
docObserve.runs = 0;
}
},
handler: (function(){
var trigger = function(){
$(document).triggerHandler('updateshadowdom');
};
return function(e){
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function(){
if(e.type == 'resize'){
var width = $window.width();
var height = $window.width();
if(height == lastHeight && width == lastWidth){
return;
}
lastHeight = height;
lastWidth = width;
docObserve.height = docObserve.getHeight();
docObserve.width = docObserve.getWidth();
}
if(window.requestAnimationFrame){
requestAnimationFrame(trigger);
} else {
setTimeout(trigger, 0);
}
}, (e.type == 'resize' && !window.requestAnimationFrame) ? 50 : 9);
};
})(),
_create: function(){
$.each({ Height: "getHeight", Width: "getWidth" }, function(name, type){
var body = document.body;
var doc = document.documentElement;
docObserve[type] = function (){
return Math.max(
body[ "scroll" + name ], doc[ "scroll" + name ],
body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
};
});
},
start: function(){
if(!this.init && document.body){
this.init = true;
this._create();
this.height = docObserve.getHeight();
this.width = docObserve.getWidth();
setInterval(this.test, 999);
$(this.test);
if($.support.boxSizing == null){
$(function(){
if($.support.boxSizing){
docObserve.handler({type: 'boxsizing'});
}
});
}
webshims.ready('WINDOWLOAD', this.test);
$(document).on('updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel', this.handler);
$(window).on('resize', this.handler);
}
}
};
webshims.docObserve = function(){
webshims.ready('DOM', function(){
docObserve.start();
});
};
return function(nativeElem, shadowElem, opts){
if(nativeElem && shadowElem){
opts = opts || {};
if(nativeElem.jquery){
nativeElem = nativeElem[0];
}
if(shadowElem.jquery){
shadowElem = shadowElem[0];
}
var nativeData = $.data(nativeElem, dataID) || $.data(nativeElem, dataID, {});
var shadowData = $.data(shadowElem, dataID) || $.data(shadowElem, dataID, {});
var shadowFocusElementData = {};
if(!opts.shadowFocusElement){
opts.shadowFocusElement = shadowElem;
} else if(opts.shadowFocusElement){
if(opts.shadowFocusElement.jquery){
opts.shadowFocusElement = opts.shadowFocusElement[0];
}
shadowFocusElementData = $.data(opts.shadowFocusElement, dataID) || $.data(opts.shadowFocusElement, dataID, shadowFocusElementData);
}
$(nativeElem).on('remove', function(e){
if (!e.originalEvent) {
setTimeout(function(){
$(shadowElem).remove();
}, 4);
}
});
nativeData.hasShadow = shadowElem;
shadowFocusElementData.nativeElement = shadowData.nativeElement = nativeElem;
shadowFocusElementData.shadowData = shadowData.shadowData = nativeData.shadowData = {
nativeElement: nativeElem,
shadowElement: shadowElem,
shadowFocusElement: opts.shadowFocusElement
};
if(opts.shadowChilds){
opts.shadowChilds.each(function(){
elementData(this, 'shadowData', shadowData.shadowData);
});
}
if(opts.data){
shadowFocusElementData.shadowData.data = shadowData.shadowData.data = nativeData.shadowData.data = opts.data;
}
opts = null;
}
webshims.docObserve();
};
})(),
propTypes: {
standard: function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
descs.attr.set.call(this, ''+val);
},
get: function(){
return descs.attr.get.call(this) || descs.defaultValue;
}
};
},
"boolean": function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
if(val){
descs.attr.set.call(this, "");
} else {
descs.removeAttr.value.call(this);
}
},
get: function(){
return descs.attr.get.call(this) != null;
}
};
},
"src": (function(){
var anchor = document.createElement('a');
anchor.style.display = "none";
return function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
descs.attr.set.call(this, val);
},
get: function(){
var href = this.getAttribute(name);
var ret;
if(href == null){return '';}
anchor.setAttribute('href', href+'' );
if(!supportHrefNormalized){
try {
$(anchor).insertAfter(this);
ret = anchor.getAttribute('href', 4);
} catch(er){
ret = anchor.getAttribute('href', 4);
}
$(anchor).detach();
}
return ret || anchor.href;
}
};
};
})(),
enumarated: function(descs, name){
createPropDefault(descs);
if(descs.prop){return;}
descs.prop = {
set: function(val){
descs.attr.set.call(this, val);
},
get: function(){
var val = (descs.attr.get.call(this) || '').toLowerCase();
if(!val || descs.limitedTo.indexOf(val) == -1){
val = descs.defaultValue;
}
return val;
}
};
}
// ,unsignedLong: $.noop
// ,"doubble": $.noop
// ,"long": $.noop
// ,tokenlist: $.noop
// ,settableTokenlist: $.noop
},
reflectProperties: function(nodeNames, props){
if(typeof props == 'string'){
props = props.split(listReg);
}
props.forEach(function(prop){
webshims.defineNodeNamesProperty(nodeNames, prop, {
prop: {
set: function(val){
$.attr(this, prop, val);
},
get: function(){
return $.attr(this, prop) || '';
}
}
});
});
},
defineNodeNameProperty: function(nodeName, prop, descs){
havePolyfill[prop] = true;
if(descs.reflect){
if(descs.propType && !webshims.propTypes[descs.propType]){
webshims.error('could not finde propType '+ descs.propType);
} else {
webshims.propTypes[descs.propType || 'standard'](descs, prop);
}
}
['prop', 'attr', 'removeAttr'].forEach(function(type){
var desc = descs[type];
if(desc){
if(type === 'prop'){
desc = $.extend({writeable: true}, desc);
} else {
desc = $.extend({}, desc, {writeable: true});
}
extendQ[type](nodeName, prop, desc);
if(nodeName != '*' && webshims.cfg.extendNative && type == 'prop' && desc.value && $.isFunction(desc.value)){
extendNativeValue(nodeName, prop, desc);
}
descs[type] = desc;
}
});
if(descs.initAttr){
initProp.content(nodeName, prop);
}
return descs;
},
defineNodeNameProperties: function(name, descs, propType, _noTmpCache){
var olddesc;
for(var prop in descs){
if(!_noTmpCache && descs[prop].initAttr){
initProp.createTmpCache(name);
}
if(propType){
if(descs[prop][propType]){
//webshims.log('override: '+ name +'['+prop +'] for '+ propType);
} else {
descs[prop][propType] = {};
['value', 'set', 'get'].forEach(function(copyProp){
if(copyProp in descs[prop]){
descs[prop][propType][copyProp] = descs[prop][copyProp];
delete descs[prop][copyProp];
}
});
}
}
descs[prop] = webshims.defineNodeNameProperty(name, prop, descs[prop]);
}
if(!_noTmpCache){
initProp.flushTmpCache();
}
return descs;
},
createElement: function(nodeName, create, descs){
var ret;
if($.isFunction(create)){
create = {
after: create
};
}
initProp.createTmpCache(nodeName);
if(create.before){
initProp.createElement(nodeName, create.before);
}
if(descs){
ret = webshims.defineNodeNameProperties(nodeName, descs, false, true);
}
if(create.after){
initProp.createElement(nodeName, create.after);
}
initProp.flushTmpCache();
return ret;
},
onNodeNamesPropertyModify: function(nodeNames, props, desc, only){
if(typeof nodeNames == 'string'){
nodeNames = nodeNames.split(listReg);
}
if($.isFunction(desc)){
desc = {set: desc};
}
nodeNames.forEach(function(name){
if(!modifyProps[name]){
modifyProps[name] = {};
}
if(typeof props == 'string'){
props = props.split(listReg);
}
if(desc.initAttr){
initProp.createTmpCache(name);
}
props.forEach(function(prop){
if(!modifyProps[name][prop]){
modifyProps[name][prop] = [];
havePolyfill[prop] = true;
}
if(desc.set){
if(only){
desc.set.only = only;
}
modifyProps[name][prop].push(desc.set);
}
if(desc.initAttr){
initProp.content(name, prop);
}
});
initProp.flushTmpCache();
});
},
defineNodeNamesBooleanProperty: function(elementNames, prop, descs){
if(!descs){
descs = {};
}
if($.isFunction(descs)){
descs.set = descs;
}
webshims.defineNodeNamesProperty(elementNames, prop, {
attr: {
set: function(val){
if(descs.useContentAttribute){
webshims.contentAttr(this, prop, val);
} else {
this.setAttribute(prop, val);
}
if(descs.set){
descs.set.call(this, true);
}
},
get: function(){
var ret = (descs.useContentAttribute) ? webshims.contentAttr(this, prop) : this.getAttribute(prop);
return (ret == null) ? undefined : prop;
}
},
removeAttr: {
value: function(){
this.removeAttribute(prop);
if(descs.set){
descs.set.call(this, false);
}
}
},
reflect: true,
propType: 'boolean',
initAttr: descs.initAttr || false
});
},
contentAttr: function(elem, name, val){
if(!elem.nodeName){return;}
var attr;
if(val === undefined){
attr = (elem.attributes[name] || {});
val = attr.specified ? attr.value : null;
return (val == null) ? undefined : val;
}
if(typeof val == 'boolean'){
if(!val){
elem.removeAttribute(name);
} else {
elem.setAttribute(name, name);
}
} else {
elem.setAttribute(name, val);
}
},
activeLang: (function(){
var curLang = [];
var langDatas = [];
var loading = {};
var load = function(src, obj, loadingLang){
obj._isLoading = true;
if(loading[src]){
loading[src].push(obj);
} else {
loading[src] = [obj];
webshims.loader.loadScript(src, function(){
if(loadingLang == curLang.join()){
$.each(loading[src], function(i, obj){
select(obj);
});
}
delete loading[src];
});
}
};
var select = function(obj){
var oldLang = obj.__active;
var selectLang = function(i, lang){
obj._isLoading = false;
if(obj[lang] || obj.availableLangs.indexOf(lang) != -1){
if(obj[lang]){
obj.__active = obj[lang];
obj.__activeName = lang;
} else {
load(obj.langSrc+lang, obj, curLang.join());
}
return false;
}
};
$.each(curLang, selectLang);
if(!obj.__active){
obj.__active = obj[''];
obj.__activeName = '';
}
if(oldLang != obj.__active){
$(obj).trigger('change');
}
};
return function(lang){
var shortLang;
if(typeof lang == 'string'){
if(curLang[0] != lang){
curLang = [lang];
shortLang = curLang[0].split('-')[0];
if(shortLang && shortLang != lang){
curLang.push(shortLang);
}
langDatas.forEach(select);
}
} else if(typeof lang == 'object'){
if(!lang.__active){
langDatas.push(lang);
select(lang);
}
return lang.__active;
}
return curLang[0];
};
})()
});
$.each({
defineNodeNamesProperty: 'defineNodeNameProperty',
defineNodeNamesProperties: 'defineNodeNameProperties',
createElements: 'createElement'
}, function(name, baseMethod){
webshims[name] = function(names, a, b, c){
if(typeof names == 'string'){
names = names.split(listReg);
}
var retDesc = {};
names.forEach(function(nodeName){
retDesc[nodeName] = webshims[baseMethod](nodeName, a, b, c);
});
return retDesc;
};
});
webshims.isReady('webshimLocalization', true);
//html5a11y + hidden attribute
(function(){
if(('content' in document.createElement('template'))){return;}
$(function(){
var main = $('main').attr({role: 'main'});
if(main.length > 1){
webshims.error('only one main element allowed in document');
} else if(main.is('article *, section *')) {
webshims.error('main not allowed inside of article/section elements');
}
});
if(('hidden' in document.createElement('a'))){
return;
}
webshims.defineNodeNamesBooleanProperty(['*'], 'hidden');
var elemMappings = {
article: "article",
aside: "complementary",
section: "region",
nav: "navigation",
address: "contentinfo"
};
var addRole = function(elem, role){
var hasRole = elem.getAttribute('role');
if (!hasRole) {
elem.setAttribute('role', role);
}
};
$.webshims.addReady(function(context, contextElem){
$.each(elemMappings, function(name, role){
var elems = $(name, context).add(contextElem.filter(name));
for (var i = 0, len = elems.length; i < len; i++) {
addRole(elems[i], role);
}
});
if (context === document) {
var header = document.getElementsByTagName('header')[0];
var footers = document.getElementsByTagName('footer');
var footerLen = footers.length;
if (header && !$(header).closest('section, article')[0]) {
addRole(header, 'banner');
}
if (!footerLen) {
return;
}
var footer = footers[footerLen - 1];
if (!$(footer).closest('section, article')[0]) {
addRole(footer, 'contentinfo');
}
}
});
})();
});
;(function(Modernizr, webshims){
"use strict";
var hasNative = Modernizr.audio && Modernizr.video;
var supportsLoop = false;
var bugs = webshims.bugs;
var swfType = 'mediaelement-jaris';
var loadSwf = function(){
webshims.ready(swfType, function(){
if(!webshims.mediaelement.createSWF){
webshims.mediaelement.loadSwf = true;
webshims.reTest([swfType], hasNative);
}
});
};
var wsCfg = webshims.cfg;
var options = wsCfg.mediaelement;
var isIE = navigator.userAgent.indexOf('MSIE') != -1;
if(!options){
webshims.error("mediaelement wasn't implemented but loaded");
return;
}
if(hasNative){
var videoElem = document.createElement('video');
Modernizr.videoBuffered = ('buffered' in videoElem);
Modernizr.mediaDefaultMuted = ('defaultMuted' in videoElem);
supportsLoop = ('loop' in videoElem);
Modernizr.mediaLoop = supportsLoop;
webshims.capturingEvents(['play', 'playing', 'waiting', 'paused', 'ended', 'durationchange', 'loadedmetadata', 'canplay', 'volumechange']);
if( !Modernizr.videoBuffered || !supportsLoop || (!Modernizr.mediaDefaultMuted && isIE && 'ActiveXObject' in window) ){
webshims.addPolyfill('mediaelement-native-fix', {
d: ['dom-support']
});
webshims.loader.loadList(['mediaelement-native-fix']);
}
}
if(Modernizr.track && !bugs.track){
(function(){
if(!bugs.track){
if(window.VTTCue && !window.TextTrackCue){
window.TextTrackCue = window.VTTCue;
} else if(!window.VTTCue){
window.VTTCue = window.TextTrackCue;
}
try {
new VTTCue(2, 3, '');
} catch(e){
bugs.track = true;
}
}
})();
}
webshims.register('mediaelement-core', function($, webshims, window, document, undefined, options){
var hasSwf = swfmini.hasFlashPlayerVersion('10.0.3');
var mediaelement = webshims.mediaelement;
mediaelement.parseRtmp = function(data){
var src = data.src.split('://');
var paths = src[1].split('/');
var i, len, found;
data.server = src[0]+'://'+paths[0]+'/';
data.streamId = [];
for(i = 1, len = paths.length; i < len; i++){
if(!found && paths[i].indexOf(':') !== -1){
paths[i] = paths[i].split(':')[1];
found = true;
}
if(!found){
data.server += paths[i]+'/';
} else {
data.streamId.push(paths[i]);
}
}
if(!data.streamId.length){
webshims.error('Could not parse rtmp url');
}
data.streamId = data.streamId.join('/');
};
var getSrcObj = function(elem, nodeName){
elem = $(elem);
var src = {src: elem.attr('src') || '', elem: elem, srcProp: elem.prop('src')};
var tmp;
if(!src.src){return src;}
tmp = elem.attr('data-server');
if(tmp != null){
src.server = tmp;
}
tmp = elem.attr('type') || elem.attr('data-type');
if(tmp){
src.type = tmp;
src.container = $.trim(tmp.split(';')[0]);
} else {
if(!nodeName){
nodeName = elem[0].nodeName.toLowerCase();
if(nodeName == 'source'){
nodeName = (elem.closest('video, audio')[0] || {nodeName: 'video'}).nodeName.toLowerCase();
}
}
if(src.server){
src.type = nodeName+'/rtmp';
src.container = nodeName+'/rtmp';
} else {
tmp = mediaelement.getTypeForSrc( src.src, nodeName, src );
if(tmp){
src.type = tmp;
src.container = tmp;
}
}
}
tmp = elem.attr('media');
if(tmp){
src.media = tmp;
}
if(src.type == 'audio/rtmp' || src.type == 'video/rtmp'){
if(src.server){
src.streamId = src.src;
} else {
mediaelement.parseRtmp(src);
}
}
return src;
};
var hasYt = !hasSwf && ('postMessage' in window) && hasNative;
var loadTrackUi = function(){
if(loadTrackUi.loaded){return;}
loadTrackUi.loaded = true;
if(!options.noAutoTrack){
webshims.ready('WINDOWLOAD', function(){
loadThird();
webshims.loader.loadList(['track-ui']);
});
}
};
var loadYt = (function(){
var loaded;
return function(){
if(loaded || !hasYt){return;}
loaded = true;
webshims.loader.loadScript("https://www.youtube.com/player_api");
$(function(){
webshims._polyfill(["mediaelement-yt"]);
});
};
})();
var loadThird = function(){
if(hasSwf){
loadSwf();
} else {
loadYt();
}
};
webshims.addPolyfill('mediaelement-yt', {
test: !hasYt,
d: ['dom-support']
});
mediaelement.mimeTypes = {
audio: {
//ogm shouldn´t be used!
'audio/ogg': ['ogg','oga', 'ogm'],
'audio/ogg;codecs="opus"': 'opus',
'audio/mpeg': ['mp2','mp3','mpga','mpega'],
'audio/mp4': ['mp4','mpg4', 'm4r', 'm4a', 'm4p', 'm4b', 'aac'],
'audio/wav': ['wav'],
'audio/3gpp': ['3gp','3gpp'],
'audio/webm': ['webm'],
'audio/fla': ['flv', 'f4a', 'fla'],
'application/x-mpegURL': ['m3u8', 'm3u']
},
video: {
//ogm shouldn´t be used!
'video/ogg': ['ogg','ogv', 'ogm'],
'video/mpeg': ['mpg','mpeg','mpe'],
'video/mp4': ['mp4','mpg4', 'm4v'],
'video/quicktime': ['mov','qt'],
'video/x-msvideo': ['avi'],
'video/x-ms-asf': ['asf', 'asx'],
'video/flv': ['flv', 'f4v'],
'video/3gpp': ['3gp','3gpp'],
'video/webm': ['webm'],
'application/x-mpegURL': ['m3u8', 'm3u'],
'video/MP2T': ['ts']
}
}
;
mediaelement.mimeTypes.source = $.extend({}, mediaelement.mimeTypes.audio, mediaelement.mimeTypes.video);
mediaelement.getTypeForSrc = function(src, nodeName){
if(src.indexOf('youtube.com/watch?') != -1 || src.indexOf('youtube.com/v/') != -1){
return 'video/youtube';
}
if(src.indexOf('rtmp') === 0){
return nodeName+'/rtmp';
}
src = src.split('?')[0].split('#')[0].split('.');
src = src[src.length - 1];
var mt;
$.each(mediaelement.mimeTypes[nodeName], function(mimeType, exts){
if(exts.indexOf(src) !== -1){
mt = mimeType;
return false;
}
});
return mt;
};
mediaelement.srces = function(mediaElem, srces){
mediaElem = $(mediaElem);
if(!srces){
srces = [];
var nodeName = mediaElem[0].nodeName.toLowerCase();
var src = getSrcObj(mediaElem, nodeName);
if(!src.src){
$('source', mediaElem).each(function(){
src = getSrcObj(this, nodeName);
if(src.src){srces.push(src);}
});
} else {
srces.push(src);
}
return srces;
} else {
webshims.error('setting sources was removed.');
}
};
mediaelement.swfMimeTypes = ['video/3gpp', 'video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/aac', 'audio/mp4', 'audio/x-m4a', 'audio/m4a', 'audio/mp3', 'audio/x-fla', 'audio/fla', 'youtube/flv', 'video/jarisplayer', 'jarisplayer/jarisplayer', 'video/youtube', 'video/rtmp', 'audio/rtmp'];
mediaelement.canThirdPlaySrces = function(mediaElem, srces){
var ret = '';
if(hasSwf || hasYt){
mediaElem = $(mediaElem);
srces = srces || mediaelement.srces(mediaElem);
$.each(srces, function(i, src){
if(src.container && src.src && ((hasSwf && mediaelement.swfMimeTypes.indexOf(src.container) != -1) || (hasYt && src.container == 'video/youtube'))){
ret = src;
return false;
}
});
}
return ret;
};
var nativeCanPlayType = {};
mediaelement.canNativePlaySrces = function(mediaElem, srces){
var ret = '';
if(hasNative){
mediaElem = $(mediaElem);
var nodeName = (mediaElem[0].nodeName || '').toLowerCase();
var nativeCanPlay = (nativeCanPlayType[nodeName] || {prop: {_supvalue: false}}).prop._supvalue || mediaElem[0].canPlayType;
if(!nativeCanPlay){return ret;}
srces = srces || mediaelement.srces(mediaElem);
$.each(srces, function(i, src){
if(src.type && nativeCanPlay.call(mediaElem[0], src.type) ){
ret = src;
return false;
}
});
}
return ret;
};
var emptyType = (/^\s*application\/octet\-stream\s*$/i);
var getRemoveEmptyType = function(){
var ret = emptyType.test($.attr(this, 'type') || '');
if(ret){
$(this).removeAttr('type');
}
return ret;
};
mediaelement.setError = function(elem, message){
if($('source', elem).filter(getRemoveEmptyType).length){
webshims.error('"application/octet-stream" is a useless mimetype for audio/video. Please change this attribute.');
try {
$(elem).mediaLoad();
} catch(er){}
} else {
if(!message){
message = "can't play sources";
}
$(elem).pause().data('mediaerror', message);
webshims.error('mediaelementError: '+ message +'. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();');
setTimeout(function(){
if($(elem).data('mediaerror')){
$(elem).addClass('media-error').trigger('mediaerror');
}
}, 1);
}
};
var handleThird = (function(){
var requested;
var readyType = hasSwf ? swfType : 'mediaelement-yt';
return function( mediaElem, ret, data ){
//readd to ready
webshims.ready(readyType, function(){
if(mediaelement.createSWF && $(mediaElem).parent()[0]){
mediaelement.createSWF( mediaElem, ret, data );
} else if(!requested) {
requested = true;
loadThird();
handleThird( mediaElem, ret, data );
}
});
if(!requested && hasYt && !mediaelement.createSWF){
loadYt();
}
};
})();
var activate = {
native: function(elem, src, data){
if(data && data.isActive == 'third') {
mediaelement.setActive(elem, 'html5', data);
}
},
third: handleThird
};
var stepSources = function(elem, data, srces){
var i, src;
var testOrder = [{test: 'canNativePlaySrces', activate: 'native'}, {test: 'canThirdPlaySrces', activate: 'third'}];
if(options.preferFlash || (data && data.isActive == 'third') ){
testOrder.reverse();
}
for(i = 0; i < 2; i++){
src = mediaelement[testOrder[i].test](elem, srces);
if(src){
activate[testOrder[i].activate](elem, src, data);
break;
}
}
if(!src){
mediaelement.setError(elem, false);
if(data && data.isActive == 'third') {
mediaelement.setActive(elem, 'html5', data);
}
}
};
var allowedPreload = {'metadata': 1, 'auto': 1, '': 1};
var fixPreload = function(elem){
var preload, img;
if(elem.getAttribute('preload') == 'none'){
if(allowedPreload[(preload = $.attr(elem, 'data-preload'))]){
$.attr(elem, 'preload', preload);
} else if(hasNative && (preload = elem.getAttribute('poster'))){
img = document.createElement('img');
img.src = preload;
}
}
};
var stopParent = /^(?:embed|object|datalist)$/i;
var selectSource = function(elem, data){
var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {});
var _srces = mediaelement.srces(elem);
var parent = elem.parentNode;
clearTimeout(baseData.loadTimer);
$(elem).removeClass('media-error');
$.data(elem, 'mediaerror', false);
if(!_srces.length || !parent || parent.nodeType != 1 || stopParent.test(parent.nodeName || '')){return;}
data = data || webshims.data(elem, 'mediaelement');
if(mediaelement.sortMedia){
_srces.sort(mediaelement.sortMedia);
}
fixPreload(elem);
stepSources(elem, data, _srces);
};
mediaelement.selectSource = selectSource;
$(document).on('ended', function(e){
var data = webshims.data(e.target, 'mediaelement');
if( supportsLoop && (!data || data.isActive == 'html5') && !$.prop(e.target, 'loop')){return;}
setTimeout(function(){
if( $.prop(e.target, 'paused') || !$.prop(e.target, 'loop') ){return;}
$(e.target).prop('currentTime', 0).play();
});
});
var handleMedia = false;
var initMediaElements = function(){
var testFixMedia = function(){
if(webshims.implement(this, 'mediaelement')){
selectSource(this);
if(!Modernizr.mediaDefaultMuted && $.attr(this, 'muted') != null){
$.prop(this, 'muted', true);
}
}
};
webshims.ready('dom-support', function(){
handleMedia = true;
if(!supportsLoop){
webshims.defineNodeNamesBooleanProperty(['audio', 'video'], 'loop');
}
['audio', 'video'].forEach(function(nodeName){
var supLoad;
supLoad = webshims.defineNodeNameProperty(nodeName, 'load', {
prop: {
value: function(){
var data = webshims.data(this, 'mediaelement');
selectSource(this, data);
if(hasNative && (!data || data.isActive == 'html5') && supLoad.prop._supvalue){
supLoad.prop._supvalue.apply(this, arguments);
}
if(!loadTrackUi.loaded && $('track', this).length){
loadTrackUi();
}
$(this).triggerHandler('wsmediareload');
}
}
});
nativeCanPlayType[nodeName] = webshims.defineNodeNameProperty(nodeName, 'canPlayType', {
prop: {
value: function(type){
var ret = '';
if(hasNative && nativeCanPlayType[nodeName].prop._supvalue){
ret = nativeCanPlayType[nodeName].prop._supvalue.call(this, type);
if(ret == 'no'){
ret = '';
}
}
if(!ret && hasSwf){
type = $.trim((type || '').split(';')[0]);
if(mediaelement.swfMimeTypes.indexOf(type) != -1){
ret = 'maybe';
}
}
if(!ret && hasYt && type == 'video/youtube'){
ret = 'maybe';
}
return ret;
}
}
});
});
webshims.onNodeNamesPropertyModify(['audio', 'video'], ['src', 'poster'], {
set: function(){
var elem = this;
var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {});
clearTimeout(baseData.loadTimer);
baseData.loadTimer = setTimeout(function(){
selectSource(elem);
elem = null;
}, 9);
}
});
webshims.addReady(function(context, insertedElement){
var media = $('video, audio', context)
.add(insertedElement.filter('video, audio'))
.each(testFixMedia)
;
if(!loadTrackUi.loaded && $('track', media).length){
loadTrackUi();
}
media = null;
});
});
if(hasNative && !handleMedia){
webshims.addReady(function(context, insertedElement){
if(!handleMedia){
$('video, audio', context)
.add(insertedElement.filter('video, audio'))
.each(function(){
if(!mediaelement.canNativePlaySrces(this)){
loadThird();
handleMedia = true;
return false;
}
})
;
}
});
}
};
mediaelement.loadDebugger = function(){
webshims.ready('dom-support', function(){
webshims.loader.loadScript('mediaelement-debug');
});
};
if(webshims.cfg.debug){
$(document).on('mediaerror', function(e){
mediaelement.loadDebugger();
});
}
//set native implementation ready, before swf api is retested
if(hasNative){
webshims.isReady('mediaelement-core', true);
initMediaElements();
webshims.ready('WINDOWLOAD mediaelement', loadThird);
} else {
webshims.ready(swfType, initMediaElements);
}
webshims.ready('track', loadTrackUi);
});
})(Modernizr, webshims);
;webshims.register('mediaelement-jaris', function($, webshims, window, document, undefined, options){
"use strict";
var mediaelement = webshims.mediaelement;
var swfmini = window.swfmini;
var hasNative = Modernizr.audio && Modernizr.video;
var hasFlash = swfmini.hasFlashPlayerVersion('9.0.115');
var loadedSwf = 0;
var needsLoadPreload = 'ActiveXObject' in window && hasNative;
var getProps = {
paused: true,
ended: false,
currentSrc: '',
duration: window.NaN,
readyState: 0,
networkState: 0,
videoHeight: 0,
videoWidth: 0,
seeking: false,
error: null,
buffered: {
start: function(index){
if(index){
webshims.error('buffered index size error');
return;
}
return 0;
},
end: function(index){
if(index){
webshims.error('buffered index size error');
return;
}
return 0;
},
length: 0
}
};
var getPropKeys = Object.keys(getProps);
var getSetProps = {
currentTime: 0,
volume: 1,
muted: false
};
var getSetPropKeys = Object.keys(getSetProps);
var playerStateObj = $.extend({
isActive: 'html5',
activating: 'html5',
wasSwfReady: false,
_bufferedEnd: 0,
_bufferedStart: 0,
currentTime: 0,
_ppFlag: undefined,
_calledMeta: false,
lastDuration: 0
}, getProps, getSetProps);
var getSwfDataFromElem = function(elem){
try {
(elem.nodeName);
} catch(er){
return null;
}
var data = webshims.data(elem, 'mediaelement');
return (data && data.isActive== 'third') ? data : null;
};
var trigger = function(elem, evt){
evt = $.Event(evt);
evt.preventDefault();
$.event.trigger(evt, undefined, elem);
};
var playerSwfPath = options.playerPath || webshims.cfg.basePath + "swf/" + (options.playerName || 'JarisFLVPlayer.swf');
webshims.extendUNDEFProp(options.params, {
allowscriptaccess: 'always',
allowfullscreen: 'true',
wmode: 'transparent',
allowNetworking: 'all'
});
webshims.extendUNDEFProp(options.vars, {
controltype: '1',
jsapi: '1'
});
webshims.extendUNDEFProp(options.attrs, {
bgcolor: '#000000'
});
var setReadyState = function(readyState, data){
if(readyState < 3){
clearTimeout(data._canplaythroughTimer);
}
if(readyState >= 3 && data.readyState < 3){
data.readyState = readyState;
trigger(data._elem, 'canplay');
if(!data.paused){
trigger(data._elem, 'playing');
}
clearTimeout(data._canplaythroughTimer);
data._canplaythroughTimer = setTimeout(function(){
setReadyState(4, data);
}, 4000);
}
if(readyState >= 4 && data.readyState < 4){
data.readyState = readyState;
trigger(data._elem, 'canplaythrough');
}
data.readyState = readyState;
};
var callSeeked = function(data){
if(data.seeking && Math.abs(data.currentTime - data._lastSeektime) < 2){
data.seeking = false;
$(data._elem).triggerHandler('seeked');
}
};
mediaelement.jarisEvent = {};
var localConnectionTimer;
var onEvent = {
onPlayPause: function(jaris, data, override){
var playing, type;
if(override == null){
try {
playing = data.api.api_get("isPlaying");
} catch(e){}
} else {
playing = override;
}
if(playing == data.paused){
data.paused = !playing;
type = data.paused ? 'pause' : 'play';
data._ppFlag = true;
trigger(data._elem, type);
if(data.readyState < 3){
setReadyState(3, data);
}
if(!data.paused){
trigger(data._elem, 'playing');
}
}
},
onSeek: function(jaris, data){
data._lastSeektime = jaris.seekTime;
data.seeking = true;
$(data._elem).triggerHandler('seeking');
clearTimeout(data._seekedTimer);
data._seekedTimer = setTimeout(function(){
callSeeked(data);
data.seeking = false;
}, 300);
},
onConnectionFailed: function(jaris, data){
mediaelement.setError(data._elem, 'flash connection error');
},
onNotBuffering: function(jaris, data){
setReadyState(3, data);
},
onDataInitialized: function(jaris, data){
var oldDur = data.duration;
var durDelta;
data.duration = jaris.duration;
if(oldDur == data.duration || isNaN(data.duration)){return;}
if(data._calledMeta && ((durDelta = Math.abs(data.lastDuration - data.duration)) < 2)){return;}
data.videoHeight = jaris.height;
data.videoWidth = jaris.width;
if(!data.networkState){
data.networkState = 2;
}
if(data.readyState < 1){
setReadyState(1, data);
}
clearTimeout(data._durationChangeTimer);
if(data._calledMeta && data.duration){
data._durationChangeTimer = setTimeout(function(){
data.lastDuration = data.duration;
trigger(data._elem, 'durationchange');
}, durDelta > 50 ? 0 : durDelta > 9 ? 9 : 99);
} else {
data.lastDuration = data.duration;
if(data.duration){
trigger(data._elem, 'durationchange');
}
if(!data._calledMeta){
trigger(data._elem, 'loadedmetadata');
}
}
data._calledMeta = true;
},
onBuffering: function(jaris, data){
if(data.ended){
data.ended = false;
}
setReadyState(1, data);
trigger(data._elem, 'waiting');
},
onTimeUpdate: function(jaris, data){
if(data.ended){
data.ended = false;
}
if(data.readyState < 3){
setReadyState(3, data);
trigger(data._elem, 'playing');
}
if(data.seeking){
callSeeked(data);
}
trigger(data._elem, 'timeupdate');
},
onProgress: function(jaris, data){
if(data.ended){
data.ended = false;
}
if(!data.duration || isNaN(data.duration)){
return;
}
var percentage = jaris.loaded / jaris.total;
if(percentage > 0.02 && percentage < 0.2){
setReadyState(3, data);
} else if(percentage > 0.2){
if(percentage > 0.99){
data.networkState = 1;
}
setReadyState(4, data);
}
if(data._bufferedEnd && (data._bufferedEnd > percentage)){
data._bufferedStart = data.currentTime || 0;
}
data._bufferedEnd = percentage;
data.buffered.length = 1;
$.event.trigger('progress', undefined, data._elem, true);
},
onPlaybackFinished: function(jaris, data){
if(data.readyState < 4){
setReadyState(4, data);
}
data.ended = true;
trigger(data._elem, 'ended');
},
onVolumeChange: function(jaris, data){
if(data.volume != jaris.volume || data.muted != jaris.mute){
data.volume = jaris.volume;
data.muted = jaris.mute;
trigger(data._elem, 'volumechange');
}
},
ready: (function(){
var testAPI = function(data){
var passed = true;
try {
data.api.api_get('volume');
} catch(er){
passed = false;
}
return passed;
};
return function(jaris, data){
var i = 0;
var doneFn = function(){
if(i > 9){
data.tryedReframeing = 0;
return;
}
i++;
data.tryedReframeing++;
if(testAPI(data)){
data.wasSwfReady = true;
data.tryedReframeing = 0;
startAutoPlay(data);
workActionQueue(data);
} else if(data.tryedReframeing < 6) {
if(data.tryedReframeing < 3){
data.reframeTimer = setTimeout(doneFn, 9);
data.shadowElem.css({overflow: 'visible'});
setTimeout(function(){
data.shadowElem.css({overflow: 'hidden'});
}, 1);
} else {
data.shadowElem.css({overflow: 'hidden'});
$(data._elem).mediaLoad();
}
} else {
clearTimeout(data.reframeTimer);
webshims.error("reframing error");
}
};
if(!data || !data.api){return;}
if(!data.tryedReframeing){
data.tryedReframeing = 0;
}
clearTimeout(localConnectionTimer);
clearTimeout(data.reframeTimer);
data.shadowElem.removeClass('flashblocker-assumed');
if(!i){
doneFn();
} else {
data.reframeTimer = setTimeout(doneFn, 9);
}
};
})()
};
onEvent.onMute = onEvent.onVolumeChange;
var workActionQueue = function(data){
var actionLen = data.actionQueue.length;
var i = 0;
var operation;
if(actionLen && data.isActive == 'third'){
while(data.actionQueue.length && actionLen > i){
i++;
operation = data.actionQueue.shift();
try{
data.api[operation.fn].apply(data.api, operation.args);
} catch(er){
webshims.warn(er);
}
}
}
if(data.actionQueue.length){
data.actionQueue = [];
}
};
var startAutoPlay = function(data){
if(!data){return;}
if( (data._ppFlag === undefined && ($.prop(data._elem, 'autoplay')) || !data.paused)){
setTimeout(function(){
if(data.isActive == 'third' && (data._ppFlag === undefined || !data.paused)){
try {
$(data._elem).play();
data._ppFlag = true;
} catch(er){}
}
}, 1);
}
if(data.muted){
$.prop(data._elem, 'muted', true);
}
if(data.volume != 1){
$.prop(data._elem, 'volume', data.volume);
}
};
var addMediaToStopEvents = $.noop;
if(hasNative){
var stopEvents = {
play: 1,
playing: 1
};
var hideEvtArray = ['play', 'pause', 'playing', 'canplay', 'progress', 'waiting', 'ended', 'loadedmetadata', 'durationchange', 'emptied'];
var hidevents = hideEvtArray.map(function(evt){
return evt +'.webshimspolyfill';
}).join(' ');
var hidePlayerEvents = function(event){
var data = webshims.data(event.target, 'mediaelement');
if(!data){return;}
var isNativeHTML5 = ( event.originalEvent && event.originalEvent.type === event.type );
if( isNativeHTML5 == (data.activating == 'third') ){
event.stopImmediatePropagation();
if(stopEvents[event.type]){
if(data.isActive != data.activating){
$(event.target).pause();
} else if(isNativeHTML5){
($.prop(event.target, 'pause')._supvalue || $.noop).apply(event.target);
}
}
}
};
addMediaToStopEvents = function(elem){
$(elem)
.off(hidevents)
.on(hidevents, hidePlayerEvents)
;
hideEvtArray.forEach(function(evt){
webshims.moveToFirstEvent(elem, evt);
});
};
addMediaToStopEvents(document);
}
mediaelement.setActive = function(elem, type, data){
if(!data){
data = webshims.data(elem, 'mediaelement');
}
if(!data || data.isActive == type){return;}
if(type != 'html5' && type != 'third'){
webshims.warn('wrong type for mediaelement activating: '+ type);
}
var shadowData = webshims.data(elem, 'shadowData');
data.activating = type;
$(elem).pause();
data.isActive = type;
if(type == 'third'){
shadowData.shadowElement = shadowData.shadowFocusElement = data.shadowElem[0];
$(elem).addClass('swf-api-active nonnative-api-active').hide().getShadowElement().show();
} else {
$(elem).removeClass('swf-api-active nonnative-api-active').show().getShadowElement().hide();
shadowData.shadowElement = shadowData.shadowFocusElement = false;
}
$(elem).trigger('mediaelementapichange');
};
var resetSwfProps = (function(){
var resetProtoProps = ['_calledMeta', 'lastDuration', '_bufferedEnd', '_bufferedStart', '_ppFlag', 'currentSrc', 'currentTime', 'duration', 'ended', 'networkState', 'paused', 'seeking', 'videoHeight', 'videoWidth'];
var len = resetProtoProps.length;
return function(data){
if(!data){return;}
clearTimeout(data._seekedTimer);
var lenI = len;
var networkState = data.networkState;
setReadyState(0, data);
clearTimeout(data._durationChangeTimer);
while(--lenI > -1){
delete data[resetProtoProps[lenI]];
}
data.actionQueue = [];
data.buffered.length = 0;
if(networkState){
trigger(data._elem, 'emptied');
}
};
})();
var getComputedDimension = (function(){
var dimCache = {};
var getVideoDims = function(data){
var ret, poster, img;
if(dimCache[data.currentSrc]){
ret = dimCache[data.currentSrc];
} else if(data.videoHeight && data.videoWidth){
dimCache[data.currentSrc] = {
width: data.videoWidth,
height: data.videoHeight
};
ret = dimCache[data.currentSrc];
} else if((poster = $.attr(data._elem, 'poster'))){
ret = dimCache[poster];
if(!ret){
img = document.createElement('img');
img.onload = function(){
dimCache[poster] = {
width: this.width,
height: this.height
};
if(dimCache[poster].height && dimCache[poster].width){
setElementDimension(data, $.prop(data._elem, 'controls'));
} else {
delete dimCache[poster];
}
img.onload = null;
};
img.src = poster;
if(img.complete && img.onload){
img.onload();
}
}
}
return ret || {width: 300, height: data._elemNodeName == 'video' ? 150 : 50};
};
var getCssStyle = function(elem, style){
return elem.style[style] || (elem.currentStyle && elem.currentStyle[style]) || (window.getComputedStyle && (window.getComputedStyle( elem, null ) || {} )[style]) || '';
};
var minMaxProps = ['minWidth', 'maxWidth', 'minHeight', 'maxHeight'];
var addMinMax = function(elem, ret){
var i, prop;
var hasMinMax = false;
for (i = 0; i < 4; i++) {
prop = getCssStyle(elem, minMaxProps[i]);
if(parseFloat(prop, 10)){
hasMinMax = true;
ret[minMaxProps[i]] = prop;
}
}
return hasMinMax;
};
var retFn = function(data){
var videoDims, ratio, hasMinMax;
var elem = data._elem;
var autos = {
width: getCssStyle(elem, 'width') == 'auto',
height: getCssStyle(elem, 'height') == 'auto'
};
var ret = {
width: !autos.width && $(elem).width(),
height: !autos.height && $(elem).height()
};
if(autos.width || autos.height){
videoDims = getVideoDims(data);
ratio = videoDims.width / videoDims.height;
if(autos.width && autos.height){
ret.width = videoDims.width;
ret.height = videoDims.height;
} else if(autos.width){
ret.width = ret.height * ratio;
} else if(autos.height){
ret.height = ret.width / ratio;
}
if(addMinMax(elem, ret)){
data.shadowElem.css(ret);
if(autos.width){
ret.width = data.shadowElem.height() * ratio;
}
if(autos.height){
ret.height = ((autos.width) ? ret.width : data.shadowElem.width()) / ratio;
}
if(autos.width && autos.height){
data.shadowElem.css(ret);
ret.height = data.shadowElem.width() / ratio;
ret.width = ret.height * ratio;
data.shadowElem.css(ret);
ret.width = data.shadowElem.height() * ratio;
ret.height = ret.width / ratio;
}
if(!Modernizr.video){
ret.width = data.shadowElem.width();
ret.height = data.shadowElem.height();
}
}
}
return ret;
};
return retFn;
})();
var setElementDimension = function(data, hasControls){
var dims;
var box = data.shadowElem;
$(data._elem)[hasControls ? 'addClass' : 'removeClass']('webshims-controls');
if(data.isActive == 'third' || data.activating == 'third'){
if(data._elemNodeName == 'audio' && !hasControls){
box.css({width: 0, height: 0});
} else {
data._elem.style.display = '';
dims = getComputedDimension(data);
data._elem.style.display = 'none';
box.css(dims);
}
}
};
var bufferSrc = (function(){
var preloads = {
'': 1,
'auto': 1
};
return function(elem){
var preload = $.attr(elem, 'preload');
if(preload == null || preload == 'none' || $.prop(elem, 'autoplay')){
return false;
}
preload = $.prop(elem, 'preload');
return !!(preloads[preload] || (preload == 'metadata' && $(elem).is('.preload-in-doubt, video:not([poster])')));
};
})();
var regs = {
A: /&/g,
a: /&/g,
e: /\=/g,
q: /\?/g
},
replaceVar = function(val){
return (val.replace) ? val.replace(regs.A, '%26').replace(regs.a, '%26').replace(regs.e, '%3D').replace(regs.q, '%3F') : val;
};
if('matchMedia' in window){
var allowMediaSorting = false;
try {
allowMediaSorting = window.matchMedia('only all').matches;
} catch(er){}
if(allowMediaSorting){
mediaelement.sortMedia = function(src1, src2){
try {
src1 = !src1.media || matchMedia( src1.media ).matches;
src2 = !src2.media || matchMedia( src2.media ).matches;
} catch(er){
return 0;
}
return src1 == src2 ?
0 :
src1 ? -1
: 1;
};
}
}
mediaelement.createSWF = function( elem, canPlaySrc, data ){
if(!hasFlash){
setTimeout(function(){
$(elem).mediaLoad(); //<- this should produce a mediaerror
}, 1);
return;
}
var attrStyle = {};
if(loadedSwf < 1){
loadedSwf = 1;
} else {
loadedSwf++;
}
if(!data){
data = webshims.data(elem, 'mediaelement');
}
if((attrStyle.height = $.attr(elem, 'height') || '') || (attrStyle.width = $.attr(elem, 'width') || '')){
$(elem).css(attrStyle);
webshims.warn("width or height content attributes used. Webshims prefers the usage of CSS (computed styles or inline styles) to detect size of a video/audio. It's really more powerfull.");
}
var isRtmp = canPlaySrc.type == 'audio/rtmp' || canPlaySrc.type == 'video/rtmp';
var vars = $.extend({}, options.vars, {
poster: replaceVar($.attr(elem, 'poster') && $.prop(elem, 'poster') || ''),
source: replaceVar(canPlaySrc.streamId || canPlaySrc.srcProp),
server: replaceVar(canPlaySrc.server || '')
});
var elemVars = $(elem).data('vars') || {};
var hasControls = $.prop(elem, 'controls');
var elemId = 'jarisplayer-'+ webshims.getID(elem);
var params = $.extend(
{},
options.params,
$(elem).data('params')
);
var elemNodeName = elem.nodeName.toLowerCase();
var attrs = $.extend(
{},
options.attrs,
{
name: elemId,
id: elemId
},
$(elem).data('attrs')
);
var setDimension = function(){
if(data.isActive == 'third'){
setElementDimension(data, $.prop(elem, 'controls'));
}
};
var box;
if(data && data.swfCreated){
mediaelement.setActive(elem, 'third', data);
data.currentSrc = canPlaySrc.srcProp;
data.shadowElem.html('<div id="'+ elemId +'">');
data.api = false;
data.actionQueue = [];
box = data.shadowElem;
resetSwfProps(data);
} else {
$(document.getElementById('wrapper-'+ elemId )).remove();
box = $('<div class="polyfill-'+ (elemNodeName) +' polyfill-mediaelement '+ webshims.shadowClass +'" id="wrapper-'+ elemId +'"><div id="'+ elemId +'"></div>')
.css({
position: 'relative',
overflow: 'hidden'
})
;
data = webshims.data(elem, 'mediaelement', webshims.objectCreate(playerStateObj, {
actionQueue: {
value: []
},
shadowElem: {
value: box
},
_elemNodeName: {
value: elemNodeName
},
_elem: {
value: elem
},
currentSrc: {
value: canPlaySrc.srcProp
},
swfCreated: {
value: true
},
id: {
value: elemId.replace(/-/g, '')
},
buffered: {
value: {
start: function(index){
if(index >= data.buffered.length){
webshims.error('buffered index size error');
return;
}
return 0;
},
end: function(index){
if(index >= data.buffered.length){
webshims.error('buffered index size error');
return;
}
return ( (data.duration - data._bufferedStart) * data._bufferedEnd) + data._bufferedStart;
},
length: 0
}
}
}));
box.insertBefore(elem);
if(hasNative){
$.extend(data, {volume: $.prop(elem, 'volume'), muted: $.prop(elem, 'muted'), paused: $.prop(elem, 'paused')});
}
webshims.addShadowDom(elem, box);
if(!webshims.data(elem, 'mediaelement')){
webshims.data(elem, 'mediaelement', data);
}
addMediaToStopEvents(elem);
mediaelement.setActive(elem, 'third', data);
setElementDimension(data, hasControls);
$(elem)
.on({
'updatemediaelementdimensions loadedmetadata emptied': setDimension,
'remove': function(e){
if(!e.originalEvent && mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem == elem){
delete mediaelement.jarisEvent[data.id];
clearTimeout(localConnectionTimer);
clearTimeout(data.flashBlock);
}
}
})
.onWSOff('updateshadowdom', setDimension)
;
}
if(mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem != elem){
webshims.error('something went wrong');
return;
} else if(!mediaelement.jarisEvent[data.id]){
mediaelement.jarisEvent[data.id] = function(jaris){
if(jaris.type == 'ready'){
var onReady = function(){
if(data.api){
if(!data.paused){
data.api.api_play();
}
if(bufferSrc(elem)){
data.api.api_preload();
}
onEvent.ready(jaris, data);
}
};
if(data.api){
onReady();
} else {
setTimeout(onReady, 9);
}
} else {
data.currentTime = jaris.position;
if(data.api){
if(!data._calledMeta && isNaN(jaris.duration) && data.duration != jaris.duration && isNaN(data.duration)){
onEvent.onDataInitialized(jaris, data);
}
if(!data._ppFlag && jaris.type != 'onPlayPause'){
onEvent.onPlayPause(jaris, data);
}
if(onEvent[jaris.type]){
onEvent[jaris.type](jaris, data);
}
}
data.duration = jaris.duration;
}
};
mediaelement.jarisEvent[data.id].elem = elem;
}
$.extend(vars,
{
id: elemId,
evtId: data.id,
controls: ''+hasControls,
autostart: 'false',
nodename: elemNodeName
},
elemVars
);
if(isRtmp){
vars.streamtype = 'rtmp';
} else if(canPlaySrc.type == 'audio/mpeg' || canPlaySrc.type == 'audio/mp3'){
vars.type = 'audio';
vars.streamtype = 'file';
} else if(canPlaySrc.type == 'video/youtube'){
vars.streamtype = 'youtube';
}
options.changeSWF(vars, elem, canPlaySrc, data, 'embed');
clearTimeout(data.flashBlock);
swfmini.embedSWF(playerSwfPath, elemId, "100%", "100%", "9.0.115", false, vars, params, attrs, function(swfData){
if(swfData.success){
var fBlocker = function(){
if((!swfData.ref.parentNode && box[0].parentNode) || swfData.ref.style.display == "none"){
box.addClass('flashblocker-assumed');
$(elem).trigger('flashblocker');
webshims.warn("flashblocker assumed");
}
$(swfData.ref).css({'minHeight': '2px', 'minWidth': '2px', display: 'block'});
};
data.api = swfData.ref;
if(!hasControls){
$(swfData.ref).attr('tabindex', '-1').css('outline', 'none');
}
data.flashBlock = setTimeout(fBlocker, 99);
if(!localConnectionTimer){
clearTimeout(localConnectionTimer);
localConnectionTimer = setTimeout(function(){
fBlocker();
var flash = $(swfData.ref);
if(flash[0].offsetWidth > 1 && flash[0].offsetHeight > 1 && location.protocol.indexOf('file:') === 0){
webshims.error("Add your local development-directory to the local-trusted security sandbox: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html");
} else if(flash[0].offsetWidth < 2 || flash[0].offsetHeight < 2) {
webshims.warn("JS-SWF connection can't be established on hidden or unconnected flash objects");
}
flash = null;
}, 8000);
}
}
});
};
var queueSwfMethod = function(elem, fn, args, data){
data = data || getSwfDataFromElem(elem);
if(data){
if(data.api && data.api[fn]){
data.api[fn].apply(data.api, args || []);
} else {
//todo add to queue
data.actionQueue.push({fn: fn, args: args});
if(data.actionQueue.length > 10){
setTimeout(function(){
if(data.actionQueue.length > 5){
data.actionQueue.shift();
}
}, 99);
}
}
return data;
}
return false;
};
['audio', 'video'].forEach(function(nodeName){
var descs = {};
var mediaSup;
var createGetProp = function(key){
if(nodeName == 'audio' && (key == 'videoHeight' || key == 'videoWidth')){return;}
descs[key] = {
get: function(){
var data = getSwfDataFromElem(this);
if(data){
return data[key];
} else if(hasNative && mediaSup[key].prop._supget) {
return mediaSup[key].prop._supget.apply(this);
} else {
return playerStateObj[key];
}
},
writeable: false
};
};
var createGetSetProp = function(key, setFn){
createGetProp(key);
delete descs[key].writeable;
descs[key].set = setFn;
};
createGetSetProp('seeking');
createGetSetProp('volume', function(v){
var data = getSwfDataFromElem(this);
if(data){
v *= 1;
if(!isNaN(v)){
if(v < 0 || v > 1){
webshims.error('volume greater or less than allowed '+ (v / 100));
}
queueSwfMethod(this, 'api_volume', [v], data);
if(data.volume != v){
data.volume = v;
trigger(data._elem, 'volumechange');
}
data = null;
}
} else if(mediaSup.volume.prop._supset) {
return mediaSup.volume.prop._supset.apply(this, arguments);
}
});
createGetSetProp('muted', function(m){
var data = getSwfDataFromElem(this);
if(data){
m = !!m;
queueSwfMethod(this, 'api_muted', [m], data);
if(data.muted != m){
data.muted = m;
trigger(data._elem, 'volumechange');
}
data = null;
} else if(mediaSup.muted.prop._supset) {
return mediaSup.muted.prop._supset.apply(this, arguments);
}
});
createGetSetProp('currentTime', function(t){
var data = getSwfDataFromElem(this);
if(data){
t *= 1;
if (!isNaN(t)) {
queueSwfMethod(this, 'api_seek', [t], data);
}
} else if(mediaSup.currentTime.prop._supset) {
return mediaSup.currentTime.prop._supset.apply(this, arguments);
}
});
['play', 'pause'].forEach(function(fn){
descs[fn] = {
value: function(){
var data = getSwfDataFromElem(this);
if(data){
if(data.stopPlayPause){
clearTimeout(data.stopPlayPause);
}
queueSwfMethod(this, fn == 'play' ? 'api_play' : 'api_pause', [], data);
data._ppFlag = true;
if(data.paused != (fn != 'play')){
data.paused = fn != 'play';
trigger(data._elem, fn);
}
} else if(mediaSup[fn].prop._supvalue) {
return mediaSup[fn].prop._supvalue.apply(this, arguments);
}
}
};
});
getPropKeys.forEach(createGetProp);
webshims.onNodeNamesPropertyModify(nodeName, 'controls', function(val, boolProp){
var data = getSwfDataFromElem(this);
$(this)[boolProp ? 'addClass' : 'removeClass']('webshims-controls');
if(data){
if(nodeName == 'audio'){
setElementDimension(data, boolProp);
}
queueSwfMethod(this, 'api_controls', [boolProp], data);
}
});
webshims.onNodeNamesPropertyModify(nodeName, 'preload', function(val){
var data, baseData, elem;
if(bufferSrc(this)){
data = getSwfDataFromElem(this);
if(data){
queueSwfMethod(this, 'api_preload', [], data);
} else if(needsLoadPreload && this.paused && !this.error && !$.data(this, 'mediaerror') && !this.readyState && !this.networkState && !this.autoplay && $(this).is(':not(.nonnative-api-active)')){
elem = this;
baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {});
clearTimeout(baseData.loadTimer);
baseData.loadTimer = setTimeout(function(){
$(elem).mediaLoad();
}, 9);
}
}
});
mediaSup = webshims.defineNodeNameProperties(nodeName, descs, 'prop');
if(!Modernizr.mediaDefaultMuted){
webshims.defineNodeNameProperties(nodeName, {
defaultMuted: {
get: function(){
return $.attr(this, 'muted') != null;
},
set: function(val){
if(val){
$.attr(this, 'muted', '');
} else {
$(this).removeAttr('muted');
}
}
}
}, 'prop');
}
});
if(hasFlash && $.cleanData){
var oldClean = $.cleanData;
var flashNames = {
object: 1,
OBJECT: 1
};
$.cleanData = function(elems){
var i, len, prop;
if(elems && (len = elems.length) && loadedSwf){
for(i = 0; i < len; i++){
if(flashNames[elems[i].nodeName] && 'api_pause' in elems[i]){
loadedSwf--;
try {
elems[i].api_pause();
if(elems[i].readyState == 4){
for (prop in elems[i]) {
if (typeof elems[i][prop] == "function") {
elems[i][prop] = null;
}
}
}
} catch(er){}
}
}
}
return oldClean.apply(this, arguments);
};
}
if(!hasNative){
['poster', 'src'].forEach(function(prop){
webshims.defineNodeNamesProperty(prop == 'src' ? ['audio', 'video', 'source'] : ['video'], prop, {
//attr: {},
reflect: true,
propType: 'src'
});
});
webshims.defineNodeNamesProperty(['audio', 'video'], 'preload', {
reflect: true,
propType: 'enumarated',
defaultValue: '',
limitedTo: ['', 'auto', 'metadata', 'none']
});
webshims.reflectProperties('source', ['type', 'media']);
['autoplay', 'controls'].forEach(function(name){
webshims.defineNodeNamesBooleanProperty(['audio', 'video'], name);
});
webshims.defineNodeNamesProperties(['audio', 'video'], {
HAVE_CURRENT_DATA: {
value: 2
},
HAVE_ENOUGH_DATA: {
value: 4
},
HAVE_FUTURE_DATA: {
value: 3
},
HAVE_METADATA: {
value: 1
},
HAVE_NOTHING: {
value: 0
},
NETWORK_EMPTY: {
value: 0
},
NETWORK_IDLE: {
value: 1
},
NETWORK_LOADING: {
value: 2
},
NETWORK_NO_SOURCE: {
value: 3
}
}, 'prop');
if(hasFlash){
webshims.ready('WINDOWLOAD', function(){
setTimeout(function(){
if(!loadedSwf){
document.createElement('img').src = playerSwfPath;
}
}, 9);
});
}
} else if(!('media' in document.createElement('source'))){
webshims.reflectProperties('source', ['media']);
}
if(hasNative && hasFlash && !options.preferFlash){
var switchErrors = {
3: 1,
4: 1
};
var switchOptions = function(e){
var media, error, parent;
if(
($(e.target).is('audio, video') || ((parent = e.target.parentNode) && $('source', parent).last()[0] == e.target)) &&
(media = $(e.target).closest('audio, video') && !media.is('.nonnative-api-active'))
){
error = media.prop('error');
setTimeout(function(){
if(!media.is('.nonnative-api-active')){
if(error && switchErrors[error.code]){
options.preferFlash = true;
document.removeEventListener('error', switchOptions, true);
$('audio, video').each(function(){
webshims.mediaelement.selectSource(this);
});
webshims.error("switching mediaelements option to 'preferFlash', due to an error with native player: "+e.target.src+" Mediaerror: "+ media.prop('error')+ 'first error: '+ error);
}
webshims.warn('There was a mediaelement error. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();')
}
});
}
};
document.addEventListener('error', switchOptions, true);
setTimeout(function(){
$('audio, video').each(function(){
var error = $.prop(this, 'error');
if(error && switchErrors[error]){
switchOptions({target: this});
}
});
});
}
});
| BobbieBel/cdnjs | ajax/libs/webshim/1.14.3-RC1/dev/shims/combos/19.js | JavaScript | mit | 131,635 |
'use strict';
import React, { Component } from 'react';
import {
ActivityIndicator,
Image,
ListView,
Platform,
StyleSheet,
View,
} from 'react-native';
import ListItem from '../../components/ListItem';
import Backend from '../../lib/Backend';
export default class ChatListScreen extends Component {
static navigationOptions = {
title: 'Chats',
header: {
visible: Platform.OS === 'ios',
},
tabBar: {
icon: ({ tintColor }) => (
<Image
// Using react-native-vector-icons works here too
source={require('./chat-icon.png')}
style={[styles.icon, {tintColor: tintColor}]}
/>
),
},
}
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
isLoading: true,
dataSource: ds,
};
}
async componentDidMount() {
const chatList = await Backend.fetchChatList();
this.setState((prevState) => ({
dataSource: prevState.dataSource.cloneWithRows(chatList),
isLoading: false,
}));
}
// Binding the function so it can be passed to ListView below
// and 'this' works properly inside renderRow
renderRow = (name) => {
return (
<ListItem
label={name}
onPress={() => {
// Start fetching in parallel with animating
this.props.navigation.navigate('Chat', {
name: name,
});
}}
/>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.loadingScreen}>
<ActivityIndicator />
</View>
);
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
);
}
}
const styles = StyleSheet.create({
loadingScreen: {
backgroundColor: 'white',
paddingTop: 8,
flex: 1,
},
listView: {
backgroundColor: 'white',
},
icon: {
width: 30,
height: 26,
},
});
| prayuditb/tryout-01 | websocket/client/Client/node_modules/react-native/local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js | JavaScript | mit | 2,035 |
/**
* File skip-link-focus-fix.js.
*
* Helps with accessibility for keyboard only users.
*
* This is the source file for what is minified in the twentynineteen_skip_link_focus_fix() PHP function.
*
* Learn more: https://git.io/vWdr2
*/
( function() {
var isIe = /(trident|msie)/i.test( navigator.userAgent );
if ( isIe && document.getElementById && window.addEventListener ) {
window.addEventListener( 'hashchange', function() {
var id = location.hash.substring( 1 ),
element;
if ( ! ( /^[A-z0-9_-]+$/.test( id ) ) ) {
return;
}
element = document.getElementById( id );
if ( element ) {
if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) {
element.tabIndex = -1;
}
element.focus();
}
}, false );
}
} )();
| TheThumbsupguy/Ross-Upholstery-Inc | wp-content/themes/twentynineteen/js/skip-link-focus-fix.js | JavaScript | gpl-2.0 | 794 |
REM Copyright (C) 2006, 2007 MySQL AB
REM
REM This program is free software; you can redistribute it and/or modify
REM it under the terms of the GNU General Public License as published by
REM the Free Software Foundation; version 2 of the License.
REM
REM This program is distributed in the hope that it will be useful,
REM but WITHOUT ANY WARRANTY; without even the implied warranty of
REM MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
REM GNU General Public License for more details.
REM
REM You should have received a copy of the GNU General Public License
REM along with this program; if not, write to the Free Software
REM Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
REM quick and dirty build file for testing different MSDEVs
setlocal
set myFLAGS= /I../include /I../taocrypt/mySTL /I../taocrypt/include /W3 /c /ZI
cl %myFLAGS% buffer.cpp
cl %myFLAGS% cert_wrapper.cpp
cl %myFLAGS% crypto_wrapper.cpp
cl %myFLAGS% handshake.cpp
cl %myFLAGS% lock.cpp
cl %myFLAGS% log.cpp
cl %myFLAGS% socket_wrapper.cpp
cl %myFLAGS% ssl.cpp
cl %myFLAGS% template_instnt.cpp
cl %myFLAGS% timer.cpp
cl %myFLAGS% yassl.cpp
cl %myFLAGS% yassl_error.cpp
cl %myFLAGS% yassl_imp.cpp
cl %myFLAGS% yassl_int.cpp
link.exe -lib /out:yassl.lib buffer.obj cert_wrapper.obj crypto_wrapper.obj handshake.obj lock.obj log.obj socket_wrapper.obj ssl.obj template_instnt.obj timer.obj yassl.obj yassl_error.obj yassl_imp.obj yassl_int.obj
| metacloud/percona-xtrabackup | percona-server-5.5-xtrabackup/Percona-Server-5.5/extra/yassl/src/make.bat | Batchfile | gpl-2.0 | 1,469 |
<!---
This README is automatically generated from the comments in these files:
paper-menu-button-animations.html paper-menu-button.html
Edit those files, and our readme bot will duplicate them over here!
Edit this file, and the bot will squash your changes :)
-->
[](https://travis-ci.org/PolymerElements/paper-menu-button)
_[Demo and API Docs](https://elements.polymer-project.org/elements/paper-menu-button)_
##<paper-menu-button>
Material design: [Dropdown buttons](https://www.google.com/design/spec/components/buttons.html#buttons-dropdown-buttons)
`paper-menu-button` allows one to compose a designated "trigger" element with
another element that represents "content", to create a dropdown menu that
displays the "content" when the "trigger" is clicked.
The child element with the class `dropdown-trigger` will be used as the
"trigger" element. The child element with the class `dropdown-content` will be
used as the "content" element.
The `paper-menu-button` is sensitive to its content's `iron-select` events. If
the "content" element triggers an `iron-select` event, the `paper-menu-button`
will close automatically.
Example:
<paper-menu-button>
<paper-icon-button icon="menu" class="dropdown-trigger"></paper-icon-button>
<paper-menu class="dropdown-content">
<paper-item>Share</paper-item>
<paper-item>Settings</paper-item>
<paper-item>Help</paper-item>
</paper-menu>
</paper-menu-button>
### Styling
The following custom properties and mixins are also available for styling:
Custom property | Description | Default
----------------|-------------|----------
`--paper-menu-button-dropdown-background` | Background color of the paper-menu-button dropdown | `#fff`
`--paper-menu-button` | Mixin applied to the paper-menu-button | `{}`
`--paper-menu-button-disabled` | Mixin applied to the paper-menu-button when disabled | `{}`
`--paper-menu-button-dropdown` | Mixin applied to the paper-menu-button dropdown | `{}`
`--paper-menu-button-content` | Mixin applied to the paper-menu-button content | `{}`
<!-- No docs for <paper-menu-grow-height-animation> found. -->
<!-- No docs for <paper-menu-grow-width-animation> found. -->
<!-- No docs for <paper-menu-shrink-height-animation> found. -->
<!-- No docs for <paper-menu-shrink-width-animation> found. -->
| SimoRihani/PFA-Qucit | www/bower_components/paper-menu-button/README.md | Markdown | lgpl-3.0 | 2,435 |
/**
* Module dependencies.
*/
var debug = require('debug')('send')
, parseRange = require('range-parser')
, Stream = require('stream')
, mime = require('mime')
, fresh = require('fresh')
, path = require('path')
, http = require('http')
, fs = require('fs')
, basename = path.basename
, normalize = path.normalize
, join = path.join
, utils = require('./utils');
/**
* Expose `send`.
*/
exports = module.exports = send;
/**
* Expose mime module.
*/
exports.mime = mime;
/**
* Return a `SendStream` for `req` and `path`.
*
* @param {Request} req
* @param {String} path
* @return {SendStream}
* @api public
*/
function send(req, path) {
return new SendStream(req, path);
}
/**
* Initialize a `SendStream` with the given `path`.
*
* Events:
*
* - `error` an error occurred
* - `stream` file streaming has started
* - `end` streaming has completed
* - `directory` a directory was requested
*
* @param {Request} req
* @param {String} path
* @api private
*/
function SendStream(req, path) {
var self = this;
this.req = req;
this.path = path;
this.maxage(0);
this.hidden(false);
this.index('index.html');
}
/**
* Inherits from `Stream.prototype`.
*/
SendStream.prototype.__proto__ = Stream.prototype;
/**
* Enable or disable "hidden" (dot) files.
*
* @param {Boolean} path
* @return {SendStream}
* @api public
*/
SendStream.prototype.hidden = function(val){
debug('hidden %s', val);
this._hidden = val;
return this;
};
/**
* Set index `path`, set to a falsy
* value to disable index support.
*
* @param {String|Boolean} path
* @return {SendStream}
* @api public
*/
SendStream.prototype.index = function(path){
debug('index %s', path);
this._index = path;
return this;
};
/**
* Set root `path`.
*
* @param {String} path
* @return {SendStream}
* @api public
*/
SendStream.prototype.root =
SendStream.prototype.from = function(path){
this._root = normalize(path);
return this;
};
/**
* Set max-age to `ms`.
*
* @param {Number} ms
* @return {SendStream}
* @api public
*/
SendStream.prototype.maxage = function(ms){
if (Infinity == ms) ms = 60 * 60 * 24 * 365 * 1000;
debug('max-age %d', ms);
this._maxage = ms;
return this;
};
/**
* Emit error with `status`.
*
* @param {Number} status
* @api private
*/
SendStream.prototype.error = function(status, err){
var res = this.res;
var msg = http.STATUS_CODES[status];
err = err || new Error(msg);
err.status = status;
if (this.listeners('error').length) return this.emit('error', err);
res.statusCode = err.status;
res.end(msg);
};
/**
* Check if the pathname is potentially malicious.
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.isMalicious = function(){
return !this._root && ~this.path.indexOf('..');
};
/**
* Check if the pathname ends with "/".
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.hasTrailingSlash = function(){
return '/' == this.path[this.path.length - 1];
};
/**
* Check if the basename leads with ".".
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.hasLeadingDot = function(){
return '.' == basename(this.path)[0];
};
/**
* Check if this is a conditional GET request.
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.isConditionalGET = function(){
return this.req.headers['if-none-match']
|| this.req.headers['if-modified-since'];
};
/**
* Strip content-* header fields.
*
* @api private
*/
SendStream.prototype.removeContentHeaderFields = function(){
var res = this.res;
Object.keys(res._headers).forEach(function(field){
if (0 == field.indexOf('content')) {
res.removeHeader(field);
}
});
};
/**
* Respond with 304 not modified.
*
* @api private
*/
SendStream.prototype.notModified = function(){
var res = this.res;
debug('not modified');
this.removeContentHeaderFields();
res.statusCode = 304;
res.end();
};
/**
* Check if the request is cacheable, aka
* responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}).
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.isCachable = function(){
var res = this.res;
return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode;
};
/**
* Handle stat() error.
*
* @param {Error} err
* @api private
*/
SendStream.prototype.onStatError = function(err){
var notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'];
if (~notfound.indexOf(err.code)) return this.error(404, err);
this.error(500, err);
};
/**
* Check if the cache is fresh.
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.isFresh = function(){
return fresh(this.req.headers, this.res._headers);
};
/**
* Redirect to `path`.
*
* @param {String} path
* @api private
*/
SendStream.prototype.redirect = function(path){
if (this.listeners('directory').length) return this.emit('directory');
var res = this.res;
path += '/';
res.statusCode = 301;
res.setHeader('Location', path);
res.end('Redirecting to ' + utils.escape(path));
};
/**
* Pipe to `res.
*
* @param {Stream} res
* @return {Stream} res
* @api public
*/
SendStream.prototype.pipe = function(res){
var self = this
, args = arguments
, path = this.path
, root = this._root;
// references
this.res = res;
// invalid request uri
path = utils.decode(path);
if (-1 == path) return this.error(400);
// null byte(s)
if (~path.indexOf('\0')) return this.error(400);
// join / normalize from optional root dir
if (root) path = normalize(join(this._root, path));
// ".." is malicious without "root"
if (this.isMalicious()) return this.error(403);
// malicious path
if (root && 0 != path.indexOf(root)) return this.error(403);
// hidden file support
if (!this._hidden && this.hasLeadingDot()) return this.error(404);
// index file support
if (this._index && this.hasTrailingSlash()) path += this._index;
debug('stat "%s"', path);
fs.stat(path, function(err, stat){
if (err) return self.onStatError(err);
if (stat.isDirectory()) return self.redirect(self.path);
self.send(path, stat);
});
return res;
};
/**
* Transfer `path`.
*
* @param {String} path
* @api public
*/
SendStream.prototype.send = function(path, stat){
var options = {};
var len = stat.size;
var res = this.res;
var req = this.req;
var ranges = req.headers.range;
// set header fields
this.setHeader(stat);
// set content-type
this.type(path);
// conditional GET support
if (this.isConditionalGET()
&& this.isCachable()
&& this.isFresh()) {
return this.notModified();
}
// Range support
if (ranges) {
ranges = parseRange(len, ranges);
// unsatisfiable
if (-1 == ranges) {
res.setHeader('Content-Range', 'bytes */' + stat.size);
return this.error(416);
}
// valid (syntactically invalid ranges are treated as a regular response)
if (-2 != ranges) {
options.start = ranges[0].start;
options.end = ranges[0].end;
// Content-Range
len = options.end - options.start + 1;
res.statusCode = 206;
res.setHeader('Content-Range', 'bytes '
+ options.start
+ '-'
+ options.end
+ '/'
+ stat.size);
}
}
// content-length
res.setHeader('Content-Length', len);
// HEAD support
if ('HEAD' == req.method) return res.end();
this.stream(path, options);
};
/**
* Stream `path` to the response.
*
* @param {String} path
* @param {Object} options
* @api private
*/
SendStream.prototype.stream = function(path, options){
// TODO: this is all lame, refactor meeee
var self = this;
var res = this.res;
var req = this.req;
// pipe
var stream = fs.createReadStream(path, options);
this.emit('stream', stream);
stream.pipe(res);
// socket closed, done with the fd
req.on('close', stream.destroy.bind(stream));
// error handling code-smell
stream.on('error', function(err){
// no hope in responding
if (res._header) {
console.error(err.stack);
req.destroy();
return;
}
// 500
err.status = 500;
self.emit('error', err);
});
// end
stream.on('end', function(){
self.emit('end');
});
};
/**
* Set content-type based on `path`
* if it hasn't been explicitly set.
*
* @param {String} path
* @api private
*/
SendStream.prototype.type = function(path){
var res = this.res;
if (res.getHeader('Content-Type')) return;
var type = mime.lookup(path);
var charset = mime.charsets.lookup(type);
debug('content-type %s', type);
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
};
/**
* Set reaponse header fields, most
* fields may be pre-defined.
*
* @param {Object} stat
* @api private
*/
SendStream.prototype.setHeader = function(stat){
var res = this.res;
res.setHeader('Accept-Ranges', 'bytes');
if (!res.getHeader('ETag')) res.setHeader('ETag', utils.etag(stat));
if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString());
if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (this._maxage / 1000));
if (!res.getHeader('Last-Modified')) res.setHeader('Last-Modified', stat.mtime.toUTCString());
};
| drbdvd/BeerTuviaSchool | server/node_modules/express/node_modules/send/lib/send.js | JavaScript | apache-2.0 | 9,299 |
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var common = require('../common');
var assert = require('assert');
var Readable = require('../../').Readable;
var r = new Readable();
var N = 256 * 1024;
// Go ahead and allow the pathological case for this test.
// Yes, it's an infinite loop, that's the point.
process.maxTickDepth = N + 2;
var reads = 0;
r._read = function(n) {
var chunk = reads++ === N ? null : new Buffer(1);
r.push(chunk);
};
r.on('readable', function onReadable() {
if (!(r._readableState.length % 256))
console.error('readable', r._readableState.length);
r.read(N * 2);
});
var ended = false;
r.on('end', function onEnd() {
ended = true;
});
r.read(0);
process.on('exit', function() {
assert(ended);
console.log('ok');
});
| hornedbull/nodeMongoDB | week4/hw4-3/blog/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/test/simple/test-stream2-read-sync-stack.js | JavaScript | gpl-2.0 | 1,856 |
/*
Copyright (c) 1998 - 2002 Frodo Looijaard <[email protected]>,
Philip Edelbrock <[email protected]>, Kyösti Mälkki <[email protected]>,
Mark D. Studebaker <[email protected]>
Copyright (C) 2005 - 2008 Jean Delvare <[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 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.
*/
/*
Supports the following VIA south bridges:
Chip name PCI ID REV I2C block
VT82C596A 0x3050 no
VT82C596B 0x3051 no
VT82C686A 0x3057 0x30 no
VT82C686B 0x3057 0x40 yes
VT8231 0x8235 no?
VT8233 0x3074 yes
VT8233A 0x3147 yes?
VT8235 0x3177 yes
VT8237R 0x3227 yes
VT8237A 0x3337 yes
VT8237S 0x3372 yes
VT8251 0x3287 yes
CX700 0x8324 yes
VX800/VX820 0x8353 yes
VX855/VX875 0x8409 yes
Note: we assume there can only be one device, with one SMBus interface.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/stddef.h>
#include <linux/ioport.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/io.h>
static struct pci_dev *vt596_pdev;
#define SMBBA1 0x90
#define SMBBA2 0x80
#define SMBBA3 0xD0
/* SMBus address offsets */
static unsigned short vt596_smba;
#define SMBHSTSTS (vt596_smba + 0)
#define SMBHSTCNT (vt596_smba + 2)
#define SMBHSTCMD (vt596_smba + 3)
#define SMBHSTADD (vt596_smba + 4)
#define SMBHSTDAT0 (vt596_smba + 5)
#define SMBHSTDAT1 (vt596_smba + 6)
#define SMBBLKDAT (vt596_smba + 7)
/* PCI Address Constants */
/* SMBus data in configuration space can be found in two places,
We try to select the better one */
static unsigned short SMBHSTCFG = 0xD2;
/* Other settings */
#define MAX_TIMEOUT 500
/* VT82C596 constants */
#define VT596_QUICK 0x00
#define VT596_BYTE 0x04
#define VT596_BYTE_DATA 0x08
#define VT596_WORD_DATA 0x0C
#define VT596_PROC_CALL 0x10
#define VT596_BLOCK_DATA 0x14
#define VT596_I2C_BLOCK_DATA 0x34
/* If force is set to anything different from 0, we forcibly enable the
VT596. DANGEROUS! */
static bool force;
module_param(force, bool, 0);
MODULE_PARM_DESC(force, "Forcibly enable the SMBus. DANGEROUS!");
/* If force_addr is set to anything different from 0, we forcibly enable
the VT596 at the given address. VERY DANGEROUS! */
static u16 force_addr;
module_param(force_addr, ushort, 0);
MODULE_PARM_DESC(force_addr,
"Forcibly enable the SMBus at the given address. "
"EXTREMELY DANGEROUS!");
static struct pci_driver vt596_driver;
static struct i2c_adapter vt596_adapter;
#define FEATURE_I2CBLOCK (1<<0)
static unsigned int vt596_features;
#ifdef DEBUG
static void vt596_dump_regs(const char *msg, u8 size)
{
dev_dbg(&vt596_adapter.dev, "%s: STS=%02x CNT=%02x CMD=%02x ADD=%02x "
"DAT=%02x,%02x\n", msg, inb_p(SMBHSTSTS), inb_p(SMBHSTCNT),
inb_p(SMBHSTCMD), inb_p(SMBHSTADD), inb_p(SMBHSTDAT0),
inb_p(SMBHSTDAT1));
if (size == VT596_BLOCK_DATA
|| size == VT596_I2C_BLOCK_DATA) {
int i;
dev_dbg(&vt596_adapter.dev, "BLK=");
for (i = 0; i < I2C_SMBUS_BLOCK_MAX / 2; i++)
printk("%02x,", inb_p(SMBBLKDAT));
printk("\n");
dev_dbg(&vt596_adapter.dev, " ");
for (; i < I2C_SMBUS_BLOCK_MAX - 1; i++)
printk("%02x,", inb_p(SMBBLKDAT));
printk("%02x\n", inb_p(SMBBLKDAT));
}
}
#else
static inline void vt596_dump_regs(const char *msg, u8 size) { }
#endif
/* Return -1 on error, 0 on success */
static int vt596_transaction(u8 size)
{
int temp;
int result = 0;
int timeout = 0;
vt596_dump_regs("Transaction (pre)", size);
/* Make sure the SMBus host is ready to start transmitting */
if ((temp = inb_p(SMBHSTSTS)) & 0x1F) {
dev_dbg(&vt596_adapter.dev, "SMBus busy (0x%02x). "
"Resetting...\n", temp);
outb_p(temp, SMBHSTSTS);
if ((temp = inb_p(SMBHSTSTS)) & 0x1F) {
dev_err(&vt596_adapter.dev, "SMBus reset failed! "
"(0x%02x)\n", temp);
return -EBUSY;
}
}
/* Start the transaction by setting bit 6 */
outb_p(0x40 | size, SMBHSTCNT);
/* We will always wait for a fraction of a second */
do {
msleep(1);
temp = inb_p(SMBHSTSTS);
} while ((temp & 0x01) && (++timeout < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout == MAX_TIMEOUT) {
result = -ETIMEDOUT;
dev_err(&vt596_adapter.dev, "SMBus timeout!\n");
}
if (temp & 0x10) {
result = -EIO;
dev_err(&vt596_adapter.dev, "Transaction failed (0x%02x)\n",
size);
}
if (temp & 0x08) {
result = -EIO;
dev_err(&vt596_adapter.dev, "SMBus collision!\n");
}
if (temp & 0x04) {
result = -ENXIO;
dev_dbg(&vt596_adapter.dev, "No response\n");
}
/* Resetting status register */
if (temp & 0x1F)
outb_p(temp, SMBHSTSTS);
vt596_dump_regs("Transaction (post)", size);
return result;
}
/* Return negative errno on error, 0 on success */
static s32 vt596_access(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write, u8 command,
int size, union i2c_smbus_data *data)
{
int i;
int status;
switch (size) {
case I2C_SMBUS_QUICK:
size = VT596_QUICK;
break;
case I2C_SMBUS_BYTE:
if (read_write == I2C_SMBUS_WRITE)
outb_p(command, SMBHSTCMD);
size = VT596_BYTE;
break;
case I2C_SMBUS_BYTE_DATA:
outb_p(command, SMBHSTCMD);
if (read_write == I2C_SMBUS_WRITE)
outb_p(data->byte, SMBHSTDAT0);
size = VT596_BYTE_DATA;
break;
case I2C_SMBUS_WORD_DATA:
outb_p(command, SMBHSTCMD);
if (read_write == I2C_SMBUS_WRITE) {
outb_p(data->word & 0xff, SMBHSTDAT0);
outb_p((data->word & 0xff00) >> 8, SMBHSTDAT1);
}
size = VT596_WORD_DATA;
break;
case I2C_SMBUS_PROC_CALL:
outb_p(command, SMBHSTCMD);
outb_p(data->word & 0xff, SMBHSTDAT0);
outb_p((data->word & 0xff00) >> 8, SMBHSTDAT1);
size = VT596_PROC_CALL;
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
if (!(vt596_features & FEATURE_I2CBLOCK))
goto exit_unsupported;
if (read_write == I2C_SMBUS_READ)
outb_p(data->block[0], SMBHSTDAT0);
/* Fall through */
case I2C_SMBUS_BLOCK_DATA:
outb_p(command, SMBHSTCMD);
if (read_write == I2C_SMBUS_WRITE) {
u8 len = data->block[0];
if (len > I2C_SMBUS_BLOCK_MAX)
len = I2C_SMBUS_BLOCK_MAX;
outb_p(len, SMBHSTDAT0);
inb_p(SMBHSTCNT); /* Reset SMBBLKDAT */
for (i = 1; i <= len; i++)
outb_p(data->block[i], SMBBLKDAT);
}
size = (size == I2C_SMBUS_I2C_BLOCK_DATA) ?
VT596_I2C_BLOCK_DATA : VT596_BLOCK_DATA;
break;
default:
goto exit_unsupported;
}
outb_p(((addr & 0x7f) << 1) | read_write, SMBHSTADD);
status = vt596_transaction(size);
if (status)
return status;
if (size == VT596_PROC_CALL)
read_write = I2C_SMBUS_READ;
if ((read_write == I2C_SMBUS_WRITE) || (size == VT596_QUICK))
return 0;
switch (size) {
case VT596_BYTE:
case VT596_BYTE_DATA:
data->byte = inb_p(SMBHSTDAT0);
break;
case VT596_WORD_DATA:
case VT596_PROC_CALL:
data->word = inb_p(SMBHSTDAT0) + (inb_p(SMBHSTDAT1) << 8);
break;
case VT596_I2C_BLOCK_DATA:
case VT596_BLOCK_DATA:
data->block[0] = inb_p(SMBHSTDAT0);
if (data->block[0] > I2C_SMBUS_BLOCK_MAX)
data->block[0] = I2C_SMBUS_BLOCK_MAX;
inb_p(SMBHSTCNT); /* Reset SMBBLKDAT */
for (i = 1; i <= data->block[0]; i++)
data->block[i] = inb_p(SMBBLKDAT);
break;
}
return 0;
exit_unsupported:
dev_warn(&vt596_adapter.dev, "Unsupported transaction %d\n",
size);
return -EOPNOTSUPP;
}
static u32 vt596_func(struct i2c_adapter *adapter)
{
u32 func = I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
I2C_SMBUS_PROC_CALL | I2C_FUNC_SMBUS_BLOCK_DATA;
if (vt596_features & FEATURE_I2CBLOCK)
func |= I2C_FUNC_SMBUS_I2C_BLOCK;
return func;
}
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = vt596_access,
.functionality = vt596_func,
};
static struct i2c_adapter vt596_adapter = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &smbus_algorithm,
};
static int vt596_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
unsigned char temp;
int error;
/* Determine the address of the SMBus areas */
if (force_addr) {
vt596_smba = force_addr & 0xfff0;
force = 0;
goto found;
}
if ((pci_read_config_word(pdev, id->driver_data, &vt596_smba)) ||
!(vt596_smba & 0x0001)) {
/* try 2nd address and config reg. for 596 */
if (id->device == PCI_DEVICE_ID_VIA_82C596_3 &&
!pci_read_config_word(pdev, SMBBA2, &vt596_smba) &&
(vt596_smba & 0x0001)) {
SMBHSTCFG = 0x84;
} else {
/* no matches at all */
dev_err(&pdev->dev, "Cannot configure "
"SMBus I/O Base address\n");
return -ENODEV;
}
}
vt596_smba &= 0xfff0;
if (vt596_smba == 0) {
dev_err(&pdev->dev, "SMBus base address "
"uninitialized - upgrade BIOS or use "
"force_addr=0xaddr\n");
return -ENODEV;
}
found:
error = acpi_check_region(vt596_smba, 8, vt596_driver.name);
if (error)
return -ENODEV;
if (!request_region(vt596_smba, 8, vt596_driver.name)) {
dev_err(&pdev->dev, "SMBus region 0x%x already in use!\n",
vt596_smba);
return -ENODEV;
}
pci_read_config_byte(pdev, SMBHSTCFG, &temp);
/* If force_addr is set, we program the new address here. Just to make
sure, we disable the VT596 first. */
if (force_addr) {
pci_write_config_byte(pdev, SMBHSTCFG, temp & 0xfe);
pci_write_config_word(pdev, id->driver_data, vt596_smba);
pci_write_config_byte(pdev, SMBHSTCFG, temp | 0x01);
dev_warn(&pdev->dev, "WARNING: SMBus interface set to new "
"address 0x%04x!\n", vt596_smba);
} else if (!(temp & 0x01)) {
if (force) {
/* NOTE: This assumes I/O space and other allocations
* WERE done by the Bios! Don't complain if your
* hardware does weird things after enabling this.
* :') Check for Bios updates before resorting to
* this.
*/
pci_write_config_byte(pdev, SMBHSTCFG, temp | 0x01);
dev_info(&pdev->dev, "Enabling SMBus device\n");
} else {
dev_err(&pdev->dev, "SMBUS: Error: Host SMBus "
"controller not enabled! - upgrade BIOS or "
"use force=1\n");
error = -ENODEV;
goto release_region;
}
}
dev_dbg(&pdev->dev, "VT596_smba = 0x%X\n", vt596_smba);
switch (pdev->device) {
case PCI_DEVICE_ID_VIA_CX700:
case PCI_DEVICE_ID_VIA_VX800:
case PCI_DEVICE_ID_VIA_VX855:
case PCI_DEVICE_ID_VIA_VX900:
case PCI_DEVICE_ID_VIA_8251:
case PCI_DEVICE_ID_VIA_8237:
case PCI_DEVICE_ID_VIA_8237A:
case PCI_DEVICE_ID_VIA_8237S:
case PCI_DEVICE_ID_VIA_8235:
case PCI_DEVICE_ID_VIA_8233A:
case PCI_DEVICE_ID_VIA_8233_0:
vt596_features |= FEATURE_I2CBLOCK;
break;
case PCI_DEVICE_ID_VIA_82C686_4:
/* The VT82C686B (rev 0x40) does support I2C block
transactions, but the VT82C686A (rev 0x30) doesn't */
if (pdev->revision >= 0x40)
vt596_features |= FEATURE_I2CBLOCK;
break;
}
vt596_adapter.dev.parent = &pdev->dev;
snprintf(vt596_adapter.name, sizeof(vt596_adapter.name),
"SMBus Via Pro adapter at %04x", vt596_smba);
vt596_pdev = pci_dev_get(pdev);
error = i2c_add_adapter(&vt596_adapter);
if (error) {
pci_dev_put(vt596_pdev);
vt596_pdev = NULL;
goto release_region;
}
/* Always return failure here. This is to allow other drivers to bind
* to this pci device. We don't really want to have control over the
* pci device, we only wanted to read as few register values from it.
*/
return -ENODEV;
release_region:
release_region(vt596_smba, 8);
return error;
}
static const struct pci_device_id vt596_ids[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C596_3),
.driver_data = SMBBA1 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C596B_3),
.driver_data = SMBBA1 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686_4),
.driver_data = SMBBA1 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233_0),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233A),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237A),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237S),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8231_4),
.driver_data = SMBBA1 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8251),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_CX700),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VX800),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VX855),
.driver_data = SMBBA3 },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VX900),
.driver_data = SMBBA3 },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, vt596_ids);
static struct pci_driver vt596_driver = {
.name = "vt596_smbus",
.id_table = vt596_ids,
.probe = vt596_probe,
};
static int __init i2c_vt596_init(void)
{
return pci_register_driver(&vt596_driver);
}
static void __exit i2c_vt596_exit(void)
{
pci_unregister_driver(&vt596_driver);
if (vt596_pdev != NULL) {
i2c_del_adapter(&vt596_adapter);
release_region(vt596_smba, 8);
pci_dev_put(vt596_pdev);
vt596_pdev = NULL;
}
}
MODULE_AUTHOR("Kyosti Malkki <[email protected]>, "
"Mark D. Studebaker <[email protected]> and "
"Jean Delvare <[email protected]>");
MODULE_DESCRIPTION("vt82c596 SMBus driver");
MODULE_LICENSE("GPL");
module_init(i2c_vt596_init);
module_exit(i2c_vt596_exit);
| AiJiaZone/linux-4.0 | virt/drivers/i2c/busses/i2c-viapro.c | C | gpl-2.0 | 14,262 |
module Fruits
class Apple
include Mongoid::Document
has_many :bananas, :class_name => "Fruits::Banana"
recursively_embeds_many
end
class Banana
include Mongoid::Document
belongs_to :apple, :class_name => "Fruits::Apple"
end
end
| LastStar/mongoid | spec/models/fruits.rb | Ruby | mit | 257 |
/**
* angular-strap
* @version v2.3.6 - 2015-11-14
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes <[email protected]> (https://github.com/mgcrea)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.typeahead').run([ '$templateCache', function($templateCache) {
$templateCache.put('typeahead/typeahead.tpl.html', '<ul tabindex="-1" class="typeahead dropdown-menu" ng-show="$isVisible()" role="select"><li role="presentation" ng-repeat="match in $matches" ng-class="{active: $index == $activeIndex}"><a role="menuitem" tabindex="-1" ng-click="$select($index, $event)" ng-bind="match.label"></a></li></ul>');
} ]); | EmprendedoresLA/emprendevs-equipo-1 | webapp2/bower_components/angular-strap/dist/modules/typeahead.tpl.js | JavaScript | mit | 708 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Display form for changing/adding table fields/columns.
* Included by tbl_addfield.php and tbl_create.php
*
* @package PhpMyAdmin
*/
if (!defined('PHPMYADMIN')) {
exit;
}
/**
* Check parameters
*/
require_once 'libraries/di/Container.class.php';
require_once 'libraries/Util.class.php';
require_once 'libraries/Template.class.php';
require_once 'libraries/util.lib.php';
use PMA\Util;
PMA_Util::checkParameters(array('server', 'db', 'table', 'action', 'num_fields'));
global $db, $table;
/**
* Initialize to avoid code execution path warnings
*/
if (!isset($num_fields)) {
$num_fields = 0;
}
if (!isset($mime_map)) {
$mime_map = null;
}
if (!isset($columnMeta)) {
$columnMeta = array();
}
// Get available character sets and storage engines
require_once './libraries/mysql_charsets.inc.php';
require_once './libraries/StorageEngine.class.php';
/**
* Class for partition management
*/
require_once './libraries/Partition.class.php';
/** @var PMA_String $pmaString */
$pmaString = $GLOBALS['PMA_String'];
$length_values_input_size = 8;
$content_cells = array();
/** @var string $db */
$form_params = array(
'db' => $db
);
if ($action == 'tbl_create.php') {
$form_params['reload'] = 1;
} else {
if ($action == 'tbl_addfield.php') {
$form_params = array_merge(
$form_params, array(
'field_where' => Util\get($_REQUEST, 'field_where'))
);
if (isset($_REQUEST['field_where'])) {
$form_params['after_field'] = $_REQUEST['after_field'];
}
}
$form_params['table'] = $table;
}
if (isset($num_fields)) {
$form_params['orig_num_fields'] = $num_fields;
}
$form_params = array_merge(
$form_params,
array(
'orig_field_where' => Util\get($_REQUEST, 'field_where'),
'orig_after_field' => Util\get($_REQUEST, 'after_field'),
)
);
if (isset($selected) && is_array($selected)) {
foreach ($selected as $o_fld_nr => $o_fld_val) {
$form_params['selected[' . $o_fld_nr . ']'] = $o_fld_val;
}
}
$is_backup = ($action != 'tbl_create.php' && $action != 'tbl_addfield.php');
require_once './libraries/transformations.lib.php';
$cfgRelation = PMA_getRelationsParam();
$comments_map = PMA_getComments($db, $table);
$move_columns = array();
if (isset($fields_meta)) {
/** @var PMA_DatabaseInterface $dbi */
$dbi = \PMA\DI\Container::getDefaultContainer()->get('dbi');
$move_columns = $dbi->getTable($db, $table)->getColumnsMeta();
}
$available_mime = array();
if ($cfgRelation['mimework'] && $GLOBALS['cfg']['BrowseMIME']) {
$mime_map = PMA_getMIME($db, $table);
$available_mime = PMA_getAvailableMIMEtypes();
}
// workaround for field_fulltext, because its submitted indices contain
// the index as a value, not a key. Inserted here for easier maintenance
// and less code to change in existing files.
if (isset($field_fulltext) && is_array($field_fulltext)) {
foreach ($field_fulltext as $fulltext_nr => $fulltext_indexkey) {
$submit_fulltext[$fulltext_indexkey] = $fulltext_indexkey;
}
}
if (isset($_REQUEST['submit_num_fields'])) {
//if adding new fields, set regenerate to keep the original values
$regenerate = 1;
}
$foreigners = PMA_getForeigners($db, $table, '', 'foreign');
$child_references = null;
// From MySQL 5.6.6 onwards columns with foreign keys can be renamed.
// Hence, no need to get child references
if (PMA_MYSQL_INT_VERSION < 50606) {
$child_references = PMA_getChildReferences($db, $table);
}
for ($columnNumber = 0; $columnNumber < $num_fields; $columnNumber++) {
$type = '';
$length = '';
$columnMeta = array();
$submit_attribute = null;
$extracted_columnspec = array();
if (!empty($regenerate)) {
$columnMeta = array_merge(
$columnMeta,
array(
'Field' => Util\get(
$_REQUEST, "field_name.${columnNumber}", false
),
'Type' => Util\get(
$_REQUEST, "field_type.${columnNumber}", false
),
'Collation' => Util\get(
$_REQUEST, "field_collation.${columnNumber}", ''
),
'Null' => Util\get(
$_REQUEST, "field_null.${columnNumber}", ''
),
'DefaultType' => Util\get(
$_REQUEST, "field_default_type.${columnNumber}", 'NONE'
),
'DefaultValue' => Util\get(
$_REQUEST, "field_default_value.${columnNumber}", ''
),
'Extra' => Util\get(
$_REQUEST, "field_extra.${columnNumber}", false
),
'Virtuality' => Util\get(
$_REQUEST, "field_virtuality.${columnNumber}", ''
),
'Expression' => Util\get(
$_REQUEST, "field_expression.${columnNumber}", ''
),
)
);
$columnMeta['Key'] = '';
$parts = explode(
'_', Util\get($_REQUEST, "field_key.${columnNumber}", ''), 2
);
if (count($parts) == 2 && $parts[1] == $columnNumber) {
$columnMeta['Key'] = Util\get(
array(
'primary' => 'PRI',
'index' => 'MUL',
'unique' => 'UNI',
'fulltext' => 'FULLTEXT',
'spatial' => 'SPATIAL'
),
$parts[0], ''
);
}
$columnMeta['Comment']
= isset($submit_fulltext[$columnNumber])
&& ($submit_fulltext[$columnNumber] == $columnNumber)
? 'FULLTEXT' : false;
switch ($columnMeta['DefaultType']) {
case 'NONE':
$columnMeta['Default'] = null;
break;
case 'USER_DEFINED':
$columnMeta['Default'] = $columnMeta['DefaultValue'];
break;
case 'NULL':
case 'CURRENT_TIMESTAMP':
$columnMeta['Default'] = $columnMeta['DefaultType'];
break;
}
$length = Util\get($_REQUEST, "field_length.${columnNumber}", $length);
$submit_attribute = Util\get(
$_REQUEST, "field_attribute.${columnNumber}", false
);
$comments_map[$columnMeta['Field']] = Util\get(
$_REQUEST, "field_comments.${columnNumber}"
);
$mime_map[$columnMeta['Field']] = array_merge(
$mime_map[$columnMeta['Field']],
array(
'mimetype' => Util\get($_REQUEST, "field_mimetype.${$columnNumber}"),
'transformation' => Util\get(
$_REQUEST, "field_transformation.${$columnNumber}"
),
'transformation_options' => Util\get(
$_REQUEST, "field_transformation_options.${$columnNumber}"
),
)
);
} elseif (isset($fields_meta[$columnNumber])) {
$columnMeta = $fields_meta[$columnNumber];
$virtual = array(
'VIRTUAL', 'PERSISTENT', 'VIRTUAL GENERATED', 'STORED GENERATED'
);
if (in_array($columnMeta['Extra'], $virtual)) {
$tableObj = new PMA_Table($GLOBALS['table'], $GLOBALS['db']);
$expressions = $tableObj->getColumnGenerationExpression(
$columnMeta['Field']
);
$columnMeta['Expression'] = $expressions[$columnMeta['Field']];
}
switch ($columnMeta['Default']) {
case null:
if (is_null($columnMeta['Default'])) { // null
if ($columnMeta['Null'] == 'YES') {
$columnMeta['DefaultType'] = 'NULL';
$columnMeta['DefaultValue'] = '';
} else {
$columnMeta['DefaultType'] = 'NONE';
$columnMeta['DefaultValue'] = '';
}
} else { // empty
$columnMeta['DefaultType'] = 'USER_DEFINED';
$columnMeta['DefaultValue'] = $columnMeta['Default'];
}
break;
case 'CURRENT_TIMESTAMP':
$columnMeta['DefaultType'] = 'CURRENT_TIMESTAMP';
$columnMeta['DefaultValue'] = '';
break;
default:
$columnMeta['DefaultType'] = 'USER_DEFINED';
$columnMeta['DefaultValue'] = $columnMeta['Default'];
break;
}
}
if (isset($columnMeta['Type'])) {
$extracted_columnspec = PMA_Util::extractColumnSpec($columnMeta['Type']);
if ($extracted_columnspec['type'] == 'bit') {
$columnMeta['Default']
= PMA_Util::convertBitDefaultValue($columnMeta['Default']);
}
$type = $extracted_columnspec['type'];
if ($length == '') {
$length = $extracted_columnspec['spec_in_brackets'];
}
} else {
// creating a column
$columnMeta['Type'] = '';
}
// Variable tell if current column is bound in a foreign key constraint or not.
// MySQL version from 5.6.6 allow renaming columns with foreign keys
if (isset($columnMeta['Field'])
&& isset($form_params['table'])
&& PMA_MYSQL_INT_VERSION < 50606
) {
$columnMeta['column_status'] = PMA_checkChildForeignReferences(
$form_params['db'],
$form_params['table'],
$columnMeta['Field'],
$foreigners,
$child_references
);
}
// some types, for example longtext, are reported as
// "longtext character set latin7" when their charset and / or collation
// differs from the ones of the corresponding database.
// rtrim the type, for cases like "float unsigned"
$type = rtrim(
mb_ereg_replace('[\w\W]character set[\w\W]*', '', $type)
);
/**
* old column attributes
*/
if ($is_backup) {
// old column name
if (isset($columnMeta['Field'])) {
$form_params['field_orig[' . $columnNumber . ']']
= $columnMeta['Field'];
if (isset($columnMeta['column_status'])
&& !$columnMeta['column_status']['isEditable']
) {
$form_params['field_name[' . $columnNumber . ']']
= $columnMeta['Field'];
}
} else {
$form_params['field_orig[' . $columnNumber . ']'] = '';
}
// old column type
if (isset($columnMeta['Type'])) {
// keep in uppercase because the new type will be in uppercase
$form_params['field_type_orig[' . $columnNumber . ']']
= /*overload*/
mb_strtoupper($type);
if (isset($columnMeta['column_status'])
&& !$columnMeta['column_status']['isEditable']
) {
$form_params['field_type[' . $columnNumber . ']']
= /*overload*/
mb_strtoupper($type);
}
} else {
$form_params['field_type_orig[' . $columnNumber . ']'] = '';
}
// old column length
$form_params['field_length_orig[' . $columnNumber . ']'] = $length;
// old column default
$form_params = array_merge(
$form_params,
array(
"field_default_value_orig[${columnNumber}]" => Util\get(
$columnMeta, 'Default', ''
),
"field_default_type_orig[${columnNumber}]" => Util\get(
$columnMeta, 'DefaultType', ''
),
"field_collation_orig[${columnNumber}]" => Util\get(
$columnMeta, 'Collation', ''
),
"field_attribute_orig[${columnNumber}]" => trim(
Util\get($extracted_columnspec, 'attribute', '')
),
"field_null_orig[${columnNumber}]" => Util\get(
$columnMeta, 'Null', ''
),
"field_extra_orig[${columnNumber}]" => Util\get(
$columnMeta, 'Extra', ''
),
"field_comments_orig[${columnNumber}]" => Util\get(
$columnMeta, 'Comment', ''
),
"field_virtuality_orig[${columnNumber}]" => Util\get(
$columnMeta, 'Virtuality', ''
),
"field_expression_orig[${columnNumber}]" => Util\get(
$columnMeta, 'Expression', ''
),
)
);
}
$content_cells[$columnNumber] = array(
'columnNumber' => $columnNumber,
'columnMeta' => $columnMeta,
'type_upper' => /*overload*/mb_strtoupper($type),
'length_values_input_size' => $length_values_input_size,
'length' => $length,
'extracted_columnspec' => $extracted_columnspec,
'submit_attribute' => $submit_attribute,
'comments_map' => $comments_map,
'fields_meta' => isset($fields_meta) ? $fields_meta : null,
'is_backup' => $is_backup,
'move_columns' => $move_columns,
'cfgRelation' => $cfgRelation,
'available_mime' => $available_mime,
'mime_map' => isset($mime_map) ? $mime_map : array()
);
} // end for
$html = PMA\Template::get('columns_definitions/column_definitions_form')->render(
array(
'is_backup' => $is_backup,
'fields_meta' => isset($fields_meta) ? $fields_meta : null,
'mimework' => $cfgRelation['mimework'],
'action' => $action,
'form_params' => $form_params,
'content_cells' => $content_cells,
)
);
unset($form_params);
$response = PMA_Response::getInstance();
$response->getHeader()->getScripts()->addFiles(
array(
'jquery/jquery.uitablefilter.js',
'indexes.js'
)
);
$response->addHTML($html);
| Dokaponteam/ITF_Project | xampp/phpMyAdmin/libraries/tbl_columns_definition_form.inc.php | PHP | mit | 14,101 |
/******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2012 - 2013 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <[email protected]>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2012 - 2013 Intel Corporation. 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#include <linux/jiffies.h>
#include <net/mac80211.h>
#include "iwl-notif-wait.h"
#include "iwl-trans.h"
#include "fw-api.h"
#include "time-event.h"
#include "mvm.h"
#include "iwl-io.h"
#include "iwl-prph.h"
/* A TimeUnit is 1024 microsecond */
#define MSEC_TO_TU(_msec) (_msec*1000/1024)
/*
* For the high priority TE use a time event type that has similar priority to
* the FW's action scan priority.
*/
#define IWL_MVM_ROC_TE_TYPE_NORMAL TE_P2P_DEVICE_DISCOVERABLE
#define IWL_MVM_ROC_TE_TYPE_MGMT_TX TE_P2P_CLIENT_ASSOC
void iwl_mvm_te_clear_data(struct iwl_mvm *mvm,
struct iwl_mvm_time_event_data *te_data)
{
lockdep_assert_held(&mvm->time_event_lock);
if (te_data->id == TE_MAX)
return;
list_del(&te_data->list);
te_data->running = false;
te_data->uid = 0;
te_data->id = TE_MAX;
te_data->vif = NULL;
}
void iwl_mvm_roc_done_wk(struct work_struct *wk)
{
struct iwl_mvm *mvm = container_of(wk, struct iwl_mvm, roc_done_wk);
synchronize_net();
/*
* Flush the offchannel queue -- this is called when the time
* event finishes or is cancelled, so that frames queued for it
* won't get stuck on the queue and be transmitted in the next
* time event.
* We have to send the command asynchronously since this cannot
* be under the mutex for locking reasons, but that's not an
* issue as it will have to complete before the next command is
* executed, and a new time event means a new command.
*/
iwl_mvm_flush_tx_path(mvm, BIT(IWL_MVM_OFFCHANNEL_QUEUE), false);
}
static void iwl_mvm_roc_finished(struct iwl_mvm *mvm)
{
/*
* First, clear the ROC_RUNNING status bit. This will cause the TX
* path to drop offchannel transmissions. That would also be done
* by mac80211, but it is racy, in particular in the case that the
* time event actually completed in the firmware (which is handled
* in iwl_mvm_te_handle_notif).
*/
clear_bit(IWL_MVM_STATUS_ROC_RUNNING, &mvm->status);
/*
* Of course, our status bit is just as racy as mac80211, so in
* addition, fire off the work struct which will drop all frames
* from the hardware queues that made it through the race. First
* it will of course synchronize the TX path to make sure that
* any *new* TX will be rejected.
*/
schedule_work(&mvm->roc_done_wk);
}
static bool iwl_mvm_te_check_disconnect(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
const char *errmsg)
{
if (vif->type != NL80211_IFTYPE_STATION)
return false;
if (vif->bss_conf.assoc && vif->bss_conf.dtim_period)
return false;
if (errmsg)
IWL_ERR(mvm, "%s\n", errmsg);
ieee80211_connection_loss(vif);
return true;
}
/*
* Handles a FW notification for an event that is known to the driver.
*
* @mvm: the mvm component
* @te_data: the time event data
* @notif: the notification data corresponding the time event data.
*/
static void iwl_mvm_te_handle_notif(struct iwl_mvm *mvm,
struct iwl_mvm_time_event_data *te_data,
struct iwl_time_event_notif *notif)
{
lockdep_assert_held(&mvm->time_event_lock);
IWL_DEBUG_TE(mvm, "Handle time event notif - UID = 0x%x action %d\n",
le32_to_cpu(notif->unique_id),
le32_to_cpu(notif->action));
/*
* The FW sends the start/end time event notifications even for events
* that it fails to schedule. This is indicated in the status field of
* the notification. This happens in cases that the scheduler cannot
* find a schedule that can handle the event (for example requesting a
* P2P Device discoveribility, while there are other higher priority
* events in the system).
*/
if (!le32_to_cpu(notif->status)) {
bool start = le32_to_cpu(notif->action) &
TE_V2_NOTIF_HOST_EVENT_START;
IWL_WARN(mvm, "Time Event %s notification failure\n",
start ? "start" : "end");
if (iwl_mvm_te_check_disconnect(mvm, te_data->vif, NULL)) {
iwl_mvm_te_clear_data(mvm, te_data);
return;
}
}
if (le32_to_cpu(notif->action) & TE_V2_NOTIF_HOST_EVENT_END) {
IWL_DEBUG_TE(mvm,
"TE ended - current time %lu, estimated end %lu\n",
jiffies, te_data->end_jiffies);
if (te_data->vif->type == NL80211_IFTYPE_P2P_DEVICE) {
ieee80211_remain_on_channel_expired(mvm->hw);
iwl_mvm_roc_finished(mvm);
}
/*
* By now, we should have finished association
* and know the dtim period.
*/
iwl_mvm_te_check_disconnect(mvm, te_data->vif,
"No association and the time event is over already...");
iwl_mvm_te_clear_data(mvm, te_data);
} else if (le32_to_cpu(notif->action) & TE_V2_NOTIF_HOST_EVENT_START) {
te_data->running = true;
te_data->end_jiffies = TU_TO_EXP_TIME(te_data->duration);
if (te_data->vif->type == NL80211_IFTYPE_P2P_DEVICE) {
set_bit(IWL_MVM_STATUS_ROC_RUNNING, &mvm->status);
ieee80211_ready_on_channel(mvm->hw);
}
} else {
IWL_WARN(mvm, "Got TE with unknown action\n");
}
}
/*
* The Rx handler for time event notifications
*/
int iwl_mvm_rx_time_event_notif(struct iwl_mvm *mvm,
struct iwl_rx_cmd_buffer *rxb,
struct iwl_device_cmd *cmd)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_time_event_notif *notif = (void *)pkt->data;
struct iwl_mvm_time_event_data *te_data, *tmp;
IWL_DEBUG_TE(mvm, "Time event notification - UID = 0x%x action %d\n",
le32_to_cpu(notif->unique_id),
le32_to_cpu(notif->action));
spin_lock_bh(&mvm->time_event_lock);
list_for_each_entry_safe(te_data, tmp, &mvm->time_event_list, list) {
if (le32_to_cpu(notif->unique_id) == te_data->uid)
iwl_mvm_te_handle_notif(mvm, te_data, notif);
}
spin_unlock_bh(&mvm->time_event_lock);
return 0;
}
static bool iwl_mvm_time_event_response(struct iwl_notif_wait_data *notif_wait,
struct iwl_rx_packet *pkt, void *data)
{
struct iwl_mvm *mvm =
container_of(notif_wait, struct iwl_mvm, notif_wait);
struct iwl_mvm_time_event_data *te_data = data;
struct iwl_time_event_resp *resp;
int resp_len = le32_to_cpu(pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK;
if (WARN_ON(pkt->hdr.cmd != TIME_EVENT_CMD))
return true;
if (WARN_ON_ONCE(resp_len != sizeof(pkt->hdr) + sizeof(*resp))) {
IWL_ERR(mvm, "Invalid TIME_EVENT_CMD response\n");
return true;
}
resp = (void *)pkt->data;
/* we should never get a response to another TIME_EVENT_CMD here */
if (WARN_ON_ONCE(le32_to_cpu(resp->id) != te_data->id))
return false;
te_data->uid = le32_to_cpu(resp->unique_id);
IWL_DEBUG_TE(mvm, "TIME_EVENT_CMD response - UID = 0x%x\n",
te_data->uid);
return true;
}
/* used to convert from time event API v2 to v1 */
#define TE_V2_DEP_POLICY_MSK (TE_V2_DEP_OTHER | TE_V2_DEP_TSF |\
TE_V2_EVENT_SOCIOPATHIC)
static inline u16 te_v2_get_notify(__le16 policy)
{
return le16_to_cpu(policy) & TE_V2_NOTIF_MSK;
}
static inline u16 te_v2_get_dep_policy(__le16 policy)
{
return (le16_to_cpu(policy) & TE_V2_DEP_POLICY_MSK) >>
TE_V2_PLACEMENT_POS;
}
static inline u16 te_v2_get_absence(__le16 policy)
{
return (le16_to_cpu(policy) & TE_V2_ABSENCE) >> TE_V2_ABSENCE_POS;
}
static void iwl_mvm_te_v2_to_v1(const struct iwl_time_event_cmd_v2 *cmd_v2,
struct iwl_time_event_cmd_v1 *cmd_v1)
{
cmd_v1->id_and_color = cmd_v2->id_and_color;
cmd_v1->action = cmd_v2->action;
cmd_v1->id = cmd_v2->id;
cmd_v1->apply_time = cmd_v2->apply_time;
cmd_v1->max_delay = cmd_v2->max_delay;
cmd_v1->depends_on = cmd_v2->depends_on;
cmd_v1->interval = cmd_v2->interval;
cmd_v1->duration = cmd_v2->duration;
if (cmd_v2->repeat == TE_V2_REPEAT_ENDLESS)
cmd_v1->repeat = cpu_to_le32(TE_V1_REPEAT_ENDLESS);
else
cmd_v1->repeat = cpu_to_le32(cmd_v2->repeat);
cmd_v1->max_frags = cpu_to_le32(cmd_v2->max_frags);
cmd_v1->interval_reciprocal = 0; /* unused */
cmd_v1->dep_policy = cpu_to_le32(te_v2_get_dep_policy(cmd_v2->policy));
cmd_v1->is_present = cpu_to_le32(!te_v2_get_absence(cmd_v2->policy));
cmd_v1->notify = cpu_to_le32(te_v2_get_notify(cmd_v2->policy));
}
static int iwl_mvm_send_time_event_cmd(struct iwl_mvm *mvm,
const struct iwl_time_event_cmd_v2 *cmd)
{
struct iwl_time_event_cmd_v1 cmd_v1;
if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_TIME_EVENT_API_V2)
return iwl_mvm_send_cmd_pdu(mvm, TIME_EVENT_CMD, CMD_SYNC,
sizeof(*cmd), cmd);
iwl_mvm_te_v2_to_v1(cmd, &cmd_v1);
return iwl_mvm_send_cmd_pdu(mvm, TIME_EVENT_CMD, CMD_SYNC,
sizeof(cmd_v1), &cmd_v1);
}
static int iwl_mvm_time_event_send_add(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_mvm_time_event_data *te_data,
struct iwl_time_event_cmd_v2 *te_cmd)
{
static const u8 time_event_response[] = { TIME_EVENT_CMD };
struct iwl_notification_wait wait_time_event;
int ret;
lockdep_assert_held(&mvm->mutex);
IWL_DEBUG_TE(mvm, "Add new TE, duration %d TU\n",
le32_to_cpu(te_cmd->duration));
spin_lock_bh(&mvm->time_event_lock);
if (WARN_ON(te_data->id != TE_MAX)) {
spin_unlock_bh(&mvm->time_event_lock);
return -EIO;
}
te_data->vif = vif;
te_data->duration = le32_to_cpu(te_cmd->duration);
te_data->id = le32_to_cpu(te_cmd->id);
list_add_tail(&te_data->list, &mvm->time_event_list);
spin_unlock_bh(&mvm->time_event_lock);
/*
* Use a notification wait, which really just processes the
* command response and doesn't wait for anything, in order
* to be able to process the response and get the UID inside
* the RX path. Using CMD_WANT_SKB doesn't work because it
* stores the buffer and then wakes up this thread, by which
* time another notification (that the time event started)
* might already be processed unsuccessfully.
*/
iwl_init_notification_wait(&mvm->notif_wait, &wait_time_event,
time_event_response,
ARRAY_SIZE(time_event_response),
iwl_mvm_time_event_response, te_data);
ret = iwl_mvm_send_time_event_cmd(mvm, te_cmd);
if (ret) {
IWL_ERR(mvm, "Couldn't send TIME_EVENT_CMD: %d\n", ret);
iwl_remove_notification(&mvm->notif_wait, &wait_time_event);
goto out_clear_te;
}
/* No need to wait for anything, so just pass 1 (0 isn't valid) */
ret = iwl_wait_notification(&mvm->notif_wait, &wait_time_event, 1);
/* should never fail */
WARN_ON_ONCE(ret);
if (ret) {
out_clear_te:
spin_lock_bh(&mvm->time_event_lock);
iwl_mvm_te_clear_data(mvm, te_data);
spin_unlock_bh(&mvm->time_event_lock);
}
return ret;
}
void iwl_mvm_protect_session(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
u32 duration, u32 min_duration,
u32 max_delay)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_mvm_time_event_data *te_data = &mvmvif->time_event_data;
struct iwl_time_event_cmd_v2 time_cmd = {};
lockdep_assert_held(&mvm->mutex);
if (te_data->running &&
time_after(te_data->end_jiffies, TU_TO_EXP_TIME(min_duration))) {
IWL_DEBUG_TE(mvm, "We have enough time in the current TE: %u\n",
jiffies_to_msecs(te_data->end_jiffies - jiffies));
return;
}
if (te_data->running) {
IWL_DEBUG_TE(mvm, "extend 0x%x: only %u ms left\n",
te_data->uid,
jiffies_to_msecs(te_data->end_jiffies - jiffies));
/*
* we don't have enough time
* cancel the current TE and issue a new one
* Of course it would be better to remove the old one only
* when the new one is added, but we don't care if we are off
* channel for a bit. All we need to do, is not to return
* before we actually begin to be on the channel.
*/
iwl_mvm_stop_session_protection(mvm, vif);
}
time_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD);
time_cmd.id_and_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color));
time_cmd.id = cpu_to_le32(TE_BSS_STA_AGGRESSIVE_ASSOC);
time_cmd.apply_time =
cpu_to_le32(iwl_read_prph(mvm->trans, DEVICE_SYSTEM_TIME_REG));
time_cmd.max_frags = TE_V2_FRAG_NONE;
time_cmd.max_delay = cpu_to_le32(max_delay);
/* TODO: why do we need to interval = bi if it is not periodic? */
time_cmd.interval = cpu_to_le32(1);
time_cmd.duration = cpu_to_le32(duration);
time_cmd.repeat = 1;
time_cmd.policy = cpu_to_le16(TE_V2_NOTIF_HOST_EVENT_START |
TE_V2_NOTIF_HOST_EVENT_END);
iwl_mvm_time_event_send_add(mvm, vif, te_data, &time_cmd);
}
/*
* Explicit request to remove a time event. The removal of a time event needs to
* be synchronized with the flow of a time event's end notification, which also
* removes the time event from the op mode data structures.
*/
void iwl_mvm_remove_time_event(struct iwl_mvm *mvm,
struct iwl_mvm_vif *mvmvif,
struct iwl_mvm_time_event_data *te_data)
{
struct iwl_time_event_cmd_v2 time_cmd = {};
u32 id, uid;
int ret;
/*
* It is possible that by the time we got to this point the time
* event was already removed.
*/
spin_lock_bh(&mvm->time_event_lock);
/* Save time event uid before clearing its data */
uid = te_data->uid;
id = te_data->id;
/*
* The clear_data function handles time events that were already removed
*/
iwl_mvm_te_clear_data(mvm, te_data);
spin_unlock_bh(&mvm->time_event_lock);
/*
* It is possible that by the time we try to remove it, the time event
* has already ended and removed. In such a case there is no need to
* send a removal command.
*/
if (id == TE_MAX) {
IWL_DEBUG_TE(mvm, "TE 0x%x has already ended\n", uid);
return;
}
/* When we remove a TE, the UID is to be set in the id field */
time_cmd.id = cpu_to_le32(uid);
time_cmd.action = cpu_to_le32(FW_CTXT_ACTION_REMOVE);
time_cmd.id_and_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color));
IWL_DEBUG_TE(mvm, "Removing TE 0x%x\n", le32_to_cpu(time_cmd.id));
ret = iwl_mvm_send_time_event_cmd(mvm, &time_cmd);
if (WARN_ON(ret))
return;
}
void iwl_mvm_stop_session_protection(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_mvm_time_event_data *te_data = &mvmvif->time_event_data;
lockdep_assert_held(&mvm->mutex);
iwl_mvm_remove_time_event(mvm, mvmvif, te_data);
}
int iwl_mvm_start_p2p_roc(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
int duration, enum ieee80211_roc_type type)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_mvm_time_event_data *te_data = &mvmvif->time_event_data;
struct iwl_time_event_cmd_v2 time_cmd = {};
lockdep_assert_held(&mvm->mutex);
if (te_data->running) {
IWL_WARN(mvm, "P2P_DEVICE remain on channel already running\n");
return -EBUSY;
}
/*
* Flush the done work, just in case it's still pending, so that
* the work it does can complete and we can accept new frames.
*/
flush_work(&mvm->roc_done_wk);
time_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD);
time_cmd.id_and_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color));
switch (type) {
case IEEE80211_ROC_TYPE_NORMAL:
time_cmd.id = cpu_to_le32(IWL_MVM_ROC_TE_TYPE_NORMAL);
break;
case IEEE80211_ROC_TYPE_MGMT_TX:
time_cmd.id = cpu_to_le32(IWL_MVM_ROC_TE_TYPE_MGMT_TX);
break;
default:
WARN_ONCE(1, "Got an invalid ROC type\n");
return -EINVAL;
}
time_cmd.apply_time = cpu_to_le32(0);
time_cmd.interval = cpu_to_le32(1);
/*
* The P2P Device TEs can have lower priority than other events
* that are being scheduled by the driver/fw, and thus it might not be
* scheduled. To improve the chances of it being scheduled, allow them
* to be fragmented, and in addition allow them to be delayed.
*/
time_cmd.max_frags = min(MSEC_TO_TU(duration)/50, TE_V2_FRAG_ENDLESS);
time_cmd.max_delay = cpu_to_le32(MSEC_TO_TU(duration/2));
time_cmd.duration = cpu_to_le32(MSEC_TO_TU(duration));
time_cmd.repeat = 1;
time_cmd.policy = cpu_to_le16(TE_V2_NOTIF_HOST_EVENT_START |
TE_V2_NOTIF_HOST_EVENT_END);
return iwl_mvm_time_event_send_add(mvm, vif, te_data, &time_cmd);
}
void iwl_mvm_stop_p2p_roc(struct iwl_mvm *mvm)
{
struct iwl_mvm_vif *mvmvif;
struct iwl_mvm_time_event_data *te_data;
lockdep_assert_held(&mvm->mutex);
/*
* Iterate over the list of time events and find the time event that is
* associated with a P2P_DEVICE interface.
* This assumes that a P2P_DEVICE interface can have only a single time
* event at any given time and this time event coresponds to a ROC
* request
*/
mvmvif = NULL;
spin_lock_bh(&mvm->time_event_lock);
list_for_each_entry(te_data, &mvm->time_event_list, list) {
if (te_data->vif->type == NL80211_IFTYPE_P2P_DEVICE) {
mvmvif = iwl_mvm_vif_from_mac80211(te_data->vif);
break;
}
}
spin_unlock_bh(&mvm->time_event_lock);
if (!mvmvif) {
IWL_WARN(mvm, "P2P_DEVICE no remain on channel event\n");
return;
}
iwl_mvm_remove_time_event(mvm, mvmvif, te_data);
iwl_mvm_roc_finished(mvm);
}
| ziqiaozhou/cachebar | source/drivers/net/wireless/iwlwifi/mvm/time-event.c | C | gpl-2.0 | 19,552 |
/*
** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
**
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of version 2 of the GNU Library General
** Public License as published by the Free Software Foundation.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Library General Public License for more details. To obtain a
** copy of the GNU Library General Public License, write to the Free
** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
** Any permitted reproduction of these routines, in whole or in part,
** must bear this legend.
**
**
** version.h
**
** Program name / version definitions
** $Id: version.h,v 1.7 2000/07/04 04:46:55 matt Exp $
*/
#ifndef _VERSION_H_
#define _VERSION_H_
#ifdef NSF_PLAYER
#define APP_STRING "Nosefart"
#else
#define APP_STRING "Nofrendo"
#endif /* NSF_PLAYER */
#define APP_VERSION "1.92"
#endif /* _VERSION_H_ */
/*
** $Log: version.h,v $
** Revision 1.7 2000/07/04 04:46:55 matt
** updated version number
**
** Revision 1.6 2000/06/20 00:03:39 matt
** updated for 1.91
**
** Revision 1.5 2000/06/09 17:01:56 matt
** changed version to 1.90
**
** Revision 1.4 2000/06/09 15:12:25 matt
** initial revision
**
*/
| xbmc/atv2 | xbmc/cores/paplayer/NSFCodec/src/version.h | C | gpl-2.0 | 1,421 |
/*
* Copyright (c) 2005-2011 Atheros Communications Inc.
* Copyright (c) 2011-2013 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "mac.h"
#include <net/mac80211.h>
#include <linux/etherdevice.h>
#include "hif.h"
#include "core.h"
#include "debug.h"
#include "wmi.h"
#include "htt.h"
#include "txrx.h"
#include "testmode.h"
#include "wmi.h"
#include "wmi-tlv.h"
#include "wmi-ops.h"
#include "wow.h"
/*********/
/* Rates */
/*********/
static struct ieee80211_rate ath10k_rates[] = {
{ .bitrate = 10,
.hw_value = ATH10K_HW_RATE_CCK_LP_1M },
{ .bitrate = 20,
.hw_value = ATH10K_HW_RATE_CCK_LP_2M,
.hw_value_short = ATH10K_HW_RATE_CCK_SP_2M,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 55,
.hw_value = ATH10K_HW_RATE_CCK_LP_5_5M,
.hw_value_short = ATH10K_HW_RATE_CCK_SP_5_5M,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 110,
.hw_value = ATH10K_HW_RATE_CCK_LP_11M,
.hw_value_short = ATH10K_HW_RATE_CCK_SP_11M,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 60, .hw_value = ATH10K_HW_RATE_OFDM_6M },
{ .bitrate = 90, .hw_value = ATH10K_HW_RATE_OFDM_9M },
{ .bitrate = 120, .hw_value = ATH10K_HW_RATE_OFDM_12M },
{ .bitrate = 180, .hw_value = ATH10K_HW_RATE_OFDM_18M },
{ .bitrate = 240, .hw_value = ATH10K_HW_RATE_OFDM_24M },
{ .bitrate = 360, .hw_value = ATH10K_HW_RATE_OFDM_36M },
{ .bitrate = 480, .hw_value = ATH10K_HW_RATE_OFDM_48M },
{ .bitrate = 540, .hw_value = ATH10K_HW_RATE_OFDM_54M },
};
#define ATH10K_MAC_FIRST_OFDM_RATE_IDX 4
#define ath10k_a_rates (ath10k_rates + ATH10K_MAC_FIRST_OFDM_RATE_IDX)
#define ath10k_a_rates_size (ARRAY_SIZE(ath10k_rates) - \
ATH10K_MAC_FIRST_OFDM_RATE_IDX)
#define ath10k_g_rates (ath10k_rates + 0)
#define ath10k_g_rates_size (ARRAY_SIZE(ath10k_rates))
static bool ath10k_mac_bitrate_is_cck(int bitrate)
{
switch (bitrate) {
case 10:
case 20:
case 55:
case 110:
return true;
}
return false;
}
static u8 ath10k_mac_bitrate_to_rate(int bitrate)
{
return DIV_ROUND_UP(bitrate, 5) |
(ath10k_mac_bitrate_is_cck(bitrate) ? BIT(7) : 0);
}
u8 ath10k_mac_hw_rate_to_idx(const struct ieee80211_supported_band *sband,
u8 hw_rate)
{
const struct ieee80211_rate *rate;
int i;
for (i = 0; i < sband->n_bitrates; i++) {
rate = &sband->bitrates[i];
if (rate->hw_value == hw_rate)
return i;
else if (rate->flags & IEEE80211_RATE_SHORT_PREAMBLE &&
rate->hw_value_short == hw_rate)
return i;
}
return 0;
}
u8 ath10k_mac_bitrate_to_idx(const struct ieee80211_supported_band *sband,
u32 bitrate)
{
int i;
for (i = 0; i < sband->n_bitrates; i++)
if (sband->bitrates[i].bitrate == bitrate)
return i;
return 0;
}
static int ath10k_mac_get_max_vht_mcs_map(u16 mcs_map, int nss)
{
switch ((mcs_map >> (2 * nss)) & 0x3) {
case IEEE80211_VHT_MCS_SUPPORT_0_7: return BIT(8) - 1;
case IEEE80211_VHT_MCS_SUPPORT_0_8: return BIT(9) - 1;
case IEEE80211_VHT_MCS_SUPPORT_0_9: return BIT(10) - 1;
}
return 0;
}
static u32
ath10k_mac_max_ht_nss(const u8 ht_mcs_mask[IEEE80211_HT_MCS_MASK_LEN])
{
int nss;
for (nss = IEEE80211_HT_MCS_MASK_LEN - 1; nss >= 0; nss--)
if (ht_mcs_mask[nss])
return nss + 1;
return 1;
}
static u32
ath10k_mac_max_vht_nss(const u16 vht_mcs_mask[NL80211_VHT_NSS_MAX])
{
int nss;
for (nss = NL80211_VHT_NSS_MAX - 1; nss >= 0; nss--)
if (vht_mcs_mask[nss])
return nss + 1;
return 1;
}
/**********/
/* Crypto */
/**********/
static int ath10k_send_key(struct ath10k_vif *arvif,
struct ieee80211_key_conf *key,
enum set_key_cmd cmd,
const u8 *macaddr, u32 flags)
{
struct ath10k *ar = arvif->ar;
struct wmi_vdev_install_key_arg arg = {
.vdev_id = arvif->vdev_id,
.key_idx = key->keyidx,
.key_len = key->keylen,
.key_data = key->key,
.key_flags = flags,
.macaddr = macaddr,
};
lockdep_assert_held(&arvif->ar->conf_mutex);
switch (key->cipher) {
case WLAN_CIPHER_SUITE_CCMP:
arg.key_cipher = WMI_CIPHER_AES_CCM;
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV_MGMT;
break;
case WLAN_CIPHER_SUITE_TKIP:
arg.key_cipher = WMI_CIPHER_TKIP;
arg.key_txmic_len = 8;
arg.key_rxmic_len = 8;
break;
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
arg.key_cipher = WMI_CIPHER_WEP;
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
WARN_ON(1);
return -EINVAL;
default:
ath10k_warn(ar, "cipher %d is not supported\n", key->cipher);
return -EOPNOTSUPP;
}
if (test_bit(ATH10K_FLAG_RAW_MODE, &ar->dev_flags))
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
if (cmd == DISABLE_KEY) {
arg.key_cipher = WMI_CIPHER_NONE;
arg.key_data = NULL;
}
return ath10k_wmi_vdev_install_key(arvif->ar, &arg);
}
static int ath10k_install_key(struct ath10k_vif *arvif,
struct ieee80211_key_conf *key,
enum set_key_cmd cmd,
const u8 *macaddr, u32 flags)
{
struct ath10k *ar = arvif->ar;
int ret;
unsigned long time_left;
lockdep_assert_held(&ar->conf_mutex);
reinit_completion(&ar->install_key_done);
if (arvif->nohwcrypt)
return 1;
ret = ath10k_send_key(arvif, key, cmd, macaddr, flags);
if (ret)
return ret;
time_left = wait_for_completion_timeout(&ar->install_key_done, 3 * HZ);
if (time_left == 0)
return -ETIMEDOUT;
return 0;
}
static int ath10k_install_peer_wep_keys(struct ath10k_vif *arvif,
const u8 *addr)
{
struct ath10k *ar = arvif->ar;
struct ath10k_peer *peer;
int ret;
int i;
u32 flags;
lockdep_assert_held(&ar->conf_mutex);
if (WARN_ON(arvif->vif->type != NL80211_IFTYPE_AP &&
arvif->vif->type != NL80211_IFTYPE_ADHOC))
return -EINVAL;
spin_lock_bh(&ar->data_lock);
peer = ath10k_peer_find(ar, arvif->vdev_id, addr);
spin_unlock_bh(&ar->data_lock);
if (!peer)
return -ENOENT;
for (i = 0; i < ARRAY_SIZE(arvif->wep_keys); i++) {
if (arvif->wep_keys[i] == NULL)
continue;
switch (arvif->vif->type) {
case NL80211_IFTYPE_AP:
flags = WMI_KEY_PAIRWISE;
if (arvif->def_wep_key_idx == i)
flags |= WMI_KEY_TX_USAGE;
ret = ath10k_install_key(arvif, arvif->wep_keys[i],
SET_KEY, addr, flags);
if (ret < 0)
return ret;
break;
case NL80211_IFTYPE_ADHOC:
ret = ath10k_install_key(arvif, arvif->wep_keys[i],
SET_KEY, addr,
WMI_KEY_PAIRWISE);
if (ret < 0)
return ret;
ret = ath10k_install_key(arvif, arvif->wep_keys[i],
SET_KEY, addr, WMI_KEY_GROUP);
if (ret < 0)
return ret;
break;
default:
WARN_ON(1);
return -EINVAL;
}
spin_lock_bh(&ar->data_lock);
peer->keys[i] = arvif->wep_keys[i];
spin_unlock_bh(&ar->data_lock);
}
/* In some cases (notably with static WEP IBSS with multiple keys)
* multicast Tx becomes broken. Both pairwise and groupwise keys are
* installed already. Using WMI_KEY_TX_USAGE in different combinations
* didn't seem help. Using def_keyid vdev parameter seems to be
* effective so use that.
*
* FIXME: Revisit. Perhaps this can be done in a less hacky way.
*/
if (arvif->vif->type != NL80211_IFTYPE_ADHOC)
return 0;
if (arvif->def_wep_key_idx == -1)
return 0;
ret = ath10k_wmi_vdev_set_param(arvif->ar,
arvif->vdev_id,
arvif->ar->wmi.vdev_param->def_keyid,
arvif->def_wep_key_idx);
if (ret) {
ath10k_warn(ar, "failed to re-set def wpa key idxon vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
return 0;
}
static int ath10k_clear_peer_keys(struct ath10k_vif *arvif,
const u8 *addr)
{
struct ath10k *ar = arvif->ar;
struct ath10k_peer *peer;
int first_errno = 0;
int ret;
int i;
u32 flags = 0;
lockdep_assert_held(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
peer = ath10k_peer_find(ar, arvif->vdev_id, addr);
spin_unlock_bh(&ar->data_lock);
if (!peer)
return -ENOENT;
for (i = 0; i < ARRAY_SIZE(peer->keys); i++) {
if (peer->keys[i] == NULL)
continue;
/* key flags are not required to delete the key */
ret = ath10k_install_key(arvif, peer->keys[i],
DISABLE_KEY, addr, flags);
if (ret < 0 && first_errno == 0)
first_errno = ret;
if (ret < 0)
ath10k_warn(ar, "failed to remove peer wep key %d: %d\n",
i, ret);
spin_lock_bh(&ar->data_lock);
peer->keys[i] = NULL;
spin_unlock_bh(&ar->data_lock);
}
return first_errno;
}
bool ath10k_mac_is_peer_wep_key_set(struct ath10k *ar, const u8 *addr,
u8 keyidx)
{
struct ath10k_peer *peer;
int i;
lockdep_assert_held(&ar->data_lock);
/* We don't know which vdev this peer belongs to,
* since WMI doesn't give us that information.
*
* FIXME: multi-bss needs to be handled.
*/
peer = ath10k_peer_find(ar, 0, addr);
if (!peer)
return false;
for (i = 0; i < ARRAY_SIZE(peer->keys); i++) {
if (peer->keys[i] && peer->keys[i]->keyidx == keyidx)
return true;
}
return false;
}
static int ath10k_clear_vdev_key(struct ath10k_vif *arvif,
struct ieee80211_key_conf *key)
{
struct ath10k *ar = arvif->ar;
struct ath10k_peer *peer;
u8 addr[ETH_ALEN];
int first_errno = 0;
int ret;
int i;
u32 flags = 0;
lockdep_assert_held(&ar->conf_mutex);
for (;;) {
/* since ath10k_install_key we can't hold data_lock all the
* time, so we try to remove the keys incrementally */
spin_lock_bh(&ar->data_lock);
i = 0;
list_for_each_entry(peer, &ar->peers, list) {
for (i = 0; i < ARRAY_SIZE(peer->keys); i++) {
if (peer->keys[i] == key) {
ether_addr_copy(addr, peer->addr);
peer->keys[i] = NULL;
break;
}
}
if (i < ARRAY_SIZE(peer->keys))
break;
}
spin_unlock_bh(&ar->data_lock);
if (i == ARRAY_SIZE(peer->keys))
break;
/* key flags are not required to delete the key */
ret = ath10k_install_key(arvif, key, DISABLE_KEY, addr, flags);
if (ret < 0 && first_errno == 0)
first_errno = ret;
if (ret)
ath10k_warn(ar, "failed to remove key for %pM: %d\n",
addr, ret);
}
return first_errno;
}
static int ath10k_mac_vif_update_wep_key(struct ath10k_vif *arvif,
struct ieee80211_key_conf *key)
{
struct ath10k *ar = arvif->ar;
struct ath10k_peer *peer;
int ret;
lockdep_assert_held(&ar->conf_mutex);
list_for_each_entry(peer, &ar->peers, list) {
if (!memcmp(peer->addr, arvif->vif->addr, ETH_ALEN))
continue;
if (!memcmp(peer->addr, arvif->bssid, ETH_ALEN))
continue;
if (peer->keys[key->keyidx] == key)
continue;
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vif vdev %i update key %i needs update\n",
arvif->vdev_id, key->keyidx);
ret = ath10k_install_peer_wep_keys(arvif, peer->addr);
if (ret) {
ath10k_warn(ar, "failed to update wep keys on vdev %i for peer %pM: %d\n",
arvif->vdev_id, peer->addr, ret);
return ret;
}
}
return 0;
}
/*********************/
/* General utilities */
/*********************/
static inline enum wmi_phy_mode
chan_to_phymode(const struct cfg80211_chan_def *chandef)
{
enum wmi_phy_mode phymode = MODE_UNKNOWN;
switch (chandef->chan->band) {
case IEEE80211_BAND_2GHZ:
switch (chandef->width) {
case NL80211_CHAN_WIDTH_20_NOHT:
if (chandef->chan->flags & IEEE80211_CHAN_NO_OFDM)
phymode = MODE_11B;
else
phymode = MODE_11G;
break;
case NL80211_CHAN_WIDTH_20:
phymode = MODE_11NG_HT20;
break;
case NL80211_CHAN_WIDTH_40:
phymode = MODE_11NG_HT40;
break;
case NL80211_CHAN_WIDTH_5:
case NL80211_CHAN_WIDTH_10:
case NL80211_CHAN_WIDTH_80:
case NL80211_CHAN_WIDTH_80P80:
case NL80211_CHAN_WIDTH_160:
phymode = MODE_UNKNOWN;
break;
}
break;
case IEEE80211_BAND_5GHZ:
switch (chandef->width) {
case NL80211_CHAN_WIDTH_20_NOHT:
phymode = MODE_11A;
break;
case NL80211_CHAN_WIDTH_20:
phymode = MODE_11NA_HT20;
break;
case NL80211_CHAN_WIDTH_40:
phymode = MODE_11NA_HT40;
break;
case NL80211_CHAN_WIDTH_80:
phymode = MODE_11AC_VHT80;
break;
case NL80211_CHAN_WIDTH_5:
case NL80211_CHAN_WIDTH_10:
case NL80211_CHAN_WIDTH_80P80:
case NL80211_CHAN_WIDTH_160:
phymode = MODE_UNKNOWN;
break;
}
break;
default:
break;
}
WARN_ON(phymode == MODE_UNKNOWN);
return phymode;
}
static u8 ath10k_parse_mpdudensity(u8 mpdudensity)
{
/*
* 802.11n D2.0 defined values for "Minimum MPDU Start Spacing":
* 0 for no restriction
* 1 for 1/4 us
* 2 for 1/2 us
* 3 for 1 us
* 4 for 2 us
* 5 for 4 us
* 6 for 8 us
* 7 for 16 us
*/
switch (mpdudensity) {
case 0:
return 0;
case 1:
case 2:
case 3:
/* Our lower layer calculations limit our precision to
1 microsecond */
return 1;
case 4:
return 2;
case 5:
return 4;
case 6:
return 8;
case 7:
return 16;
default:
return 0;
}
}
int ath10k_mac_vif_chan(struct ieee80211_vif *vif,
struct cfg80211_chan_def *def)
{
struct ieee80211_chanctx_conf *conf;
rcu_read_lock();
conf = rcu_dereference(vif->chanctx_conf);
if (!conf) {
rcu_read_unlock();
return -ENOENT;
}
*def = conf->def;
rcu_read_unlock();
return 0;
}
static void ath10k_mac_num_chanctxs_iter(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *conf,
void *data)
{
int *num = data;
(*num)++;
}
static int ath10k_mac_num_chanctxs(struct ath10k *ar)
{
int num = 0;
ieee80211_iter_chan_contexts_atomic(ar->hw,
ath10k_mac_num_chanctxs_iter,
&num);
return num;
}
static void
ath10k_mac_get_any_chandef_iter(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *conf,
void *data)
{
struct cfg80211_chan_def **def = data;
*def = &conf->def;
}
static int ath10k_peer_create(struct ath10k *ar, u32 vdev_id, const u8 *addr,
enum wmi_peer_type peer_type)
{
struct ath10k_vif *arvif;
int num_peers = 0;
int ret;
lockdep_assert_held(&ar->conf_mutex);
num_peers = ar->num_peers;
/* Each vdev consumes a peer entry as well */
list_for_each_entry(arvif, &ar->arvifs, list)
num_peers++;
if (num_peers >= ar->max_num_peers)
return -ENOBUFS;
ret = ath10k_wmi_peer_create(ar, vdev_id, addr, peer_type);
if (ret) {
ath10k_warn(ar, "failed to create wmi peer %pM on vdev %i: %i\n",
addr, vdev_id, ret);
return ret;
}
ret = ath10k_wait_for_peer_created(ar, vdev_id, addr);
if (ret) {
ath10k_warn(ar, "failed to wait for created wmi peer %pM on vdev %i: %i\n",
addr, vdev_id, ret);
return ret;
}
ar->num_peers++;
return 0;
}
static int ath10k_mac_set_kickout(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
u32 param;
int ret;
param = ar->wmi.pdev_param->sta_kickout_th;
ret = ath10k_wmi_pdev_set_param(ar, param,
ATH10K_KICKOUT_THRESHOLD);
if (ret) {
ath10k_warn(ar, "failed to set kickout threshold on vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
param = ar->wmi.vdev_param->ap_keepalive_min_idle_inactive_time_secs;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, param,
ATH10K_KEEPALIVE_MIN_IDLE);
if (ret) {
ath10k_warn(ar, "failed to set keepalive minimum idle time on vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
param = ar->wmi.vdev_param->ap_keepalive_max_idle_inactive_time_secs;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, param,
ATH10K_KEEPALIVE_MAX_IDLE);
if (ret) {
ath10k_warn(ar, "failed to set keepalive maximum idle time on vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
param = ar->wmi.vdev_param->ap_keepalive_max_unresponsive_time_secs;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, param,
ATH10K_KEEPALIVE_MAX_UNRESPONSIVE);
if (ret) {
ath10k_warn(ar, "failed to set keepalive maximum unresponsive time on vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
return 0;
}
static int ath10k_mac_set_rts(struct ath10k_vif *arvif, u32 value)
{
struct ath10k *ar = arvif->ar;
u32 vdev_param;
vdev_param = ar->wmi.vdev_param->rts_threshold;
return ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param, value);
}
static int ath10k_peer_delete(struct ath10k *ar, u32 vdev_id, const u8 *addr)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_wmi_peer_delete(ar, vdev_id, addr);
if (ret)
return ret;
ret = ath10k_wait_for_peer_deleted(ar, vdev_id, addr);
if (ret)
return ret;
ar->num_peers--;
return 0;
}
static void ath10k_peer_cleanup(struct ath10k *ar, u32 vdev_id)
{
struct ath10k_peer *peer, *tmp;
lockdep_assert_held(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
list_for_each_entry_safe(peer, tmp, &ar->peers, list) {
if (peer->vdev_id != vdev_id)
continue;
ath10k_warn(ar, "removing stale peer %pM from vdev_id %d\n",
peer->addr, vdev_id);
list_del(&peer->list);
kfree(peer);
ar->num_peers--;
}
spin_unlock_bh(&ar->data_lock);
}
static void ath10k_peer_cleanup_all(struct ath10k *ar)
{
struct ath10k_peer *peer, *tmp;
lockdep_assert_held(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
list_for_each_entry_safe(peer, tmp, &ar->peers, list) {
list_del(&peer->list);
kfree(peer);
}
spin_unlock_bh(&ar->data_lock);
ar->num_peers = 0;
ar->num_stations = 0;
}
static int ath10k_mac_tdls_peer_update(struct ath10k *ar, u32 vdev_id,
struct ieee80211_sta *sta,
enum wmi_tdls_peer_state state)
{
int ret;
struct wmi_tdls_peer_update_cmd_arg arg = {};
struct wmi_tdls_peer_capab_arg cap = {};
struct wmi_channel_arg chan_arg = {};
lockdep_assert_held(&ar->conf_mutex);
arg.vdev_id = vdev_id;
arg.peer_state = state;
ether_addr_copy(arg.addr, sta->addr);
cap.peer_max_sp = sta->max_sp;
cap.peer_uapsd_queues = sta->uapsd_queues;
if (state == WMI_TDLS_PEER_STATE_CONNECTED &&
!sta->tdls_initiator)
cap.is_peer_responder = 1;
ret = ath10k_wmi_tdls_peer_update(ar, &arg, &cap, &chan_arg);
if (ret) {
ath10k_warn(ar, "failed to update tdls peer %pM on vdev %i: %i\n",
arg.addr, vdev_id, ret);
return ret;
}
return 0;
}
/************************/
/* Interface management */
/************************/
void ath10k_mac_vif_beacon_free(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
lockdep_assert_held(&ar->data_lock);
if (!arvif->beacon)
return;
if (!arvif->beacon_buf)
dma_unmap_single(ar->dev, ATH10K_SKB_CB(arvif->beacon)->paddr,
arvif->beacon->len, DMA_TO_DEVICE);
if (WARN_ON(arvif->beacon_state != ATH10K_BEACON_SCHEDULED &&
arvif->beacon_state != ATH10K_BEACON_SENT))
return;
dev_kfree_skb_any(arvif->beacon);
arvif->beacon = NULL;
arvif->beacon_state = ATH10K_BEACON_SCHEDULED;
}
static void ath10k_mac_vif_beacon_cleanup(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
lockdep_assert_held(&ar->data_lock);
ath10k_mac_vif_beacon_free(arvif);
if (arvif->beacon_buf) {
dma_free_coherent(ar->dev, IEEE80211_MAX_FRAME_LEN,
arvif->beacon_buf, arvif->beacon_paddr);
arvif->beacon_buf = NULL;
}
}
static inline int ath10k_vdev_setup_sync(struct ath10k *ar)
{
unsigned long time_left;
lockdep_assert_held(&ar->conf_mutex);
if (test_bit(ATH10K_FLAG_CRASH_FLUSH, &ar->dev_flags))
return -ESHUTDOWN;
time_left = wait_for_completion_timeout(&ar->vdev_setup_done,
ATH10K_VDEV_SETUP_TIMEOUT_HZ);
if (time_left == 0)
return -ETIMEDOUT;
return 0;
}
static int ath10k_monitor_vdev_start(struct ath10k *ar, int vdev_id)
{
struct cfg80211_chan_def *chandef = NULL;
struct ieee80211_channel *channel = NULL;
struct wmi_vdev_start_request_arg arg = {};
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
ieee80211_iter_chan_contexts_atomic(ar->hw,
ath10k_mac_get_any_chandef_iter,
&chandef);
if (WARN_ON_ONCE(!chandef))
return -ENOENT;
channel = chandef->chan;
arg.vdev_id = vdev_id;
arg.channel.freq = channel->center_freq;
arg.channel.band_center_freq1 = chandef->center_freq1;
/* TODO setup this dynamically, what in case we
don't have any vifs? */
arg.channel.mode = chan_to_phymode(chandef);
arg.channel.chan_radar =
!!(channel->flags & IEEE80211_CHAN_RADAR);
arg.channel.min_power = 0;
arg.channel.max_power = channel->max_power * 2;
arg.channel.max_reg_power = channel->max_reg_power * 2;
arg.channel.max_antenna_gain = channel->max_antenna_gain * 2;
reinit_completion(&ar->vdev_setup_done);
ret = ath10k_wmi_vdev_start(ar, &arg);
if (ret) {
ath10k_warn(ar, "failed to request monitor vdev %i start: %d\n",
vdev_id, ret);
return ret;
}
ret = ath10k_vdev_setup_sync(ar);
if (ret) {
ath10k_warn(ar, "failed to synchronize setup for monitor vdev %i start: %d\n",
vdev_id, ret);
return ret;
}
ret = ath10k_wmi_vdev_up(ar, vdev_id, 0, ar->mac_addr);
if (ret) {
ath10k_warn(ar, "failed to put up monitor vdev %i: %d\n",
vdev_id, ret);
goto vdev_stop;
}
ar->monitor_vdev_id = vdev_id;
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac monitor vdev %i started\n",
ar->monitor_vdev_id);
return 0;
vdev_stop:
ret = ath10k_wmi_vdev_stop(ar, ar->monitor_vdev_id);
if (ret)
ath10k_warn(ar, "failed to stop monitor vdev %i after start failure: %d\n",
ar->monitor_vdev_id, ret);
return ret;
}
static int ath10k_monitor_vdev_stop(struct ath10k *ar)
{
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_wmi_vdev_down(ar, ar->monitor_vdev_id);
if (ret)
ath10k_warn(ar, "failed to put down monitor vdev %i: %d\n",
ar->monitor_vdev_id, ret);
reinit_completion(&ar->vdev_setup_done);
ret = ath10k_wmi_vdev_stop(ar, ar->monitor_vdev_id);
if (ret)
ath10k_warn(ar, "failed to to request monitor vdev %i stop: %d\n",
ar->monitor_vdev_id, ret);
ret = ath10k_vdev_setup_sync(ar);
if (ret)
ath10k_warn(ar, "failed to synchronize monitor vdev %i stop: %d\n",
ar->monitor_vdev_id, ret);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac monitor vdev %i stopped\n",
ar->monitor_vdev_id);
return ret;
}
static int ath10k_monitor_vdev_create(struct ath10k *ar)
{
int bit, ret = 0;
lockdep_assert_held(&ar->conf_mutex);
if (ar->free_vdev_map == 0) {
ath10k_warn(ar, "failed to find free vdev id for monitor vdev\n");
return -ENOMEM;
}
bit = __ffs64(ar->free_vdev_map);
ar->monitor_vdev_id = bit;
ret = ath10k_wmi_vdev_create(ar, ar->monitor_vdev_id,
WMI_VDEV_TYPE_MONITOR,
0, ar->mac_addr);
if (ret) {
ath10k_warn(ar, "failed to request monitor vdev %i creation: %d\n",
ar->monitor_vdev_id, ret);
return ret;
}
ar->free_vdev_map &= ~(1LL << ar->monitor_vdev_id);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac monitor vdev %d created\n",
ar->monitor_vdev_id);
return 0;
}
static int ath10k_monitor_vdev_delete(struct ath10k *ar)
{
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_wmi_vdev_delete(ar, ar->monitor_vdev_id);
if (ret) {
ath10k_warn(ar, "failed to request wmi monitor vdev %i removal: %d\n",
ar->monitor_vdev_id, ret);
return ret;
}
ar->free_vdev_map |= 1LL << ar->monitor_vdev_id;
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac monitor vdev %d deleted\n",
ar->monitor_vdev_id);
return ret;
}
static int ath10k_monitor_start(struct ath10k *ar)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_monitor_vdev_create(ar);
if (ret) {
ath10k_warn(ar, "failed to create monitor vdev: %d\n", ret);
return ret;
}
ret = ath10k_monitor_vdev_start(ar, ar->monitor_vdev_id);
if (ret) {
ath10k_warn(ar, "failed to start monitor vdev: %d\n", ret);
ath10k_monitor_vdev_delete(ar);
return ret;
}
ar->monitor_started = true;
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac monitor started\n");
return 0;
}
static int ath10k_monitor_stop(struct ath10k *ar)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_monitor_vdev_stop(ar);
if (ret) {
ath10k_warn(ar, "failed to stop monitor vdev: %d\n", ret);
return ret;
}
ret = ath10k_monitor_vdev_delete(ar);
if (ret) {
ath10k_warn(ar, "failed to delete monitor vdev: %d\n", ret);
return ret;
}
ar->monitor_started = false;
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac monitor stopped\n");
return 0;
}
static bool ath10k_mac_monitor_vdev_is_needed(struct ath10k *ar)
{
int num_ctx;
/* At least one chanctx is required to derive a channel to start
* monitor vdev on.
*/
num_ctx = ath10k_mac_num_chanctxs(ar);
if (num_ctx == 0)
return false;
/* If there's already an existing special monitor interface then don't
* bother creating another monitor vdev.
*/
if (ar->monitor_arvif)
return false;
return ar->monitor ||
ar->filter_flags & FIF_OTHER_BSS ||
test_bit(ATH10K_CAC_RUNNING, &ar->dev_flags);
}
static bool ath10k_mac_monitor_vdev_is_allowed(struct ath10k *ar)
{
int num_ctx;
num_ctx = ath10k_mac_num_chanctxs(ar);
/* FIXME: Current interface combinations and cfg80211/mac80211 code
* shouldn't allow this but make sure to prevent handling the following
* case anyway since multi-channel DFS hasn't been tested at all.
*/
if (test_bit(ATH10K_CAC_RUNNING, &ar->dev_flags) && num_ctx > 1)
return false;
return true;
}
static int ath10k_monitor_recalc(struct ath10k *ar)
{
bool needed;
bool allowed;
int ret;
lockdep_assert_held(&ar->conf_mutex);
needed = ath10k_mac_monitor_vdev_is_needed(ar);
allowed = ath10k_mac_monitor_vdev_is_allowed(ar);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac monitor recalc started? %d needed? %d allowed? %d\n",
ar->monitor_started, needed, allowed);
if (WARN_ON(needed && !allowed)) {
if (ar->monitor_started) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac monitor stopping disallowed monitor\n");
ret = ath10k_monitor_stop(ar);
if (ret)
ath10k_warn(ar, "failed to stop disallowed monitor: %d\n",
ret);
/* not serious */
}
return -EPERM;
}
if (needed == ar->monitor_started)
return 0;
if (needed)
return ath10k_monitor_start(ar);
else
return ath10k_monitor_stop(ar);
}
static int ath10k_recalc_rtscts_prot(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
u32 vdev_param, rts_cts = 0;
lockdep_assert_held(&ar->conf_mutex);
vdev_param = ar->wmi.vdev_param->enable_rtscts;
rts_cts |= SM(WMI_RTSCTS_ENABLED, WMI_RTSCTS_SET);
if (arvif->num_legacy_stations > 0)
rts_cts |= SM(WMI_RTSCTS_ACROSS_SW_RETRIES,
WMI_RTSCTS_PROFILE);
else
rts_cts |= SM(WMI_RTSCTS_FOR_SECOND_RATESERIES,
WMI_RTSCTS_PROFILE);
return ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
rts_cts);
}
static int ath10k_start_cac(struct ath10k *ar)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
set_bit(ATH10K_CAC_RUNNING, &ar->dev_flags);
ret = ath10k_monitor_recalc(ar);
if (ret) {
ath10k_warn(ar, "failed to start monitor (cac): %d\n", ret);
clear_bit(ATH10K_CAC_RUNNING, &ar->dev_flags);
return ret;
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac cac start monitor vdev %d\n",
ar->monitor_vdev_id);
return 0;
}
static int ath10k_stop_cac(struct ath10k *ar)
{
lockdep_assert_held(&ar->conf_mutex);
/* CAC is not running - do nothing */
if (!test_bit(ATH10K_CAC_RUNNING, &ar->dev_flags))
return 0;
clear_bit(ATH10K_CAC_RUNNING, &ar->dev_flags);
ath10k_monitor_stop(ar);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac cac finished\n");
return 0;
}
static void ath10k_mac_has_radar_iter(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *conf,
void *data)
{
bool *ret = data;
if (!*ret && conf->radar_enabled)
*ret = true;
}
static bool ath10k_mac_has_radar_enabled(struct ath10k *ar)
{
bool has_radar = false;
ieee80211_iter_chan_contexts_atomic(ar->hw,
ath10k_mac_has_radar_iter,
&has_radar);
return has_radar;
}
static void ath10k_recalc_radar_detection(struct ath10k *ar)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
ath10k_stop_cac(ar);
if (!ath10k_mac_has_radar_enabled(ar))
return;
if (ar->num_started_vdevs > 0)
return;
ret = ath10k_start_cac(ar);
if (ret) {
/*
* Not possible to start CAC on current channel so starting
* radiation is not allowed, make this channel DFS_UNAVAILABLE
* by indicating that radar was detected.
*/
ath10k_warn(ar, "failed to start CAC: %d\n", ret);
ieee80211_radar_detected(ar->hw);
}
}
static int ath10k_vdev_stop(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
int ret;
lockdep_assert_held(&ar->conf_mutex);
reinit_completion(&ar->vdev_setup_done);
ret = ath10k_wmi_vdev_stop(ar, arvif->vdev_id);
if (ret) {
ath10k_warn(ar, "failed to stop WMI vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
ret = ath10k_vdev_setup_sync(ar);
if (ret) {
ath10k_warn(ar, "failed to syncronise setup for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
WARN_ON(ar->num_started_vdevs == 0);
if (ar->num_started_vdevs != 0) {
ar->num_started_vdevs--;
ath10k_recalc_radar_detection(ar);
}
return ret;
}
static int ath10k_vdev_start_restart(struct ath10k_vif *arvif,
const struct cfg80211_chan_def *chandef,
bool restart)
{
struct ath10k *ar = arvif->ar;
struct wmi_vdev_start_request_arg arg = {};
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
reinit_completion(&ar->vdev_setup_done);
arg.vdev_id = arvif->vdev_id;
arg.dtim_period = arvif->dtim_period;
arg.bcn_intval = arvif->beacon_interval;
arg.channel.freq = chandef->chan->center_freq;
arg.channel.band_center_freq1 = chandef->center_freq1;
arg.channel.mode = chan_to_phymode(chandef);
arg.channel.min_power = 0;
arg.channel.max_power = chandef->chan->max_power * 2;
arg.channel.max_reg_power = chandef->chan->max_reg_power * 2;
arg.channel.max_antenna_gain = chandef->chan->max_antenna_gain * 2;
if (arvif->vdev_type == WMI_VDEV_TYPE_AP) {
arg.ssid = arvif->u.ap.ssid;
arg.ssid_len = arvif->u.ap.ssid_len;
arg.hidden_ssid = arvif->u.ap.hidden_ssid;
/* For now allow DFS for AP mode */
arg.channel.chan_radar =
!!(chandef->chan->flags & IEEE80211_CHAN_RADAR);
} else if (arvif->vdev_type == WMI_VDEV_TYPE_IBSS) {
arg.ssid = arvif->vif->bss_conf.ssid;
arg.ssid_len = arvif->vif->bss_conf.ssid_len;
}
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac vdev %d start center_freq %d phymode %s\n",
arg.vdev_id, arg.channel.freq,
ath10k_wmi_phymode_str(arg.channel.mode));
if (restart)
ret = ath10k_wmi_vdev_restart(ar, &arg);
else
ret = ath10k_wmi_vdev_start(ar, &arg);
if (ret) {
ath10k_warn(ar, "failed to start WMI vdev %i: %d\n",
arg.vdev_id, ret);
return ret;
}
ret = ath10k_vdev_setup_sync(ar);
if (ret) {
ath10k_warn(ar,
"failed to synchronize setup for vdev %i restart %d: %d\n",
arg.vdev_id, restart, ret);
return ret;
}
ar->num_started_vdevs++;
ath10k_recalc_radar_detection(ar);
return ret;
}
static int ath10k_vdev_start(struct ath10k_vif *arvif,
const struct cfg80211_chan_def *def)
{
return ath10k_vdev_start_restart(arvif, def, false);
}
static int ath10k_vdev_restart(struct ath10k_vif *arvif,
const struct cfg80211_chan_def *def)
{
return ath10k_vdev_start_restart(arvif, def, true);
}
static int ath10k_mac_setup_bcn_p2p_ie(struct ath10k_vif *arvif,
struct sk_buff *bcn)
{
struct ath10k *ar = arvif->ar;
struct ieee80211_mgmt *mgmt;
const u8 *p2p_ie;
int ret;
if (arvif->vdev_type != WMI_VDEV_TYPE_AP)
return 0;
if (arvif->vdev_subtype != WMI_VDEV_SUBTYPE_P2P_GO)
return 0;
mgmt = (void *)bcn->data;
p2p_ie = cfg80211_find_vendor_ie(WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P,
mgmt->u.beacon.variable,
bcn->len - (mgmt->u.beacon.variable -
bcn->data));
if (!p2p_ie)
return -ENOENT;
ret = ath10k_wmi_p2p_go_bcn_ie(ar, arvif->vdev_id, p2p_ie);
if (ret) {
ath10k_warn(ar, "failed to submit p2p go bcn ie for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
return 0;
}
static int ath10k_mac_remove_vendor_ie(struct sk_buff *skb, unsigned int oui,
u8 oui_type, size_t ie_offset)
{
size_t len;
const u8 *next;
const u8 *end;
u8 *ie;
if (WARN_ON(skb->len < ie_offset))
return -EINVAL;
ie = (u8 *)cfg80211_find_vendor_ie(oui, oui_type,
skb->data + ie_offset,
skb->len - ie_offset);
if (!ie)
return -ENOENT;
len = ie[1] + 2;
end = skb->data + skb->len;
next = ie + len;
if (WARN_ON(next > end))
return -EINVAL;
memmove(ie, next, end - next);
skb_trim(skb, skb->len - len);
return 0;
}
static int ath10k_mac_setup_bcn_tmpl(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
struct ieee80211_hw *hw = ar->hw;
struct ieee80211_vif *vif = arvif->vif;
struct ieee80211_mutable_offsets offs = {};
struct sk_buff *bcn;
int ret;
if (!test_bit(WMI_SERVICE_BEACON_OFFLOAD, ar->wmi.svc_map))
return 0;
if (arvif->vdev_type != WMI_VDEV_TYPE_AP &&
arvif->vdev_type != WMI_VDEV_TYPE_IBSS)
return 0;
bcn = ieee80211_beacon_get_template(hw, vif, &offs);
if (!bcn) {
ath10k_warn(ar, "failed to get beacon template from mac80211\n");
return -EPERM;
}
ret = ath10k_mac_setup_bcn_p2p_ie(arvif, bcn);
if (ret) {
ath10k_warn(ar, "failed to setup p2p go bcn ie: %d\n", ret);
kfree_skb(bcn);
return ret;
}
/* P2P IE is inserted by firmware automatically (as configured above)
* so remove it from the base beacon template to avoid duplicate P2P
* IEs in beacon frames.
*/
ath10k_mac_remove_vendor_ie(bcn, WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P,
offsetof(struct ieee80211_mgmt,
u.beacon.variable));
ret = ath10k_wmi_bcn_tmpl(ar, arvif->vdev_id, offs.tim_offset, bcn, 0,
0, NULL, 0);
kfree_skb(bcn);
if (ret) {
ath10k_warn(ar, "failed to submit beacon template command: %d\n",
ret);
return ret;
}
return 0;
}
static int ath10k_mac_setup_prb_tmpl(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
struct ieee80211_hw *hw = ar->hw;
struct ieee80211_vif *vif = arvif->vif;
struct sk_buff *prb;
int ret;
if (!test_bit(WMI_SERVICE_BEACON_OFFLOAD, ar->wmi.svc_map))
return 0;
if (arvif->vdev_type != WMI_VDEV_TYPE_AP)
return 0;
prb = ieee80211_proberesp_get(hw, vif);
if (!prb) {
ath10k_warn(ar, "failed to get probe resp template from mac80211\n");
return -EPERM;
}
ret = ath10k_wmi_prb_tmpl(ar, arvif->vdev_id, prb);
kfree_skb(prb);
if (ret) {
ath10k_warn(ar, "failed to submit probe resp template command: %d\n",
ret);
return ret;
}
return 0;
}
static int ath10k_mac_vif_fix_hidden_ssid(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
struct cfg80211_chan_def def;
int ret;
/* When originally vdev is started during assign_vif_chanctx() some
* information is missing, notably SSID. Firmware revisions with beacon
* offloading require the SSID to be provided during vdev (re)start to
* handle hidden SSID properly.
*
* Vdev restart must be done after vdev has been both started and
* upped. Otherwise some firmware revisions (at least 10.2) fail to
* deliver vdev restart response event causing timeouts during vdev
* syncing in ath10k.
*
* Note: The vdev down/up and template reinstallation could be skipped
* since only wmi-tlv firmware are known to have beacon offload and
* wmi-tlv doesn't seem to misbehave like 10.2 wrt vdev restart
* response delivery. It's probably more robust to keep it as is.
*/
if (!test_bit(WMI_SERVICE_BEACON_OFFLOAD, ar->wmi.svc_map))
return 0;
if (WARN_ON(!arvif->is_started))
return -EINVAL;
if (WARN_ON(!arvif->is_up))
return -EINVAL;
if (WARN_ON(ath10k_mac_vif_chan(arvif->vif, &def)))
return -EINVAL;
ret = ath10k_wmi_vdev_down(ar, arvif->vdev_id);
if (ret) {
ath10k_warn(ar, "failed to bring down ap vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
/* Vdev down reset beacon & presp templates. Reinstall them. Otherwise
* firmware will crash upon vdev up.
*/
ret = ath10k_mac_setup_bcn_tmpl(arvif);
if (ret) {
ath10k_warn(ar, "failed to update beacon template: %d\n", ret);
return ret;
}
ret = ath10k_mac_setup_prb_tmpl(arvif);
if (ret) {
ath10k_warn(ar, "failed to update presp template: %d\n", ret);
return ret;
}
ret = ath10k_vdev_restart(arvif, &def);
if (ret) {
ath10k_warn(ar, "failed to restart ap vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
ret = ath10k_wmi_vdev_up(arvif->ar, arvif->vdev_id, arvif->aid,
arvif->bssid);
if (ret) {
ath10k_warn(ar, "failed to bring up ap vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
return 0;
}
static void ath10k_control_beaconing(struct ath10k_vif *arvif,
struct ieee80211_bss_conf *info)
{
struct ath10k *ar = arvif->ar;
int ret = 0;
lockdep_assert_held(&arvif->ar->conf_mutex);
if (!info->enable_beacon) {
ret = ath10k_wmi_vdev_down(ar, arvif->vdev_id);
if (ret)
ath10k_warn(ar, "failed to down vdev_id %i: %d\n",
arvif->vdev_id, ret);
arvif->is_up = false;
spin_lock_bh(&arvif->ar->data_lock);
ath10k_mac_vif_beacon_free(arvif);
spin_unlock_bh(&arvif->ar->data_lock);
return;
}
arvif->tx_seq_no = 0x1000;
arvif->aid = 0;
ether_addr_copy(arvif->bssid, info->bssid);
ret = ath10k_wmi_vdev_up(arvif->ar, arvif->vdev_id, arvif->aid,
arvif->bssid);
if (ret) {
ath10k_warn(ar, "failed to bring up vdev %d: %i\n",
arvif->vdev_id, ret);
return;
}
arvif->is_up = true;
ret = ath10k_mac_vif_fix_hidden_ssid(arvif);
if (ret) {
ath10k_warn(ar, "failed to fix hidden ssid for vdev %i, expect trouble: %d\n",
arvif->vdev_id, ret);
return;
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %d up\n", arvif->vdev_id);
}
static void ath10k_control_ibss(struct ath10k_vif *arvif,
struct ieee80211_bss_conf *info,
const u8 self_peer[ETH_ALEN])
{
struct ath10k *ar = arvif->ar;
u32 vdev_param;
int ret = 0;
lockdep_assert_held(&arvif->ar->conf_mutex);
if (!info->ibss_joined) {
if (is_zero_ether_addr(arvif->bssid))
return;
eth_zero_addr(arvif->bssid);
return;
}
vdev_param = arvif->ar->wmi.vdev_param->atim_window;
ret = ath10k_wmi_vdev_set_param(arvif->ar, arvif->vdev_id, vdev_param,
ATH10K_DEFAULT_ATIM);
if (ret)
ath10k_warn(ar, "failed to set IBSS ATIM for vdev %d: %d\n",
arvif->vdev_id, ret);
}
static int ath10k_mac_vif_recalc_ps_wake_threshold(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
u32 param;
u32 value;
int ret;
lockdep_assert_held(&arvif->ar->conf_mutex);
if (arvif->u.sta.uapsd)
value = WMI_STA_PS_TX_WAKE_THRESHOLD_NEVER;
else
value = WMI_STA_PS_TX_WAKE_THRESHOLD_ALWAYS;
param = WMI_STA_PS_PARAM_TX_WAKE_THRESHOLD;
ret = ath10k_wmi_set_sta_ps_param(ar, arvif->vdev_id, param, value);
if (ret) {
ath10k_warn(ar, "failed to submit ps wake threshold %u on vdev %i: %d\n",
value, arvif->vdev_id, ret);
return ret;
}
return 0;
}
static int ath10k_mac_vif_recalc_ps_poll_count(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
u32 param;
u32 value;
int ret;
lockdep_assert_held(&arvif->ar->conf_mutex);
if (arvif->u.sta.uapsd)
value = WMI_STA_PS_PSPOLL_COUNT_UAPSD;
else
value = WMI_STA_PS_PSPOLL_COUNT_NO_MAX;
param = WMI_STA_PS_PARAM_PSPOLL_COUNT;
ret = ath10k_wmi_set_sta_ps_param(ar, arvif->vdev_id,
param, value);
if (ret) {
ath10k_warn(ar, "failed to submit ps poll count %u on vdev %i: %d\n",
value, arvif->vdev_id, ret);
return ret;
}
return 0;
}
static int ath10k_mac_num_vifs_started(struct ath10k *ar)
{
struct ath10k_vif *arvif;
int num = 0;
lockdep_assert_held(&ar->conf_mutex);
list_for_each_entry(arvif, &ar->arvifs, list)
if (arvif->is_started)
num++;
return num;
}
static int ath10k_mac_vif_setup_ps(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
struct ieee80211_vif *vif = arvif->vif;
struct ieee80211_conf *conf = &ar->hw->conf;
enum wmi_sta_powersave_param param;
enum wmi_sta_ps_mode psmode;
int ret;
int ps_timeout;
bool enable_ps;
lockdep_assert_held(&arvif->ar->conf_mutex);
if (arvif->vif->type != NL80211_IFTYPE_STATION)
return 0;
enable_ps = arvif->ps;
if (enable_ps && ath10k_mac_num_vifs_started(ar) > 1 &&
!test_bit(ATH10K_FW_FEATURE_MULTI_VIF_PS_SUPPORT,
ar->fw_features)) {
ath10k_warn(ar, "refusing to enable ps on vdev %i: not supported by fw\n",
arvif->vdev_id);
enable_ps = false;
}
if (!arvif->is_started) {
/* mac80211 can update vif powersave state while disconnected.
* Firmware doesn't behave nicely and consumes more power than
* necessary if PS is disabled on a non-started vdev. Hence
* force-enable PS for non-running vdevs.
*/
psmode = WMI_STA_PS_MODE_ENABLED;
} else if (enable_ps) {
psmode = WMI_STA_PS_MODE_ENABLED;
param = WMI_STA_PS_PARAM_INACTIVITY_TIME;
ps_timeout = conf->dynamic_ps_timeout;
if (ps_timeout == 0) {
/* Firmware doesn't like 0 */
ps_timeout = ieee80211_tu_to_usec(
vif->bss_conf.beacon_int) / 1000;
}
ret = ath10k_wmi_set_sta_ps_param(ar, arvif->vdev_id, param,
ps_timeout);
if (ret) {
ath10k_warn(ar, "failed to set inactivity time for vdev %d: %i\n",
arvif->vdev_id, ret);
return ret;
}
} else {
psmode = WMI_STA_PS_MODE_DISABLED;
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %d psmode %s\n",
arvif->vdev_id, psmode ? "enable" : "disable");
ret = ath10k_wmi_set_psmode(ar, arvif->vdev_id, psmode);
if (ret) {
ath10k_warn(ar, "failed to set PS Mode %d for vdev %d: %d\n",
psmode, arvif->vdev_id, ret);
return ret;
}
return 0;
}
static int ath10k_mac_vif_disable_keepalive(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
struct wmi_sta_keepalive_arg arg = {};
int ret;
lockdep_assert_held(&arvif->ar->conf_mutex);
if (arvif->vdev_type != WMI_VDEV_TYPE_STA)
return 0;
if (!test_bit(WMI_SERVICE_STA_KEEP_ALIVE, ar->wmi.svc_map))
return 0;
/* Some firmware revisions have a bug and ignore the `enabled` field.
* Instead use the interval to disable the keepalive.
*/
arg.vdev_id = arvif->vdev_id;
arg.enabled = 1;
arg.method = WMI_STA_KEEPALIVE_METHOD_NULL_FRAME;
arg.interval = WMI_STA_KEEPALIVE_INTERVAL_DISABLE;
ret = ath10k_wmi_sta_keepalive(ar, &arg);
if (ret) {
ath10k_warn(ar, "failed to submit keepalive on vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
return 0;
}
static void ath10k_mac_vif_ap_csa_count_down(struct ath10k_vif *arvif)
{
struct ath10k *ar = arvif->ar;
struct ieee80211_vif *vif = arvif->vif;
int ret;
lockdep_assert_held(&arvif->ar->conf_mutex);
if (WARN_ON(!test_bit(WMI_SERVICE_BEACON_OFFLOAD, ar->wmi.svc_map)))
return;
if (arvif->vdev_type != WMI_VDEV_TYPE_AP)
return;
if (!vif->csa_active)
return;
if (!arvif->is_up)
return;
if (!ieee80211_csa_is_complete(vif)) {
ieee80211_csa_update_counter(vif);
ret = ath10k_mac_setup_bcn_tmpl(arvif);
if (ret)
ath10k_warn(ar, "failed to update bcn tmpl during csa: %d\n",
ret);
ret = ath10k_mac_setup_prb_tmpl(arvif);
if (ret)
ath10k_warn(ar, "failed to update prb tmpl during csa: %d\n",
ret);
} else {
ieee80211_csa_finish(vif);
}
}
static void ath10k_mac_vif_ap_csa_work(struct work_struct *work)
{
struct ath10k_vif *arvif = container_of(work, struct ath10k_vif,
ap_csa_work);
struct ath10k *ar = arvif->ar;
mutex_lock(&ar->conf_mutex);
ath10k_mac_vif_ap_csa_count_down(arvif);
mutex_unlock(&ar->conf_mutex);
}
static void ath10k_mac_handle_beacon_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct sk_buff *skb = data;
struct ieee80211_mgmt *mgmt = (void *)skb->data;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
if (vif->type != NL80211_IFTYPE_STATION)
return;
if (!ether_addr_equal(mgmt->bssid, vif->bss_conf.bssid))
return;
cancel_delayed_work(&arvif->connection_loss_work);
}
void ath10k_mac_handle_beacon(struct ath10k *ar, struct sk_buff *skb)
{
ieee80211_iterate_active_interfaces_atomic(ar->hw,
IEEE80211_IFACE_ITER_NORMAL,
ath10k_mac_handle_beacon_iter,
skb);
}
static void ath10k_mac_handle_beacon_miss_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
u32 *vdev_id = data;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct ath10k *ar = arvif->ar;
struct ieee80211_hw *hw = ar->hw;
if (arvif->vdev_id != *vdev_id)
return;
if (!arvif->is_up)
return;
ieee80211_beacon_loss(vif);
/* Firmware doesn't report beacon loss events repeatedly. If AP probe
* (done by mac80211) succeeds but beacons do not resume then it
* doesn't make sense to continue operation. Queue connection loss work
* which can be cancelled when beacon is received.
*/
ieee80211_queue_delayed_work(hw, &arvif->connection_loss_work,
ATH10K_CONNECTION_LOSS_HZ);
}
void ath10k_mac_handle_beacon_miss(struct ath10k *ar, u32 vdev_id)
{
ieee80211_iterate_active_interfaces_atomic(ar->hw,
IEEE80211_IFACE_ITER_NORMAL,
ath10k_mac_handle_beacon_miss_iter,
&vdev_id);
}
static void ath10k_mac_vif_sta_connection_loss_work(struct work_struct *work)
{
struct ath10k_vif *arvif = container_of(work, struct ath10k_vif,
connection_loss_work.work);
struct ieee80211_vif *vif = arvif->vif;
if (!arvif->is_up)
return;
ieee80211_connection_loss(vif);
}
/**********************/
/* Station management */
/**********************/
static u32 ath10k_peer_assoc_h_listen_intval(struct ath10k *ar,
struct ieee80211_vif *vif)
{
/* Some firmware revisions have unstable STA powersave when listen
* interval is set too high (e.g. 5). The symptoms are firmware doesn't
* generate NullFunc frames properly even if buffered frames have been
* indicated in Beacon TIM. Firmware would seldom wake up to pull
* buffered frames. Often pinging the device from AP would simply fail.
*
* As a workaround set it to 1.
*/
if (vif->type == NL80211_IFTYPE_STATION)
return 1;
return ar->hw->conf.listen_interval;
}
static void ath10k_peer_assoc_h_basic(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wmi_peer_assoc_complete_arg *arg)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
u32 aid;
lockdep_assert_held(&ar->conf_mutex);
if (vif->type == NL80211_IFTYPE_STATION)
aid = vif->bss_conf.aid;
else
aid = sta->aid;
ether_addr_copy(arg->addr, sta->addr);
arg->vdev_id = arvif->vdev_id;
arg->peer_aid = aid;
arg->peer_flags |= WMI_PEER_AUTH;
arg->peer_listen_intval = ath10k_peer_assoc_h_listen_intval(ar, vif);
arg->peer_num_spatial_streams = 1;
arg->peer_caps = vif->bss_conf.assoc_capability;
}
static void ath10k_peer_assoc_h_crypto(struct ath10k *ar,
struct ieee80211_vif *vif,
struct wmi_peer_assoc_complete_arg *arg)
{
struct ieee80211_bss_conf *info = &vif->bss_conf;
struct cfg80211_chan_def def;
struct cfg80211_bss *bss;
const u8 *rsnie = NULL;
const u8 *wpaie = NULL;
lockdep_assert_held(&ar->conf_mutex);
if (WARN_ON(ath10k_mac_vif_chan(vif, &def)))
return;
bss = cfg80211_get_bss(ar->hw->wiphy, def.chan, info->bssid, NULL, 0,
IEEE80211_BSS_TYPE_ANY, IEEE80211_PRIVACY_ANY);
if (bss) {
const struct cfg80211_bss_ies *ies;
rcu_read_lock();
rsnie = ieee80211_bss_get_ie(bss, WLAN_EID_RSN);
ies = rcu_dereference(bss->ies);
wpaie = cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT,
WLAN_OUI_TYPE_MICROSOFT_WPA,
ies->data,
ies->len);
rcu_read_unlock();
cfg80211_put_bss(ar->hw->wiphy, bss);
}
/* FIXME: base on RSN IE/WPA IE is a correct idea? */
if (rsnie || wpaie) {
ath10k_dbg(ar, ATH10K_DBG_WMI, "%s: rsn ie found\n", __func__);
arg->peer_flags |= WMI_PEER_NEED_PTK_4_WAY;
}
if (wpaie) {
ath10k_dbg(ar, ATH10K_DBG_WMI, "%s: wpa ie found\n", __func__);
arg->peer_flags |= WMI_PEER_NEED_GTK_2_WAY;
}
}
static void ath10k_peer_assoc_h_rates(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wmi_peer_assoc_complete_arg *arg)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct wmi_rate_set_arg *rateset = &arg->peer_legacy_rates;
struct cfg80211_chan_def def;
const struct ieee80211_supported_band *sband;
const struct ieee80211_rate *rates;
enum ieee80211_band band;
u32 ratemask;
u8 rate;
int i;
lockdep_assert_held(&ar->conf_mutex);
if (WARN_ON(ath10k_mac_vif_chan(vif, &def)))
return;
band = def.chan->band;
sband = ar->hw->wiphy->bands[band];
ratemask = sta->supp_rates[band];
ratemask &= arvif->bitrate_mask.control[band].legacy;
rates = sband->bitrates;
rateset->num_rates = 0;
for (i = 0; i < 32; i++, ratemask >>= 1, rates++) {
if (!(ratemask & 1))
continue;
rate = ath10k_mac_bitrate_to_rate(rates->bitrate);
rateset->rates[rateset->num_rates] = rate;
rateset->num_rates++;
}
}
static bool
ath10k_peer_assoc_h_ht_masked(const u8 ht_mcs_mask[IEEE80211_HT_MCS_MASK_LEN])
{
int nss;
for (nss = 0; nss < IEEE80211_HT_MCS_MASK_LEN; nss++)
if (ht_mcs_mask[nss])
return false;
return true;
}
static bool
ath10k_peer_assoc_h_vht_masked(const u16 vht_mcs_mask[NL80211_VHT_NSS_MAX])
{
int nss;
for (nss = 0; nss < NL80211_VHT_NSS_MAX; nss++)
if (vht_mcs_mask[nss])
return false;
return true;
}
static void ath10k_peer_assoc_h_ht(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wmi_peer_assoc_complete_arg *arg)
{
const struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct cfg80211_chan_def def;
enum ieee80211_band band;
const u8 *ht_mcs_mask;
const u16 *vht_mcs_mask;
int i, n;
u8 max_nss;
u32 stbc;
lockdep_assert_held(&ar->conf_mutex);
if (WARN_ON(ath10k_mac_vif_chan(vif, &def)))
return;
if (!ht_cap->ht_supported)
return;
band = def.chan->band;
ht_mcs_mask = arvif->bitrate_mask.control[band].ht_mcs;
vht_mcs_mask = arvif->bitrate_mask.control[band].vht_mcs;
if (ath10k_peer_assoc_h_ht_masked(ht_mcs_mask) &&
ath10k_peer_assoc_h_vht_masked(vht_mcs_mask))
return;
arg->peer_flags |= WMI_PEER_HT;
arg->peer_max_mpdu = (1 << (IEEE80211_HT_MAX_AMPDU_FACTOR +
ht_cap->ampdu_factor)) - 1;
arg->peer_mpdu_density =
ath10k_parse_mpdudensity(ht_cap->ampdu_density);
arg->peer_ht_caps = ht_cap->cap;
arg->peer_rate_caps |= WMI_RC_HT_FLAG;
if (ht_cap->cap & IEEE80211_HT_CAP_LDPC_CODING)
arg->peer_flags |= WMI_PEER_LDPC;
if (sta->bandwidth >= IEEE80211_STA_RX_BW_40) {
arg->peer_flags |= WMI_PEER_40MHZ;
arg->peer_rate_caps |= WMI_RC_CW40_FLAG;
}
if (arvif->bitrate_mask.control[band].gi != NL80211_TXRATE_FORCE_LGI) {
if (ht_cap->cap & IEEE80211_HT_CAP_SGI_20)
arg->peer_rate_caps |= WMI_RC_SGI_FLAG;
if (ht_cap->cap & IEEE80211_HT_CAP_SGI_40)
arg->peer_rate_caps |= WMI_RC_SGI_FLAG;
}
if (ht_cap->cap & IEEE80211_HT_CAP_TX_STBC) {
arg->peer_rate_caps |= WMI_RC_TX_STBC_FLAG;
arg->peer_flags |= WMI_PEER_STBC;
}
if (ht_cap->cap & IEEE80211_HT_CAP_RX_STBC) {
stbc = ht_cap->cap & IEEE80211_HT_CAP_RX_STBC;
stbc = stbc >> IEEE80211_HT_CAP_RX_STBC_SHIFT;
stbc = stbc << WMI_RC_RX_STBC_FLAG_S;
arg->peer_rate_caps |= stbc;
arg->peer_flags |= WMI_PEER_STBC;
}
if (ht_cap->mcs.rx_mask[1] && ht_cap->mcs.rx_mask[2])
arg->peer_rate_caps |= WMI_RC_TS_FLAG;
else if (ht_cap->mcs.rx_mask[1])
arg->peer_rate_caps |= WMI_RC_DS_FLAG;
for (i = 0, n = 0, max_nss = 0; i < IEEE80211_HT_MCS_MASK_LEN * 8; i++)
if ((ht_cap->mcs.rx_mask[i / 8] & BIT(i % 8)) &&
(ht_mcs_mask[i / 8] & BIT(i % 8))) {
max_nss = (i / 8) + 1;
arg->peer_ht_rates.rates[n++] = i;
}
/*
* This is a workaround for HT-enabled STAs which break the spec
* and have no HT capabilities RX mask (no HT RX MCS map).
*
* As per spec, in section 20.3.5 Modulation and coding scheme (MCS),
* MCS 0 through 7 are mandatory in 20MHz with 800 ns GI at all STAs.
*
* Firmware asserts if such situation occurs.
*/
if (n == 0) {
arg->peer_ht_rates.num_rates = 8;
for (i = 0; i < arg->peer_ht_rates.num_rates; i++)
arg->peer_ht_rates.rates[i] = i;
} else {
arg->peer_ht_rates.num_rates = n;
arg->peer_num_spatial_streams = min(sta->rx_nss, max_nss);
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac ht peer %pM mcs cnt %d nss %d\n",
arg->addr,
arg->peer_ht_rates.num_rates,
arg->peer_num_spatial_streams);
}
static int ath10k_peer_assoc_qos_ap(struct ath10k *ar,
struct ath10k_vif *arvif,
struct ieee80211_sta *sta)
{
u32 uapsd = 0;
u32 max_sp = 0;
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
if (sta->wme && sta->uapsd_queues) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac uapsd_queues 0x%x max_sp %d\n",
sta->uapsd_queues, sta->max_sp);
if (sta->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VO)
uapsd |= WMI_AP_PS_UAPSD_AC3_DELIVERY_EN |
WMI_AP_PS_UAPSD_AC3_TRIGGER_EN;
if (sta->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VI)
uapsd |= WMI_AP_PS_UAPSD_AC2_DELIVERY_EN |
WMI_AP_PS_UAPSD_AC2_TRIGGER_EN;
if (sta->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_BK)
uapsd |= WMI_AP_PS_UAPSD_AC1_DELIVERY_EN |
WMI_AP_PS_UAPSD_AC1_TRIGGER_EN;
if (sta->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_BE)
uapsd |= WMI_AP_PS_UAPSD_AC0_DELIVERY_EN |
WMI_AP_PS_UAPSD_AC0_TRIGGER_EN;
if (sta->max_sp < MAX_WMI_AP_PS_PEER_PARAM_MAX_SP)
max_sp = sta->max_sp;
ret = ath10k_wmi_set_ap_ps_param(ar, arvif->vdev_id,
sta->addr,
WMI_AP_PS_PEER_PARAM_UAPSD,
uapsd);
if (ret) {
ath10k_warn(ar, "failed to set ap ps peer param uapsd for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
ret = ath10k_wmi_set_ap_ps_param(ar, arvif->vdev_id,
sta->addr,
WMI_AP_PS_PEER_PARAM_MAX_SP,
max_sp);
if (ret) {
ath10k_warn(ar, "failed to set ap ps peer param max sp for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
/* TODO setup this based on STA listen interval and
beacon interval. Currently we don't know
sta->listen_interval - mac80211 patch required.
Currently use 10 seconds */
ret = ath10k_wmi_set_ap_ps_param(ar, arvif->vdev_id, sta->addr,
WMI_AP_PS_PEER_PARAM_AGEOUT_TIME,
10);
if (ret) {
ath10k_warn(ar, "failed to set ap ps peer param ageout time for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
}
return 0;
}
static u16
ath10k_peer_assoc_h_vht_limit(u16 tx_mcs_set,
const u16 vht_mcs_limit[NL80211_VHT_NSS_MAX])
{
int idx_limit;
int nss;
u16 mcs_map;
u16 mcs;
for (nss = 0; nss < NL80211_VHT_NSS_MAX; nss++) {
mcs_map = ath10k_mac_get_max_vht_mcs_map(tx_mcs_set, nss) &
vht_mcs_limit[nss];
if (mcs_map)
idx_limit = fls(mcs_map) - 1;
else
idx_limit = -1;
switch (idx_limit) {
case 0: /* fall through */
case 1: /* fall through */
case 2: /* fall through */
case 3: /* fall through */
case 4: /* fall through */
case 5: /* fall through */
case 6: /* fall through */
default:
/* see ath10k_mac_can_set_bitrate_mask() */
WARN_ON(1);
/* fall through */
case -1:
mcs = IEEE80211_VHT_MCS_NOT_SUPPORTED;
break;
case 7:
mcs = IEEE80211_VHT_MCS_SUPPORT_0_7;
break;
case 8:
mcs = IEEE80211_VHT_MCS_SUPPORT_0_8;
break;
case 9:
mcs = IEEE80211_VHT_MCS_SUPPORT_0_9;
break;
}
tx_mcs_set &= ~(0x3 << (nss * 2));
tx_mcs_set |= mcs << (nss * 2);
}
return tx_mcs_set;
}
static void ath10k_peer_assoc_h_vht(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wmi_peer_assoc_complete_arg *arg)
{
const struct ieee80211_sta_vht_cap *vht_cap = &sta->vht_cap;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct cfg80211_chan_def def;
enum ieee80211_band band;
const u16 *vht_mcs_mask;
u8 ampdu_factor;
if (WARN_ON(ath10k_mac_vif_chan(vif, &def)))
return;
if (!vht_cap->vht_supported)
return;
band = def.chan->band;
vht_mcs_mask = arvif->bitrate_mask.control[band].vht_mcs;
if (ath10k_peer_assoc_h_vht_masked(vht_mcs_mask))
return;
arg->peer_flags |= WMI_PEER_VHT;
if (def.chan->band == IEEE80211_BAND_2GHZ)
arg->peer_flags |= WMI_PEER_VHT_2G;
arg->peer_vht_caps = vht_cap->cap;
ampdu_factor = (vht_cap->cap &
IEEE80211_VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_MASK) >>
IEEE80211_VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_SHIFT;
/* Workaround: Some Netgear/Linksys 11ac APs set Rx A-MPDU factor to
* zero in VHT IE. Using it would result in degraded throughput.
* arg->peer_max_mpdu at this point contains HT max_mpdu so keep
* it if VHT max_mpdu is smaller. */
arg->peer_max_mpdu = max(arg->peer_max_mpdu,
(1U << (IEEE80211_HT_MAX_AMPDU_FACTOR +
ampdu_factor)) - 1);
if (sta->bandwidth == IEEE80211_STA_RX_BW_80)
arg->peer_flags |= WMI_PEER_80MHZ;
arg->peer_vht_rates.rx_max_rate =
__le16_to_cpu(vht_cap->vht_mcs.rx_highest);
arg->peer_vht_rates.rx_mcs_set =
__le16_to_cpu(vht_cap->vht_mcs.rx_mcs_map);
arg->peer_vht_rates.tx_max_rate =
__le16_to_cpu(vht_cap->vht_mcs.tx_highest);
arg->peer_vht_rates.tx_mcs_set = ath10k_peer_assoc_h_vht_limit(
__le16_to_cpu(vht_cap->vht_mcs.tx_mcs_map), vht_mcs_mask);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vht peer %pM max_mpdu %d flags 0x%x\n",
sta->addr, arg->peer_max_mpdu, arg->peer_flags);
}
static void ath10k_peer_assoc_h_qos(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wmi_peer_assoc_complete_arg *arg)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
switch (arvif->vdev_type) {
case WMI_VDEV_TYPE_AP:
if (sta->wme)
arg->peer_flags |= WMI_PEER_QOS;
if (sta->wme && sta->uapsd_queues) {
arg->peer_flags |= WMI_PEER_APSD;
arg->peer_rate_caps |= WMI_RC_UAPSD_FLAG;
}
break;
case WMI_VDEV_TYPE_STA:
if (vif->bss_conf.qos)
arg->peer_flags |= WMI_PEER_QOS;
break;
case WMI_VDEV_TYPE_IBSS:
if (sta->wme)
arg->peer_flags |= WMI_PEER_QOS;
break;
default:
break;
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac peer %pM qos %d\n",
sta->addr, !!(arg->peer_flags & WMI_PEER_QOS));
}
static bool ath10k_mac_sta_has_ofdm_only(struct ieee80211_sta *sta)
{
return sta->supp_rates[IEEE80211_BAND_2GHZ] >>
ATH10K_MAC_FIRST_OFDM_RATE_IDX;
}
static void ath10k_peer_assoc_h_phymode(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wmi_peer_assoc_complete_arg *arg)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct cfg80211_chan_def def;
enum ieee80211_band band;
const u8 *ht_mcs_mask;
const u16 *vht_mcs_mask;
enum wmi_phy_mode phymode = MODE_UNKNOWN;
if (WARN_ON(ath10k_mac_vif_chan(vif, &def)))
return;
band = def.chan->band;
ht_mcs_mask = arvif->bitrate_mask.control[band].ht_mcs;
vht_mcs_mask = arvif->bitrate_mask.control[band].vht_mcs;
switch (band) {
case IEEE80211_BAND_2GHZ:
if (sta->vht_cap.vht_supported &&
!ath10k_peer_assoc_h_vht_masked(vht_mcs_mask)) {
if (sta->bandwidth == IEEE80211_STA_RX_BW_40)
phymode = MODE_11AC_VHT40;
else
phymode = MODE_11AC_VHT20;
} else if (sta->ht_cap.ht_supported &&
!ath10k_peer_assoc_h_ht_masked(ht_mcs_mask)) {
if (sta->bandwidth == IEEE80211_STA_RX_BW_40)
phymode = MODE_11NG_HT40;
else
phymode = MODE_11NG_HT20;
} else if (ath10k_mac_sta_has_ofdm_only(sta)) {
phymode = MODE_11G;
} else {
phymode = MODE_11B;
}
break;
case IEEE80211_BAND_5GHZ:
/*
* Check VHT first.
*/
if (sta->vht_cap.vht_supported &&
!ath10k_peer_assoc_h_vht_masked(vht_mcs_mask)) {
if (sta->bandwidth == IEEE80211_STA_RX_BW_80)
phymode = MODE_11AC_VHT80;
else if (sta->bandwidth == IEEE80211_STA_RX_BW_40)
phymode = MODE_11AC_VHT40;
else if (sta->bandwidth == IEEE80211_STA_RX_BW_20)
phymode = MODE_11AC_VHT20;
} else if (sta->ht_cap.ht_supported &&
!ath10k_peer_assoc_h_ht_masked(ht_mcs_mask)) {
if (sta->bandwidth >= IEEE80211_STA_RX_BW_40)
phymode = MODE_11NA_HT40;
else
phymode = MODE_11NA_HT20;
} else {
phymode = MODE_11A;
}
break;
default:
break;
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac peer %pM phymode %s\n",
sta->addr, ath10k_wmi_phymode_str(phymode));
arg->peer_phymode = phymode;
WARN_ON(phymode == MODE_UNKNOWN);
}
static int ath10k_peer_assoc_prepare(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wmi_peer_assoc_complete_arg *arg)
{
lockdep_assert_held(&ar->conf_mutex);
memset(arg, 0, sizeof(*arg));
ath10k_peer_assoc_h_basic(ar, vif, sta, arg);
ath10k_peer_assoc_h_crypto(ar, vif, arg);
ath10k_peer_assoc_h_rates(ar, vif, sta, arg);
ath10k_peer_assoc_h_ht(ar, vif, sta, arg);
ath10k_peer_assoc_h_vht(ar, vif, sta, arg);
ath10k_peer_assoc_h_qos(ar, vif, sta, arg);
ath10k_peer_assoc_h_phymode(ar, vif, sta, arg);
return 0;
}
static const u32 ath10k_smps_map[] = {
[WLAN_HT_CAP_SM_PS_STATIC] = WMI_PEER_SMPS_STATIC,
[WLAN_HT_CAP_SM_PS_DYNAMIC] = WMI_PEER_SMPS_DYNAMIC,
[WLAN_HT_CAP_SM_PS_INVALID] = WMI_PEER_SMPS_PS_NONE,
[WLAN_HT_CAP_SM_PS_DISABLED] = WMI_PEER_SMPS_PS_NONE,
};
static int ath10k_setup_peer_smps(struct ath10k *ar, struct ath10k_vif *arvif,
const u8 *addr,
const struct ieee80211_sta_ht_cap *ht_cap)
{
int smps;
if (!ht_cap->ht_supported)
return 0;
smps = ht_cap->cap & IEEE80211_HT_CAP_SM_PS;
smps >>= IEEE80211_HT_CAP_SM_PS_SHIFT;
if (smps >= ARRAY_SIZE(ath10k_smps_map))
return -EINVAL;
return ath10k_wmi_peer_set_param(ar, arvif->vdev_id, addr,
WMI_PEER_SMPS_STATE,
ath10k_smps_map[smps]);
}
static int ath10k_mac_vif_recalc_txbf(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta_vht_cap vht_cap)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
int ret;
u32 param;
u32 value;
if (ath10k_wmi_get_txbf_conf_scheme(ar) != WMI_TXBF_CONF_AFTER_ASSOC)
return 0;
if (!(ar->vht_cap_info &
(IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE |
IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE)))
return 0;
param = ar->wmi.vdev_param->txbf;
value = 0;
if (WARN_ON(param == WMI_VDEV_PARAM_UNSUPPORTED))
return 0;
/* The following logic is correct. If a remote STA advertises support
* for being a beamformer then we should enable us being a beamformee.
*/
if (ar->vht_cap_info &
(IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE)) {
if (vht_cap.cap & IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE)
value |= WMI_VDEV_PARAM_TXBF_SU_TX_BFEE;
if (vht_cap.cap & IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE)
value |= WMI_VDEV_PARAM_TXBF_MU_TX_BFEE;
}
if (ar->vht_cap_info &
(IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE)) {
if (vht_cap.cap & IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE)
value |= WMI_VDEV_PARAM_TXBF_SU_TX_BFER;
if (vht_cap.cap & IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE)
value |= WMI_VDEV_PARAM_TXBF_MU_TX_BFER;
}
if (value & WMI_VDEV_PARAM_TXBF_MU_TX_BFEE)
value |= WMI_VDEV_PARAM_TXBF_SU_TX_BFEE;
if (value & WMI_VDEV_PARAM_TXBF_MU_TX_BFER)
value |= WMI_VDEV_PARAM_TXBF_SU_TX_BFER;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, param, value);
if (ret) {
ath10k_warn(ar, "failed to submit vdev param txbf 0x%x: %d\n",
value, ret);
return ret;
}
return 0;
}
/* can be called only in mac80211 callbacks due to `key_count` usage */
static void ath10k_bss_assoc(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct ieee80211_sta_ht_cap ht_cap;
struct ieee80211_sta_vht_cap vht_cap;
struct wmi_peer_assoc_complete_arg peer_arg;
struct ieee80211_sta *ap_sta;
int ret;
lockdep_assert_held(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %i assoc bssid %pM aid %d\n",
arvif->vdev_id, arvif->bssid, arvif->aid);
rcu_read_lock();
ap_sta = ieee80211_find_sta(vif, bss_conf->bssid);
if (!ap_sta) {
ath10k_warn(ar, "failed to find station entry for bss %pM vdev %i\n",
bss_conf->bssid, arvif->vdev_id);
rcu_read_unlock();
return;
}
/* ap_sta must be accessed only within rcu section which must be left
* before calling ath10k_setup_peer_smps() which might sleep. */
ht_cap = ap_sta->ht_cap;
vht_cap = ap_sta->vht_cap;
ret = ath10k_peer_assoc_prepare(ar, vif, ap_sta, &peer_arg);
if (ret) {
ath10k_warn(ar, "failed to prepare peer assoc for %pM vdev %i: %d\n",
bss_conf->bssid, arvif->vdev_id, ret);
rcu_read_unlock();
return;
}
rcu_read_unlock();
ret = ath10k_wmi_peer_assoc(ar, &peer_arg);
if (ret) {
ath10k_warn(ar, "failed to run peer assoc for %pM vdev %i: %d\n",
bss_conf->bssid, arvif->vdev_id, ret);
return;
}
ret = ath10k_setup_peer_smps(ar, arvif, bss_conf->bssid, &ht_cap);
if (ret) {
ath10k_warn(ar, "failed to setup peer SMPS for vdev %i: %d\n",
arvif->vdev_id, ret);
return;
}
ret = ath10k_mac_vif_recalc_txbf(ar, vif, vht_cap);
if (ret) {
ath10k_warn(ar, "failed to recalc txbf for vdev %i on bss %pM: %d\n",
arvif->vdev_id, bss_conf->bssid, ret);
return;
}
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac vdev %d up (associated) bssid %pM aid %d\n",
arvif->vdev_id, bss_conf->bssid, bss_conf->aid);
WARN_ON(arvif->is_up);
arvif->aid = bss_conf->aid;
ether_addr_copy(arvif->bssid, bss_conf->bssid);
ret = ath10k_wmi_vdev_up(ar, arvif->vdev_id, arvif->aid, arvif->bssid);
if (ret) {
ath10k_warn(ar, "failed to set vdev %d up: %d\n",
arvif->vdev_id, ret);
return;
}
arvif->is_up = true;
/* Workaround: Some firmware revisions (tested with qca6174
* WLAN.RM.2.0-00073) have buggy powersave state machine and must be
* poked with peer param command.
*/
ret = ath10k_wmi_peer_set_param(ar, arvif->vdev_id, arvif->bssid,
WMI_PEER_DUMMY_VAR, 1);
if (ret) {
ath10k_warn(ar, "failed to poke peer %pM param for ps workaround on vdev %i: %d\n",
arvif->bssid, arvif->vdev_id, ret);
return;
}
}
static void ath10k_bss_disassoc(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct ieee80211_sta_vht_cap vht_cap = {};
int ret;
lockdep_assert_held(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %i disassoc bssid %pM\n",
arvif->vdev_id, arvif->bssid);
ret = ath10k_wmi_vdev_down(ar, arvif->vdev_id);
if (ret)
ath10k_warn(ar, "faield to down vdev %i: %d\n",
arvif->vdev_id, ret);
arvif->def_wep_key_idx = -1;
ret = ath10k_mac_vif_recalc_txbf(ar, vif, vht_cap);
if (ret) {
ath10k_warn(ar, "failed to recalc txbf for vdev %i: %d\n",
arvif->vdev_id, ret);
return;
}
arvif->is_up = false;
cancel_delayed_work_sync(&arvif->connection_loss_work);
}
static int ath10k_station_assoc(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
bool reassoc)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct wmi_peer_assoc_complete_arg peer_arg;
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_peer_assoc_prepare(ar, vif, sta, &peer_arg);
if (ret) {
ath10k_warn(ar, "failed to prepare WMI peer assoc for %pM vdev %i: %i\n",
sta->addr, arvif->vdev_id, ret);
return ret;
}
ret = ath10k_wmi_peer_assoc(ar, &peer_arg);
if (ret) {
ath10k_warn(ar, "failed to run peer assoc for STA %pM vdev %i: %d\n",
sta->addr, arvif->vdev_id, ret);
return ret;
}
/* Re-assoc is run only to update supported rates for given station. It
* doesn't make much sense to reconfigure the peer completely.
*/
if (!reassoc) {
ret = ath10k_setup_peer_smps(ar, arvif, sta->addr,
&sta->ht_cap);
if (ret) {
ath10k_warn(ar, "failed to setup peer SMPS for vdev %d: %d\n",
arvif->vdev_id, ret);
return ret;
}
ret = ath10k_peer_assoc_qos_ap(ar, arvif, sta);
if (ret) {
ath10k_warn(ar, "failed to set qos params for STA %pM for vdev %i: %d\n",
sta->addr, arvif->vdev_id, ret);
return ret;
}
if (!sta->wme) {
arvif->num_legacy_stations++;
ret = ath10k_recalc_rtscts_prot(arvif);
if (ret) {
ath10k_warn(ar, "failed to recalculate rts/cts prot for vdev %d: %d\n",
arvif->vdev_id, ret);
return ret;
}
}
/* Plumb cached keys only for static WEP */
if (arvif->def_wep_key_idx != -1) {
ret = ath10k_install_peer_wep_keys(arvif, sta->addr);
if (ret) {
ath10k_warn(ar, "failed to install peer wep keys for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
}
}
return ret;
}
static int ath10k_station_disassoc(struct ath10k *ar,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
if (!sta->wme) {
arvif->num_legacy_stations--;
ret = ath10k_recalc_rtscts_prot(arvif);
if (ret) {
ath10k_warn(ar, "failed to recalculate rts/cts prot for vdev %d: %d\n",
arvif->vdev_id, ret);
return ret;
}
}
ret = ath10k_clear_peer_keys(arvif, sta->addr);
if (ret) {
ath10k_warn(ar, "failed to clear all peer wep keys for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
return ret;
}
/**************/
/* Regulatory */
/**************/
static int ath10k_update_channel_list(struct ath10k *ar)
{
struct ieee80211_hw *hw = ar->hw;
struct ieee80211_supported_band **bands;
enum ieee80211_band band;
struct ieee80211_channel *channel;
struct wmi_scan_chan_list_arg arg = {0};
struct wmi_channel_arg *ch;
bool passive;
int len;
int ret;
int i;
lockdep_assert_held(&ar->conf_mutex);
bands = hw->wiphy->bands;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (!bands[band])
continue;
for (i = 0; i < bands[band]->n_channels; i++) {
if (bands[band]->channels[i].flags &
IEEE80211_CHAN_DISABLED)
continue;
arg.n_channels++;
}
}
len = sizeof(struct wmi_channel_arg) * arg.n_channels;
arg.channels = kzalloc(len, GFP_KERNEL);
if (!arg.channels)
return -ENOMEM;
ch = arg.channels;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (!bands[band])
continue;
for (i = 0; i < bands[band]->n_channels; i++) {
channel = &bands[band]->channels[i];
if (channel->flags & IEEE80211_CHAN_DISABLED)
continue;
ch->allow_ht = true;
/* FIXME: when should we really allow VHT? */
ch->allow_vht = true;
ch->allow_ibss =
!(channel->flags & IEEE80211_CHAN_NO_IR);
ch->ht40plus =
!(channel->flags & IEEE80211_CHAN_NO_HT40PLUS);
ch->chan_radar =
!!(channel->flags & IEEE80211_CHAN_RADAR);
passive = channel->flags & IEEE80211_CHAN_NO_IR;
ch->passive = passive;
ch->freq = channel->center_freq;
ch->band_center_freq1 = channel->center_freq;
ch->min_power = 0;
ch->max_power = channel->max_power * 2;
ch->max_reg_power = channel->max_reg_power * 2;
ch->max_antenna_gain = channel->max_antenna_gain * 2;
ch->reg_class_id = 0; /* FIXME */
/* FIXME: why use only legacy modes, why not any
* HT/VHT modes? Would that even make any
* difference? */
if (channel->band == IEEE80211_BAND_2GHZ)
ch->mode = MODE_11G;
else
ch->mode = MODE_11A;
if (WARN_ON_ONCE(ch->mode == MODE_UNKNOWN))
continue;
ath10k_dbg(ar, ATH10K_DBG_WMI,
"mac channel [%zd/%d] freq %d maxpower %d regpower %d antenna %d mode %d\n",
ch - arg.channels, arg.n_channels,
ch->freq, ch->max_power, ch->max_reg_power,
ch->max_antenna_gain, ch->mode);
ch++;
}
}
ret = ath10k_wmi_scan_chan_list(ar, &arg);
kfree(arg.channels);
return ret;
}
static enum wmi_dfs_region
ath10k_mac_get_dfs_region(enum nl80211_dfs_regions dfs_region)
{
switch (dfs_region) {
case NL80211_DFS_UNSET:
return WMI_UNINIT_DFS_DOMAIN;
case NL80211_DFS_FCC:
return WMI_FCC_DFS_DOMAIN;
case NL80211_DFS_ETSI:
return WMI_ETSI_DFS_DOMAIN;
case NL80211_DFS_JP:
return WMI_MKK4_DFS_DOMAIN;
}
return WMI_UNINIT_DFS_DOMAIN;
}
static void ath10k_regd_update(struct ath10k *ar)
{
struct reg_dmn_pair_mapping *regpair;
int ret;
enum wmi_dfs_region wmi_dfs_reg;
enum nl80211_dfs_regions nl_dfs_reg;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_update_channel_list(ar);
if (ret)
ath10k_warn(ar, "failed to update channel list: %d\n", ret);
regpair = ar->ath_common.regulatory.regpair;
if (config_enabled(CONFIG_ATH10K_DFS_CERTIFIED) && ar->dfs_detector) {
nl_dfs_reg = ar->dfs_detector->region;
wmi_dfs_reg = ath10k_mac_get_dfs_region(nl_dfs_reg);
} else {
wmi_dfs_reg = WMI_UNINIT_DFS_DOMAIN;
}
/* Target allows setting up per-band regdomain but ath_common provides
* a combined one only */
ret = ath10k_wmi_pdev_set_regdomain(ar,
regpair->reg_domain,
regpair->reg_domain, /* 2ghz */
regpair->reg_domain, /* 5ghz */
regpair->reg_2ghz_ctl,
regpair->reg_5ghz_ctl,
wmi_dfs_reg);
if (ret)
ath10k_warn(ar, "failed to set pdev regdomain: %d\n", ret);
}
static void ath10k_reg_notifier(struct wiphy *wiphy,
struct regulatory_request *request)
{
struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
struct ath10k *ar = hw->priv;
bool result;
ath_reg_notifier_apply(wiphy, request, &ar->ath_common.regulatory);
if (config_enabled(CONFIG_ATH10K_DFS_CERTIFIED) && ar->dfs_detector) {
ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "dfs region 0x%x\n",
request->dfs_region);
result = ar->dfs_detector->set_dfs_domain(ar->dfs_detector,
request->dfs_region);
if (!result)
ath10k_warn(ar, "DFS region 0x%X not supported, will trigger radar for every pulse\n",
request->dfs_region);
}
mutex_lock(&ar->conf_mutex);
if (ar->state == ATH10K_STATE_ON)
ath10k_regd_update(ar);
mutex_unlock(&ar->conf_mutex);
}
/***************/
/* TX handlers */
/***************/
void ath10k_mac_tx_lock(struct ath10k *ar, int reason)
{
lockdep_assert_held(&ar->htt.tx_lock);
WARN_ON(reason >= ATH10K_TX_PAUSE_MAX);
ar->tx_paused |= BIT(reason);
ieee80211_stop_queues(ar->hw);
}
static void ath10k_mac_tx_unlock_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct ath10k *ar = data;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
if (arvif->tx_paused)
return;
ieee80211_wake_queue(ar->hw, arvif->vdev_id);
}
void ath10k_mac_tx_unlock(struct ath10k *ar, int reason)
{
lockdep_assert_held(&ar->htt.tx_lock);
WARN_ON(reason >= ATH10K_TX_PAUSE_MAX);
ar->tx_paused &= ~BIT(reason);
if (ar->tx_paused)
return;
ieee80211_iterate_active_interfaces_atomic(ar->hw,
IEEE80211_IFACE_ITER_RESUME_ALL,
ath10k_mac_tx_unlock_iter,
ar);
ieee80211_wake_queue(ar->hw, ar->hw->offchannel_tx_hw_queue);
}
void ath10k_mac_vif_tx_lock(struct ath10k_vif *arvif, int reason)
{
struct ath10k *ar = arvif->ar;
lockdep_assert_held(&ar->htt.tx_lock);
WARN_ON(reason >= BITS_PER_LONG);
arvif->tx_paused |= BIT(reason);
ieee80211_stop_queue(ar->hw, arvif->vdev_id);
}
void ath10k_mac_vif_tx_unlock(struct ath10k_vif *arvif, int reason)
{
struct ath10k *ar = arvif->ar;
lockdep_assert_held(&ar->htt.tx_lock);
WARN_ON(reason >= BITS_PER_LONG);
arvif->tx_paused &= ~BIT(reason);
if (ar->tx_paused)
return;
if (arvif->tx_paused)
return;
ieee80211_wake_queue(ar->hw, arvif->vdev_id);
}
static void ath10k_mac_vif_handle_tx_pause(struct ath10k_vif *arvif,
enum wmi_tlv_tx_pause_id pause_id,
enum wmi_tlv_tx_pause_action action)
{
struct ath10k *ar = arvif->ar;
lockdep_assert_held(&ar->htt.tx_lock);
switch (action) {
case WMI_TLV_TX_PAUSE_ACTION_STOP:
ath10k_mac_vif_tx_lock(arvif, pause_id);
break;
case WMI_TLV_TX_PAUSE_ACTION_WAKE:
ath10k_mac_vif_tx_unlock(arvif, pause_id);
break;
default:
ath10k_warn(ar, "received unknown tx pause action %d on vdev %i, ignoring\n",
action, arvif->vdev_id);
break;
}
}
struct ath10k_mac_tx_pause {
u32 vdev_id;
enum wmi_tlv_tx_pause_id pause_id;
enum wmi_tlv_tx_pause_action action;
};
static void ath10k_mac_handle_tx_pause_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct ath10k_mac_tx_pause *arg = data;
if (arvif->vdev_id != arg->vdev_id)
return;
ath10k_mac_vif_handle_tx_pause(arvif, arg->pause_id, arg->action);
}
void ath10k_mac_handle_tx_pause_vdev(struct ath10k *ar, u32 vdev_id,
enum wmi_tlv_tx_pause_id pause_id,
enum wmi_tlv_tx_pause_action action)
{
struct ath10k_mac_tx_pause arg = {
.vdev_id = vdev_id,
.pause_id = pause_id,
.action = action,
};
spin_lock_bh(&ar->htt.tx_lock);
ieee80211_iterate_active_interfaces_atomic(ar->hw,
IEEE80211_IFACE_ITER_RESUME_ALL,
ath10k_mac_handle_tx_pause_iter,
&arg);
spin_unlock_bh(&ar->htt.tx_lock);
}
static u8 ath10k_tx_h_get_tid(struct ieee80211_hdr *hdr)
{
if (ieee80211_is_mgmt(hdr->frame_control))
return HTT_DATA_TX_EXT_TID_MGMT;
if (!ieee80211_is_data_qos(hdr->frame_control))
return HTT_DATA_TX_EXT_TID_NON_QOS_MCAST_BCAST;
if (!is_unicast_ether_addr(ieee80211_get_DA(hdr)))
return HTT_DATA_TX_EXT_TID_NON_QOS_MCAST_BCAST;
return ieee80211_get_qos_ctl(hdr)[0] & IEEE80211_QOS_CTL_TID_MASK;
}
static u8 ath10k_tx_h_get_vdev_id(struct ath10k *ar, struct ieee80211_vif *vif)
{
if (vif)
return ath10k_vif_to_arvif(vif)->vdev_id;
if (ar->monitor_started)
return ar->monitor_vdev_id;
ath10k_warn(ar, "failed to resolve vdev id\n");
return 0;
}
static enum ath10k_hw_txrx_mode
ath10k_tx_h_get_txmode(struct ath10k *ar, struct ieee80211_vif *vif,
struct ieee80211_sta *sta, struct sk_buff *skb)
{
const struct ieee80211_hdr *hdr = (void *)skb->data;
__le16 fc = hdr->frame_control;
if (!vif || vif->type == NL80211_IFTYPE_MONITOR)
return ATH10K_HW_TXRX_RAW;
if (ieee80211_is_mgmt(fc))
return ATH10K_HW_TXRX_MGMT;
/* Workaround:
*
* NullFunc frames are mostly used to ping if a client or AP are still
* reachable and responsive. This implies tx status reports must be
* accurate - otherwise either mac80211 or userspace (e.g. hostapd) can
* come to a conclusion that the other end disappeared and tear down
* BSS connection or it can never disconnect from BSS/client (which is
* the case).
*
* Firmware with HTT older than 3.0 delivers incorrect tx status for
* NullFunc frames to driver. However there's a HTT Mgmt Tx command
* which seems to deliver correct tx reports for NullFunc frames. The
* downside of using it is it ignores client powersave state so it can
* end up disconnecting sleeping clients in AP mode. It should fix STA
* mode though because AP don't sleep.
*/
if (ar->htt.target_version_major < 3 &&
(ieee80211_is_nullfunc(fc) || ieee80211_is_qos_nullfunc(fc)) &&
!test_bit(ATH10K_FW_FEATURE_HAS_WMI_MGMT_TX, ar->fw_features))
return ATH10K_HW_TXRX_MGMT;
/* Workaround:
*
* Some wmi-tlv firmwares for qca6174 have broken Tx key selection for
* NativeWifi txmode - it selects AP key instead of peer key. It seems
* to work with Ethernet txmode so use it.
*
* FIXME: Check if raw mode works with TDLS.
*/
if (ieee80211_is_data_present(fc) && sta && sta->tdls)
return ATH10K_HW_TXRX_ETHERNET;
if (test_bit(ATH10K_FLAG_RAW_MODE, &ar->dev_flags))
return ATH10K_HW_TXRX_RAW;
return ATH10K_HW_TXRX_NATIVE_WIFI;
}
static bool ath10k_tx_h_use_hwcrypto(struct ieee80211_vif *vif,
struct sk_buff *skb) {
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
const u32 mask = IEEE80211_TX_INTFL_DONT_ENCRYPT |
IEEE80211_TX_CTL_INJECTED;
if ((info->flags & mask) == mask)
return false;
if (vif)
return !ath10k_vif_to_arvif(vif)->nohwcrypt;
return true;
}
/* HTT Tx uses Native Wifi tx mode which expects 802.11 frames without QoS
* Control in the header.
*/
static void ath10k_tx_h_nwifi(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (void *)skb->data;
struct ath10k_skb_cb *cb = ATH10K_SKB_CB(skb);
u8 *qos_ctl;
if (!ieee80211_is_data_qos(hdr->frame_control))
return;
qos_ctl = ieee80211_get_qos_ctl(hdr);
memmove(skb->data + IEEE80211_QOS_CTL_LEN,
skb->data, (void *)qos_ctl - (void *)skb->data);
skb_pull(skb, IEEE80211_QOS_CTL_LEN);
/* Some firmware revisions don't handle sending QoS NullFunc well.
* These frames are mainly used for CQM purposes so it doesn't really
* matter whether QoS NullFunc or NullFunc are sent.
*/
hdr = (void *)skb->data;
if (ieee80211_is_qos_nullfunc(hdr->frame_control))
cb->htt.tid = HTT_DATA_TX_EXT_TID_NON_QOS_MCAST_BCAST;
hdr->frame_control &= ~__cpu_to_le16(IEEE80211_STYPE_QOS_DATA);
}
static void ath10k_tx_h_8023(struct sk_buff *skb)
{
struct ieee80211_hdr *hdr;
struct rfc1042_hdr *rfc1042;
struct ethhdr *eth;
size_t hdrlen;
u8 da[ETH_ALEN];
u8 sa[ETH_ALEN];
__be16 type;
hdr = (void *)skb->data;
hdrlen = ieee80211_hdrlen(hdr->frame_control);
rfc1042 = (void *)skb->data + hdrlen;
ether_addr_copy(da, ieee80211_get_DA(hdr));
ether_addr_copy(sa, ieee80211_get_SA(hdr));
type = rfc1042->snap_type;
skb_pull(skb, hdrlen + sizeof(*rfc1042));
skb_push(skb, sizeof(*eth));
eth = (void *)skb->data;
ether_addr_copy(eth->h_dest, da);
ether_addr_copy(eth->h_source, sa);
eth->h_proto = type;
}
static void ath10k_tx_h_add_p2p_noa_ie(struct ath10k *ar,
struct ieee80211_vif *vif,
struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
/* This is case only for P2P_GO */
if (arvif->vdev_type != WMI_VDEV_TYPE_AP ||
arvif->vdev_subtype != WMI_VDEV_SUBTYPE_P2P_GO)
return;
if (unlikely(ieee80211_is_probe_resp(hdr->frame_control))) {
spin_lock_bh(&ar->data_lock);
if (arvif->u.ap.noa_data)
if (!pskb_expand_head(skb, 0, arvif->u.ap.noa_len,
GFP_ATOMIC))
memcpy(skb_put(skb, arvif->u.ap.noa_len),
arvif->u.ap.noa_data,
arvif->u.ap.noa_len);
spin_unlock_bh(&ar->data_lock);
}
}
static bool ath10k_mac_need_offchan_tx_work(struct ath10k *ar)
{
/* FIXME: Not really sure since when the behaviour changed. At some
* point new firmware stopped requiring creation of peer entries for
* offchannel tx (and actually creating them causes issues with wmi-htc
* tx credit replenishment and reliability). Assuming it's at least 3.4
* because that's when the `freq` was introduced to TX_FRM HTT command.
*/
return !(ar->htt.target_version_major >= 3 &&
ar->htt.target_version_minor >= 4);
}
static int ath10k_mac_tx_wmi_mgmt(struct ath10k *ar, struct sk_buff *skb)
{
struct sk_buff_head *q = &ar->wmi_mgmt_tx_queue;
int ret = 0;
spin_lock_bh(&ar->data_lock);
if (skb_queue_len(q) == ATH10K_MAX_NUM_MGMT_PENDING) {
ath10k_warn(ar, "wmi mgmt tx queue is full\n");
ret = -ENOSPC;
goto unlock;
}
__skb_queue_tail(q, skb);
ieee80211_queue_work(ar->hw, &ar->wmi_mgmt_tx_work);
unlock:
spin_unlock_bh(&ar->data_lock);
return ret;
}
static void ath10k_mac_tx(struct ath10k *ar, struct sk_buff *skb)
{
struct ath10k_skb_cb *cb = ATH10K_SKB_CB(skb);
struct ath10k_htt *htt = &ar->htt;
int ret = 0;
switch (cb->txmode) {
case ATH10K_HW_TXRX_RAW:
case ATH10K_HW_TXRX_NATIVE_WIFI:
case ATH10K_HW_TXRX_ETHERNET:
ret = ath10k_htt_tx(htt, skb);
break;
case ATH10K_HW_TXRX_MGMT:
if (test_bit(ATH10K_FW_FEATURE_HAS_WMI_MGMT_TX,
ar->fw_features))
ret = ath10k_mac_tx_wmi_mgmt(ar, skb);
else if (ar->htt.target_version_major >= 3)
ret = ath10k_htt_tx(htt, skb);
else
ret = ath10k_htt_mgmt_tx(htt, skb);
break;
}
if (ret) {
ath10k_warn(ar, "failed to transmit packet, dropping: %d\n",
ret);
ieee80211_free_txskb(ar->hw, skb);
}
}
void ath10k_offchan_tx_purge(struct ath10k *ar)
{
struct sk_buff *skb;
for (;;) {
skb = skb_dequeue(&ar->offchan_tx_queue);
if (!skb)
break;
ieee80211_free_txskb(ar->hw, skb);
}
}
void ath10k_offchan_tx_work(struct work_struct *work)
{
struct ath10k *ar = container_of(work, struct ath10k, offchan_tx_work);
struct ath10k_peer *peer;
struct ieee80211_hdr *hdr;
struct sk_buff *skb;
const u8 *peer_addr;
int vdev_id;
int ret;
unsigned long time_left;
bool tmp_peer_created = false;
/* FW requirement: We must create a peer before FW will send out
* an offchannel frame. Otherwise the frame will be stuck and
* never transmitted. We delete the peer upon tx completion.
* It is unlikely that a peer for offchannel tx will already be
* present. However it may be in some rare cases so account for that.
* Otherwise we might remove a legitimate peer and break stuff. */
for (;;) {
skb = skb_dequeue(&ar->offchan_tx_queue);
if (!skb)
break;
mutex_lock(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac offchannel skb %p\n",
skb);
hdr = (struct ieee80211_hdr *)skb->data;
peer_addr = ieee80211_get_DA(hdr);
vdev_id = ATH10K_SKB_CB(skb)->vdev_id;
spin_lock_bh(&ar->data_lock);
peer = ath10k_peer_find(ar, vdev_id, peer_addr);
spin_unlock_bh(&ar->data_lock);
if (peer)
/* FIXME: should this use ath10k_warn()? */
ath10k_dbg(ar, ATH10K_DBG_MAC, "peer %pM on vdev %d already present\n",
peer_addr, vdev_id);
if (!peer) {
ret = ath10k_peer_create(ar, vdev_id, peer_addr,
WMI_PEER_TYPE_DEFAULT);
if (ret)
ath10k_warn(ar, "failed to create peer %pM on vdev %d: %d\n",
peer_addr, vdev_id, ret);
tmp_peer_created = (ret == 0);
}
spin_lock_bh(&ar->data_lock);
reinit_completion(&ar->offchan_tx_completed);
ar->offchan_tx_skb = skb;
spin_unlock_bh(&ar->data_lock);
ath10k_mac_tx(ar, skb);
time_left =
wait_for_completion_timeout(&ar->offchan_tx_completed, 3 * HZ);
if (time_left == 0)
ath10k_warn(ar, "timed out waiting for offchannel skb %p\n",
skb);
if (!peer && tmp_peer_created) {
ret = ath10k_peer_delete(ar, vdev_id, peer_addr);
if (ret)
ath10k_warn(ar, "failed to delete peer %pM on vdev %d: %d\n",
peer_addr, vdev_id, ret);
}
mutex_unlock(&ar->conf_mutex);
}
}
void ath10k_mgmt_over_wmi_tx_purge(struct ath10k *ar)
{
struct sk_buff *skb;
for (;;) {
skb = skb_dequeue(&ar->wmi_mgmt_tx_queue);
if (!skb)
break;
ieee80211_free_txskb(ar->hw, skb);
}
}
void ath10k_mgmt_over_wmi_tx_work(struct work_struct *work)
{
struct ath10k *ar = container_of(work, struct ath10k, wmi_mgmt_tx_work);
struct sk_buff *skb;
int ret;
for (;;) {
skb = skb_dequeue(&ar->wmi_mgmt_tx_queue);
if (!skb)
break;
ret = ath10k_wmi_mgmt_tx(ar, skb);
if (ret) {
ath10k_warn(ar, "failed to transmit management frame via WMI: %d\n",
ret);
ieee80211_free_txskb(ar->hw, skb);
}
}
}
/************/
/* Scanning */
/************/
void __ath10k_scan_finish(struct ath10k *ar)
{
lockdep_assert_held(&ar->data_lock);
switch (ar->scan.state) {
case ATH10K_SCAN_IDLE:
break;
case ATH10K_SCAN_RUNNING:
case ATH10K_SCAN_ABORTING:
if (!ar->scan.is_roc)
ieee80211_scan_completed(ar->hw,
(ar->scan.state ==
ATH10K_SCAN_ABORTING));
else if (ar->scan.roc_notify)
ieee80211_remain_on_channel_expired(ar->hw);
/* fall through */
case ATH10K_SCAN_STARTING:
ar->scan.state = ATH10K_SCAN_IDLE;
ar->scan_channel = NULL;
ath10k_offchan_tx_purge(ar);
cancel_delayed_work(&ar->scan.timeout);
complete_all(&ar->scan.completed);
break;
}
}
void ath10k_scan_finish(struct ath10k *ar)
{
spin_lock_bh(&ar->data_lock);
__ath10k_scan_finish(ar);
spin_unlock_bh(&ar->data_lock);
}
static int ath10k_scan_stop(struct ath10k *ar)
{
struct wmi_stop_scan_arg arg = {
.req_id = 1, /* FIXME */
.req_type = WMI_SCAN_STOP_ONE,
.u.scan_id = ATH10K_SCAN_ID,
};
int ret;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_wmi_stop_scan(ar, &arg);
if (ret) {
ath10k_warn(ar, "failed to stop wmi scan: %d\n", ret);
goto out;
}
ret = wait_for_completion_timeout(&ar->scan.completed, 3*HZ);
if (ret == 0) {
ath10k_warn(ar, "failed to receive scan abortion completion: timed out\n");
ret = -ETIMEDOUT;
} else if (ret > 0) {
ret = 0;
}
out:
/* Scan state should be updated upon scan completion but in case
* firmware fails to deliver the event (for whatever reason) it is
* desired to clean up scan state anyway. Firmware may have just
* dropped the scan completion event delivery due to transport pipe
* being overflown with data and/or it can recover on its own before
* next scan request is submitted.
*/
spin_lock_bh(&ar->data_lock);
if (ar->scan.state != ATH10K_SCAN_IDLE)
__ath10k_scan_finish(ar);
spin_unlock_bh(&ar->data_lock);
return ret;
}
static void ath10k_scan_abort(struct ath10k *ar)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
switch (ar->scan.state) {
case ATH10K_SCAN_IDLE:
/* This can happen if timeout worker kicked in and called
* abortion while scan completion was being processed.
*/
break;
case ATH10K_SCAN_STARTING:
case ATH10K_SCAN_ABORTING:
ath10k_warn(ar, "refusing scan abortion due to invalid scan state: %s (%d)\n",
ath10k_scan_state_str(ar->scan.state),
ar->scan.state);
break;
case ATH10K_SCAN_RUNNING:
ar->scan.state = ATH10K_SCAN_ABORTING;
spin_unlock_bh(&ar->data_lock);
ret = ath10k_scan_stop(ar);
if (ret)
ath10k_warn(ar, "failed to abort scan: %d\n", ret);
spin_lock_bh(&ar->data_lock);
break;
}
spin_unlock_bh(&ar->data_lock);
}
void ath10k_scan_timeout_work(struct work_struct *work)
{
struct ath10k *ar = container_of(work, struct ath10k,
scan.timeout.work);
mutex_lock(&ar->conf_mutex);
ath10k_scan_abort(ar);
mutex_unlock(&ar->conf_mutex);
}
static int ath10k_start_scan(struct ath10k *ar,
const struct wmi_start_scan_arg *arg)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
ret = ath10k_wmi_start_scan(ar, arg);
if (ret)
return ret;
ret = wait_for_completion_timeout(&ar->scan.started, 1*HZ);
if (ret == 0) {
ret = ath10k_scan_stop(ar);
if (ret)
ath10k_warn(ar, "failed to stop scan: %d\n", ret);
return -ETIMEDOUT;
}
/* If we failed to start the scan, return error code at
* this point. This is probably due to some issue in the
* firmware, but no need to wedge the driver due to that...
*/
spin_lock_bh(&ar->data_lock);
if (ar->scan.state == ATH10K_SCAN_IDLE) {
spin_unlock_bh(&ar->data_lock);
return -EINVAL;
}
spin_unlock_bh(&ar->data_lock);
return 0;
}
/**********************/
/* mac80211 callbacks */
/**********************/
static void ath10k_tx(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control,
struct sk_buff *skb)
{
struct ath10k *ar = hw->priv;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_vif *vif = info->control.vif;
struct ieee80211_sta *sta = control->sta;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
__le16 fc = hdr->frame_control;
/* We should disable CCK RATE due to P2P */
if (info->flags & IEEE80211_TX_CTL_NO_CCK_RATE)
ath10k_dbg(ar, ATH10K_DBG_MAC, "IEEE80211_TX_CTL_NO_CCK_RATE\n");
ATH10K_SKB_CB(skb)->htt.is_offchan = false;
ATH10K_SKB_CB(skb)->htt.freq = 0;
ATH10K_SKB_CB(skb)->htt.tid = ath10k_tx_h_get_tid(hdr);
ATH10K_SKB_CB(skb)->htt.nohwcrypt = !ath10k_tx_h_use_hwcrypto(vif, skb);
ATH10K_SKB_CB(skb)->vdev_id = ath10k_tx_h_get_vdev_id(ar, vif);
ATH10K_SKB_CB(skb)->txmode = ath10k_tx_h_get_txmode(ar, vif, sta, skb);
ATH10K_SKB_CB(skb)->is_protected = ieee80211_has_protected(fc);
switch (ATH10K_SKB_CB(skb)->txmode) {
case ATH10K_HW_TXRX_MGMT:
case ATH10K_HW_TXRX_NATIVE_WIFI:
ath10k_tx_h_nwifi(hw, skb);
ath10k_tx_h_add_p2p_noa_ie(ar, vif, skb);
ath10k_tx_h_seq_no(vif, skb);
break;
case ATH10K_HW_TXRX_ETHERNET:
ath10k_tx_h_8023(skb);
break;
case ATH10K_HW_TXRX_RAW:
if (!test_bit(ATH10K_FLAG_RAW_MODE, &ar->dev_flags)) {
WARN_ON_ONCE(1);
ieee80211_free_txskb(hw, skb);
return;
}
}
if (info->flags & IEEE80211_TX_CTL_TX_OFFCHAN) {
spin_lock_bh(&ar->data_lock);
ATH10K_SKB_CB(skb)->htt.freq = ar->scan.roc_freq;
ATH10K_SKB_CB(skb)->vdev_id = ar->scan.vdev_id;
spin_unlock_bh(&ar->data_lock);
if (ath10k_mac_need_offchan_tx_work(ar)) {
ATH10K_SKB_CB(skb)->htt.freq = 0;
ATH10K_SKB_CB(skb)->htt.is_offchan = true;
ath10k_dbg(ar, ATH10K_DBG_MAC, "queued offchannel skb %p\n",
skb);
skb_queue_tail(&ar->offchan_tx_queue, skb);
ieee80211_queue_work(hw, &ar->offchan_tx_work);
return;
}
}
ath10k_mac_tx(ar, skb);
}
/* Must not be called with conf_mutex held as workers can use that also. */
void ath10k_drain_tx(struct ath10k *ar)
{
/* make sure rcu-protected mac80211 tx path itself is drained */
synchronize_net();
ath10k_offchan_tx_purge(ar);
ath10k_mgmt_over_wmi_tx_purge(ar);
cancel_work_sync(&ar->offchan_tx_work);
cancel_work_sync(&ar->wmi_mgmt_tx_work);
}
void ath10k_halt(struct ath10k *ar)
{
struct ath10k_vif *arvif;
lockdep_assert_held(&ar->conf_mutex);
clear_bit(ATH10K_CAC_RUNNING, &ar->dev_flags);
ar->filter_flags = 0;
ar->monitor = false;
ar->monitor_arvif = NULL;
if (ar->monitor_started)
ath10k_monitor_stop(ar);
ar->monitor_started = false;
ar->tx_paused = 0;
ath10k_scan_finish(ar);
ath10k_peer_cleanup_all(ar);
ath10k_core_stop(ar);
ath10k_hif_power_down(ar);
spin_lock_bh(&ar->data_lock);
list_for_each_entry(arvif, &ar->arvifs, list)
ath10k_mac_vif_beacon_cleanup(arvif);
spin_unlock_bh(&ar->data_lock);
}
static int ath10k_get_antenna(struct ieee80211_hw *hw, u32 *tx_ant, u32 *rx_ant)
{
struct ath10k *ar = hw->priv;
mutex_lock(&ar->conf_mutex);
*tx_ant = ar->cfg_tx_chainmask;
*rx_ant = ar->cfg_rx_chainmask;
mutex_unlock(&ar->conf_mutex);
return 0;
}
static void ath10k_check_chain_mask(struct ath10k *ar, u32 cm, const char *dbg)
{
/* It is not clear that allowing gaps in chainmask
* is helpful. Probably it will not do what user
* is hoping for, so warn in that case.
*/
if (cm == 15 || cm == 7 || cm == 3 || cm == 1 || cm == 0)
return;
ath10k_warn(ar, "mac %s antenna chainmask may be invalid: 0x%x. Suggested values: 15, 7, 3, 1 or 0.\n",
dbg, cm);
}
static int ath10k_mac_get_vht_cap_bf_sts(struct ath10k *ar)
{
int nsts = ar->vht_cap_info;
nsts &= IEEE80211_VHT_CAP_BEAMFORMEE_STS_MASK;
nsts >>= IEEE80211_VHT_CAP_BEAMFORMEE_STS_SHIFT;
/* If firmware does not deliver to host number of space-time
* streams supported, assume it support up to 4 BF STS and return
* the value for VHT CAP: nsts-1)
*/
if (nsts == 0)
return 3;
return nsts;
}
static int ath10k_mac_get_vht_cap_bf_sound_dim(struct ath10k *ar)
{
int sound_dim = ar->vht_cap_info;
sound_dim &= IEEE80211_VHT_CAP_SOUNDING_DIMENSIONS_MASK;
sound_dim >>= IEEE80211_VHT_CAP_SOUNDING_DIMENSIONS_SHIFT;
/* If the sounding dimension is not advertised by the firmware,
* let's use a default value of 1
*/
if (sound_dim == 0)
return 1;
return sound_dim;
}
static struct ieee80211_sta_vht_cap ath10k_create_vht_cap(struct ath10k *ar)
{
struct ieee80211_sta_vht_cap vht_cap = {0};
u16 mcs_map;
u32 val;
int i;
vht_cap.vht_supported = 1;
vht_cap.cap = ar->vht_cap_info;
if (ar->vht_cap_info & (IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE)) {
val = ath10k_mac_get_vht_cap_bf_sts(ar);
val <<= IEEE80211_VHT_CAP_BEAMFORMEE_STS_SHIFT;
val &= IEEE80211_VHT_CAP_BEAMFORMEE_STS_MASK;
vht_cap.cap |= val;
}
if (ar->vht_cap_info & (IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE)) {
val = ath10k_mac_get_vht_cap_bf_sound_dim(ar);
val <<= IEEE80211_VHT_CAP_SOUNDING_DIMENSIONS_SHIFT;
val &= IEEE80211_VHT_CAP_SOUNDING_DIMENSIONS_MASK;
vht_cap.cap |= val;
}
mcs_map = 0;
for (i = 0; i < 8; i++) {
if ((i < ar->num_rf_chains) && (ar->cfg_tx_chainmask & BIT(i)))
mcs_map |= IEEE80211_VHT_MCS_SUPPORT_0_9 << (i * 2);
else
mcs_map |= IEEE80211_VHT_MCS_NOT_SUPPORTED << (i * 2);
}
vht_cap.vht_mcs.rx_mcs_map = cpu_to_le16(mcs_map);
vht_cap.vht_mcs.tx_mcs_map = cpu_to_le16(mcs_map);
return vht_cap;
}
static struct ieee80211_sta_ht_cap ath10k_get_ht_cap(struct ath10k *ar)
{
int i;
struct ieee80211_sta_ht_cap ht_cap = {0};
if (!(ar->ht_cap_info & WMI_HT_CAP_ENABLED))
return ht_cap;
ht_cap.ht_supported = 1;
ht_cap.ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K;
ht_cap.ampdu_density = IEEE80211_HT_MPDU_DENSITY_8;
ht_cap.cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
ht_cap.cap |= IEEE80211_HT_CAP_DSSSCCK40;
ht_cap.cap |= WLAN_HT_CAP_SM_PS_STATIC << IEEE80211_HT_CAP_SM_PS_SHIFT;
if (ar->ht_cap_info & WMI_HT_CAP_HT20_SGI)
ht_cap.cap |= IEEE80211_HT_CAP_SGI_20;
if (ar->ht_cap_info & WMI_HT_CAP_HT40_SGI)
ht_cap.cap |= IEEE80211_HT_CAP_SGI_40;
if (ar->ht_cap_info & WMI_HT_CAP_DYNAMIC_SMPS) {
u32 smps;
smps = WLAN_HT_CAP_SM_PS_DYNAMIC;
smps <<= IEEE80211_HT_CAP_SM_PS_SHIFT;
ht_cap.cap |= smps;
}
if (ar->ht_cap_info & WMI_HT_CAP_TX_STBC)
ht_cap.cap |= IEEE80211_HT_CAP_TX_STBC;
if (ar->ht_cap_info & WMI_HT_CAP_RX_STBC) {
u32 stbc;
stbc = ar->ht_cap_info;
stbc &= WMI_HT_CAP_RX_STBC;
stbc >>= WMI_HT_CAP_RX_STBC_MASK_SHIFT;
stbc <<= IEEE80211_HT_CAP_RX_STBC_SHIFT;
stbc &= IEEE80211_HT_CAP_RX_STBC;
ht_cap.cap |= stbc;
}
if (ar->ht_cap_info & WMI_HT_CAP_LDPC)
ht_cap.cap |= IEEE80211_HT_CAP_LDPC_CODING;
if (ar->ht_cap_info & WMI_HT_CAP_L_SIG_TXOP_PROT)
ht_cap.cap |= IEEE80211_HT_CAP_LSIG_TXOP_PROT;
/* max AMSDU is implicitly taken from vht_cap_info */
if (ar->vht_cap_info & WMI_VHT_CAP_MAX_MPDU_LEN_MASK)
ht_cap.cap |= IEEE80211_HT_CAP_MAX_AMSDU;
for (i = 0; i < ar->num_rf_chains; i++) {
if (ar->cfg_rx_chainmask & BIT(i))
ht_cap.mcs.rx_mask[i] = 0xFF;
}
ht_cap.mcs.tx_params |= IEEE80211_HT_MCS_TX_DEFINED;
return ht_cap;
}
static void ath10k_mac_setup_ht_vht_cap(struct ath10k *ar)
{
struct ieee80211_supported_band *band;
struct ieee80211_sta_vht_cap vht_cap;
struct ieee80211_sta_ht_cap ht_cap;
ht_cap = ath10k_get_ht_cap(ar);
vht_cap = ath10k_create_vht_cap(ar);
if (ar->phy_capability & WHAL_WLAN_11G_CAPABILITY) {
band = &ar->mac.sbands[IEEE80211_BAND_2GHZ];
band->ht_cap = ht_cap;
/* Enable the VHT support at 2.4 GHz */
band->vht_cap = vht_cap;
}
if (ar->phy_capability & WHAL_WLAN_11A_CAPABILITY) {
band = &ar->mac.sbands[IEEE80211_BAND_5GHZ];
band->ht_cap = ht_cap;
band->vht_cap = vht_cap;
}
}
static int __ath10k_set_antenna(struct ath10k *ar, u32 tx_ant, u32 rx_ant)
{
int ret;
lockdep_assert_held(&ar->conf_mutex);
ath10k_check_chain_mask(ar, tx_ant, "tx");
ath10k_check_chain_mask(ar, rx_ant, "rx");
ar->cfg_tx_chainmask = tx_ant;
ar->cfg_rx_chainmask = rx_ant;
if ((ar->state != ATH10K_STATE_ON) &&
(ar->state != ATH10K_STATE_RESTARTED))
return 0;
ret = ath10k_wmi_pdev_set_param(ar, ar->wmi.pdev_param->tx_chain_mask,
tx_ant);
if (ret) {
ath10k_warn(ar, "failed to set tx-chainmask: %d, req 0x%x\n",
ret, tx_ant);
return ret;
}
ret = ath10k_wmi_pdev_set_param(ar, ar->wmi.pdev_param->rx_chain_mask,
rx_ant);
if (ret) {
ath10k_warn(ar, "failed to set rx-chainmask: %d, req 0x%x\n",
ret, rx_ant);
return ret;
}
/* Reload HT/VHT capability */
ath10k_mac_setup_ht_vht_cap(ar);
return 0;
}
static int ath10k_set_antenna(struct ieee80211_hw *hw, u32 tx_ant, u32 rx_ant)
{
struct ath10k *ar = hw->priv;
int ret;
mutex_lock(&ar->conf_mutex);
ret = __ath10k_set_antenna(ar, tx_ant, rx_ant);
mutex_unlock(&ar->conf_mutex);
return ret;
}
static int ath10k_start(struct ieee80211_hw *hw)
{
struct ath10k *ar = hw->priv;
u32 burst_enable;
int ret = 0;
/*
* This makes sense only when restarting hw. It is harmless to call
* uncoditionally. This is necessary to make sure no HTT/WMI tx
* commands will be submitted while restarting.
*/
ath10k_drain_tx(ar);
mutex_lock(&ar->conf_mutex);
switch (ar->state) {
case ATH10K_STATE_OFF:
ar->state = ATH10K_STATE_ON;
break;
case ATH10K_STATE_RESTARTING:
ath10k_halt(ar);
ar->state = ATH10K_STATE_RESTARTED;
break;
case ATH10K_STATE_ON:
case ATH10K_STATE_RESTARTED:
case ATH10K_STATE_WEDGED:
WARN_ON(1);
ret = -EINVAL;
goto err;
case ATH10K_STATE_UTF:
ret = -EBUSY;
goto err;
}
ret = ath10k_hif_power_up(ar);
if (ret) {
ath10k_err(ar, "Could not init hif: %d\n", ret);
goto err_off;
}
ret = ath10k_core_start(ar, ATH10K_FIRMWARE_MODE_NORMAL);
if (ret) {
ath10k_err(ar, "Could not init core: %d\n", ret);
goto err_power_down;
}
ret = ath10k_wmi_pdev_set_param(ar, ar->wmi.pdev_param->pmf_qos, 1);
if (ret) {
ath10k_warn(ar, "failed to enable PMF QOS: %d\n", ret);
goto err_core_stop;
}
ret = ath10k_wmi_pdev_set_param(ar, ar->wmi.pdev_param->dynamic_bw, 1);
if (ret) {
ath10k_warn(ar, "failed to enable dynamic BW: %d\n", ret);
goto err_core_stop;
}
if (test_bit(WMI_SERVICE_ADAPTIVE_OCS, ar->wmi.svc_map)) {
ret = ath10k_wmi_adaptive_qcs(ar, true);
if (ret) {
ath10k_warn(ar, "failed to enable adaptive qcs: %d\n",
ret);
goto err_core_stop;
}
}
if (test_bit(WMI_SERVICE_BURST, ar->wmi.svc_map)) {
burst_enable = ar->wmi.pdev_param->burst_enable;
ret = ath10k_wmi_pdev_set_param(ar, burst_enable, 0);
if (ret) {
ath10k_warn(ar, "failed to disable burst: %d\n", ret);
goto err_core_stop;
}
}
__ath10k_set_antenna(ar, ar->cfg_tx_chainmask, ar->cfg_rx_chainmask);
/*
* By default FW set ARP frames ac to voice (6). In that case ARP
* exchange is not working properly for UAPSD enabled AP. ARP requests
* which arrives with access category 0 are processed by network stack
* and send back with access category 0, but FW changes access category
* to 6. Set ARP frames access category to best effort (0) solves
* this problem.
*/
ret = ath10k_wmi_pdev_set_param(ar,
ar->wmi.pdev_param->arp_ac_override, 0);
if (ret) {
ath10k_warn(ar, "failed to set arp ac override parameter: %d\n",
ret);
goto err_core_stop;
}
if (test_bit(ATH10K_FW_FEATURE_SUPPORTS_ADAPTIVE_CCA,
ar->fw_features)) {
ret = ath10k_wmi_pdev_enable_adaptive_cca(ar, 1,
WMI_CCA_DETECT_LEVEL_AUTO,
WMI_CCA_DETECT_MARGIN_AUTO);
if (ret) {
ath10k_warn(ar, "failed to enable adaptive cca: %d\n",
ret);
goto err_core_stop;
}
}
ret = ath10k_wmi_pdev_set_param(ar,
ar->wmi.pdev_param->ani_enable, 1);
if (ret) {
ath10k_warn(ar, "failed to enable ani by default: %d\n",
ret);
goto err_core_stop;
}
ar->ani_enabled = true;
ar->num_started_vdevs = 0;
ath10k_regd_update(ar);
ath10k_spectral_start(ar);
ath10k_thermal_set_throttling(ar);
mutex_unlock(&ar->conf_mutex);
return 0;
err_core_stop:
ath10k_core_stop(ar);
err_power_down:
ath10k_hif_power_down(ar);
err_off:
ar->state = ATH10K_STATE_OFF;
err:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static void ath10k_stop(struct ieee80211_hw *hw)
{
struct ath10k *ar = hw->priv;
ath10k_drain_tx(ar);
mutex_lock(&ar->conf_mutex);
if (ar->state != ATH10K_STATE_OFF) {
ath10k_halt(ar);
ar->state = ATH10K_STATE_OFF;
}
mutex_unlock(&ar->conf_mutex);
cancel_delayed_work_sync(&ar->scan.timeout);
cancel_work_sync(&ar->restart_work);
}
static int ath10k_config_ps(struct ath10k *ar)
{
struct ath10k_vif *arvif;
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
list_for_each_entry(arvif, &ar->arvifs, list) {
ret = ath10k_mac_vif_setup_ps(arvif);
if (ret) {
ath10k_warn(ar, "failed to setup powersave: %d\n", ret);
break;
}
}
return ret;
}
static int ath10k_mac_txpower_setup(struct ath10k *ar, int txpower)
{
int ret;
u32 param;
lockdep_assert_held(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac txpower %d\n", txpower);
param = ar->wmi.pdev_param->txpower_limit2g;
ret = ath10k_wmi_pdev_set_param(ar, param, txpower * 2);
if (ret) {
ath10k_warn(ar, "failed to set 2g txpower %d: %d\n",
txpower, ret);
return ret;
}
param = ar->wmi.pdev_param->txpower_limit5g;
ret = ath10k_wmi_pdev_set_param(ar, param, txpower * 2);
if (ret) {
ath10k_warn(ar, "failed to set 5g txpower %d: %d\n",
txpower, ret);
return ret;
}
return 0;
}
static int ath10k_mac_txpower_recalc(struct ath10k *ar)
{
struct ath10k_vif *arvif;
int ret, txpower = -1;
lockdep_assert_held(&ar->conf_mutex);
list_for_each_entry(arvif, &ar->arvifs, list) {
WARN_ON(arvif->txpower < 0);
if (txpower == -1)
txpower = arvif->txpower;
else
txpower = min(txpower, arvif->txpower);
}
if (WARN_ON(txpower == -1))
return -EINVAL;
ret = ath10k_mac_txpower_setup(ar, txpower);
if (ret) {
ath10k_warn(ar, "failed to setup tx power %d: %d\n",
txpower, ret);
return ret;
}
return 0;
}
static int ath10k_config(struct ieee80211_hw *hw, u32 changed)
{
struct ath10k *ar = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
int ret = 0;
mutex_lock(&ar->conf_mutex);
if (changed & IEEE80211_CONF_CHANGE_PS)
ath10k_config_ps(ar);
if (changed & IEEE80211_CONF_CHANGE_MONITOR) {
ar->monitor = conf->flags & IEEE80211_CONF_MONITOR;
ret = ath10k_monitor_recalc(ar);
if (ret)
ath10k_warn(ar, "failed to recalc monitor: %d\n", ret);
}
mutex_unlock(&ar->conf_mutex);
return ret;
}
static u32 get_nss_from_chainmask(u16 chain_mask)
{
if ((chain_mask & 0xf) == 0xf)
return 4;
else if ((chain_mask & 0x7) == 0x7)
return 3;
else if ((chain_mask & 0x3) == 0x3)
return 2;
return 1;
}
static int ath10k_mac_set_txbf_conf(struct ath10k_vif *arvif)
{
u32 value = 0;
struct ath10k *ar = arvif->ar;
int nsts;
int sound_dim;
if (ath10k_wmi_get_txbf_conf_scheme(ar) != WMI_TXBF_CONF_BEFORE_ASSOC)
return 0;
nsts = ath10k_mac_get_vht_cap_bf_sts(ar);
if (ar->vht_cap_info & (IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE))
value |= SM(nsts, WMI_TXBF_STS_CAP_OFFSET);
sound_dim = ath10k_mac_get_vht_cap_bf_sound_dim(ar);
if (ar->vht_cap_info & (IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE |
IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE))
value |= SM(sound_dim, WMI_BF_SOUND_DIM_OFFSET);
if (!value)
return 0;
if (ar->vht_cap_info & IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE)
value |= WMI_VDEV_PARAM_TXBF_SU_TX_BFER;
if (ar->vht_cap_info & IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE)
value |= (WMI_VDEV_PARAM_TXBF_MU_TX_BFER |
WMI_VDEV_PARAM_TXBF_SU_TX_BFER);
if (ar->vht_cap_info & IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE)
value |= WMI_VDEV_PARAM_TXBF_SU_TX_BFEE;
if (ar->vht_cap_info & IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE)
value |= (WMI_VDEV_PARAM_TXBF_MU_TX_BFEE |
WMI_VDEV_PARAM_TXBF_SU_TX_BFEE);
return ath10k_wmi_vdev_set_param(ar, arvif->vdev_id,
ar->wmi.vdev_param->txbf, value);
}
/*
* TODO:
* Figure out how to handle WMI_VDEV_SUBTYPE_P2P_DEVICE,
* because we will send mgmt frames without CCK. This requirement
* for P2P_FIND/GO_NEG should be handled by checking CCK flag
* in the TX packet.
*/
static int ath10k_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
enum wmi_sta_powersave_param param;
int ret = 0;
u32 value;
int bit;
int i;
u32 vdev_param;
vif->driver_flags |= IEEE80211_VIF_SUPPORTS_UAPSD;
mutex_lock(&ar->conf_mutex);
memset(arvif, 0, sizeof(*arvif));
arvif->ar = ar;
arvif->vif = vif;
INIT_LIST_HEAD(&arvif->list);
INIT_WORK(&arvif->ap_csa_work, ath10k_mac_vif_ap_csa_work);
INIT_DELAYED_WORK(&arvif->connection_loss_work,
ath10k_mac_vif_sta_connection_loss_work);
for (i = 0; i < ARRAY_SIZE(arvif->bitrate_mask.control); i++) {
arvif->bitrate_mask.control[i].legacy = 0xffffffff;
memset(arvif->bitrate_mask.control[i].ht_mcs, 0xff,
sizeof(arvif->bitrate_mask.control[i].ht_mcs));
memset(arvif->bitrate_mask.control[i].vht_mcs, 0xff,
sizeof(arvif->bitrate_mask.control[i].vht_mcs));
}
if (ar->num_peers >= ar->max_num_peers) {
ath10k_warn(ar, "refusing vdev creation due to insufficient peer entry resources in firmware\n");
ret = -ENOBUFS;
goto err;
}
if (ar->free_vdev_map == 0) {
ath10k_warn(ar, "Free vdev map is empty, no more interfaces allowed.\n");
ret = -EBUSY;
goto err;
}
bit = __ffs64(ar->free_vdev_map);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac create vdev %i map %llx\n",
bit, ar->free_vdev_map);
arvif->vdev_id = bit;
arvif->vdev_subtype = WMI_VDEV_SUBTYPE_NONE;
switch (vif->type) {
case NL80211_IFTYPE_P2P_DEVICE:
arvif->vdev_type = WMI_VDEV_TYPE_STA;
arvif->vdev_subtype = WMI_VDEV_SUBTYPE_P2P_DEVICE;
break;
case NL80211_IFTYPE_UNSPECIFIED:
case NL80211_IFTYPE_STATION:
arvif->vdev_type = WMI_VDEV_TYPE_STA;
if (vif->p2p)
arvif->vdev_subtype = WMI_VDEV_SUBTYPE_P2P_CLIENT;
break;
case NL80211_IFTYPE_ADHOC:
arvif->vdev_type = WMI_VDEV_TYPE_IBSS;
break;
case NL80211_IFTYPE_MESH_POINT:
if (!test_bit(ATH10K_FLAG_RAW_MODE, &ar->dev_flags)) {
ret = -EINVAL;
ath10k_warn(ar, "must load driver with rawmode=1 to add mesh interfaces\n");
goto err;
}
arvif->vdev_type = WMI_VDEV_TYPE_AP;
break;
case NL80211_IFTYPE_AP:
arvif->vdev_type = WMI_VDEV_TYPE_AP;
if (vif->p2p)
arvif->vdev_subtype = WMI_VDEV_SUBTYPE_P2P_GO;
break;
case NL80211_IFTYPE_MONITOR:
arvif->vdev_type = WMI_VDEV_TYPE_MONITOR;
break;
default:
WARN_ON(1);
break;
}
/* Using vdev_id as queue number will make it very easy to do per-vif
* tx queue locking. This shouldn't wrap due to interface combinations
* but do a modulo for correctness sake and prevent using offchannel tx
* queues for regular vif tx.
*/
vif->cab_queue = arvif->vdev_id % (IEEE80211_MAX_QUEUES - 1);
for (i = 0; i < ARRAY_SIZE(vif->hw_queue); i++)
vif->hw_queue[i] = arvif->vdev_id % (IEEE80211_MAX_QUEUES - 1);
/* Some firmware revisions don't wait for beacon tx completion before
* sending another SWBA event. This could lead to hardware using old
* (freed) beacon data in some cases, e.g. tx credit starvation
* combined with missed TBTT. This is very very rare.
*
* On non-IOMMU-enabled hosts this could be a possible security issue
* because hw could beacon some random data on the air. On
* IOMMU-enabled hosts DMAR faults would occur in most cases and target
* device would crash.
*
* Since there are no beacon tx completions (implicit nor explicit)
* propagated to host the only workaround for this is to allocate a
* DMA-coherent buffer for a lifetime of a vif and use it for all
* beacon tx commands. Worst case for this approach is some beacons may
* become corrupted, e.g. have garbled IEs or out-of-date TIM bitmap.
*/
if (vif->type == NL80211_IFTYPE_ADHOC ||
vif->type == NL80211_IFTYPE_MESH_POINT ||
vif->type == NL80211_IFTYPE_AP) {
arvif->beacon_buf = dma_zalloc_coherent(ar->dev,
IEEE80211_MAX_FRAME_LEN,
&arvif->beacon_paddr,
GFP_ATOMIC);
if (!arvif->beacon_buf) {
ret = -ENOMEM;
ath10k_warn(ar, "failed to allocate beacon buffer: %d\n",
ret);
goto err;
}
}
if (test_bit(ATH10K_FLAG_HW_CRYPTO_DISABLED, &ar->dev_flags))
arvif->nohwcrypt = true;
if (arvif->nohwcrypt &&
!test_bit(ATH10K_FLAG_RAW_MODE, &ar->dev_flags)) {
ath10k_warn(ar, "cryptmode module param needed for sw crypto\n");
goto err;
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev create %d (add interface) type %d subtype %d bcnmode %s\n",
arvif->vdev_id, arvif->vdev_type, arvif->vdev_subtype,
arvif->beacon_buf ? "single-buf" : "per-skb");
ret = ath10k_wmi_vdev_create(ar, arvif->vdev_id, arvif->vdev_type,
arvif->vdev_subtype, vif->addr);
if (ret) {
ath10k_warn(ar, "failed to create WMI vdev %i: %d\n",
arvif->vdev_id, ret);
goto err;
}
ar->free_vdev_map &= ~(1LL << arvif->vdev_id);
list_add(&arvif->list, &ar->arvifs);
/* It makes no sense to have firmware do keepalives. mac80211 already
* takes care of this with idle connection polling.
*/
ret = ath10k_mac_vif_disable_keepalive(arvif);
if (ret) {
ath10k_warn(ar, "failed to disable keepalive on vdev %i: %d\n",
arvif->vdev_id, ret);
goto err_vdev_delete;
}
arvif->def_wep_key_idx = -1;
vdev_param = ar->wmi.vdev_param->tx_encap_type;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
ATH10K_HW_TXRX_NATIVE_WIFI);
/* 10.X firmware does not support this VDEV parameter. Do not warn */
if (ret && ret != -EOPNOTSUPP) {
ath10k_warn(ar, "failed to set vdev %i TX encapsulation: %d\n",
arvif->vdev_id, ret);
goto err_vdev_delete;
}
if (ar->cfg_tx_chainmask) {
u16 nss = get_nss_from_chainmask(ar->cfg_tx_chainmask);
vdev_param = ar->wmi.vdev_param->nss;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
nss);
if (ret) {
ath10k_warn(ar, "failed to set vdev %i chainmask 0x%x, nss %i: %d\n",
arvif->vdev_id, ar->cfg_tx_chainmask, nss,
ret);
goto err_vdev_delete;
}
}
if (arvif->vdev_type == WMI_VDEV_TYPE_AP ||
arvif->vdev_type == WMI_VDEV_TYPE_IBSS) {
ret = ath10k_peer_create(ar, arvif->vdev_id, vif->addr,
WMI_PEER_TYPE_DEFAULT);
if (ret) {
ath10k_warn(ar, "failed to create vdev %i peer for AP/IBSS: %d\n",
arvif->vdev_id, ret);
goto err_vdev_delete;
}
}
if (arvif->vdev_type == WMI_VDEV_TYPE_AP) {
ret = ath10k_mac_set_kickout(arvif);
if (ret) {
ath10k_warn(ar, "failed to set vdev %i kickout parameters: %d\n",
arvif->vdev_id, ret);
goto err_peer_delete;
}
}
if (arvif->vdev_type == WMI_VDEV_TYPE_STA) {
param = WMI_STA_PS_PARAM_RX_WAKE_POLICY;
value = WMI_STA_PS_RX_WAKE_POLICY_WAKE;
ret = ath10k_wmi_set_sta_ps_param(ar, arvif->vdev_id,
param, value);
if (ret) {
ath10k_warn(ar, "failed to set vdev %i RX wake policy: %d\n",
arvif->vdev_id, ret);
goto err_peer_delete;
}
ret = ath10k_mac_vif_recalc_ps_wake_threshold(arvif);
if (ret) {
ath10k_warn(ar, "failed to recalc ps wake threshold on vdev %i: %d\n",
arvif->vdev_id, ret);
goto err_peer_delete;
}
ret = ath10k_mac_vif_recalc_ps_poll_count(arvif);
if (ret) {
ath10k_warn(ar, "failed to recalc ps poll count on vdev %i: %d\n",
arvif->vdev_id, ret);
goto err_peer_delete;
}
}
ret = ath10k_mac_set_txbf_conf(arvif);
if (ret) {
ath10k_warn(ar, "failed to set txbf for vdev %d: %d\n",
arvif->vdev_id, ret);
goto err_peer_delete;
}
ret = ath10k_mac_set_rts(arvif, ar->hw->wiphy->rts_threshold);
if (ret) {
ath10k_warn(ar, "failed to set rts threshold for vdev %d: %d\n",
arvif->vdev_id, ret);
goto err_peer_delete;
}
arvif->txpower = vif->bss_conf.txpower;
ret = ath10k_mac_txpower_recalc(ar);
if (ret) {
ath10k_warn(ar, "failed to recalc tx power: %d\n", ret);
goto err_peer_delete;
}
if (vif->type == NL80211_IFTYPE_MONITOR) {
ar->monitor_arvif = arvif;
ret = ath10k_monitor_recalc(ar);
if (ret) {
ath10k_warn(ar, "failed to recalc monitor: %d\n", ret);
goto err_peer_delete;
}
}
spin_lock_bh(&ar->htt.tx_lock);
if (!ar->tx_paused)
ieee80211_wake_queue(ar->hw, arvif->vdev_id);
spin_unlock_bh(&ar->htt.tx_lock);
mutex_unlock(&ar->conf_mutex);
return 0;
err_peer_delete:
if (arvif->vdev_type == WMI_VDEV_TYPE_AP ||
arvif->vdev_type == WMI_VDEV_TYPE_IBSS)
ath10k_wmi_peer_delete(ar, arvif->vdev_id, vif->addr);
err_vdev_delete:
ath10k_wmi_vdev_delete(ar, arvif->vdev_id);
ar->free_vdev_map |= 1LL << arvif->vdev_id;
list_del(&arvif->list);
err:
if (arvif->beacon_buf) {
dma_free_coherent(ar->dev, IEEE80211_MAX_FRAME_LEN,
arvif->beacon_buf, arvif->beacon_paddr);
arvif->beacon_buf = NULL;
}
mutex_unlock(&ar->conf_mutex);
return ret;
}
static void ath10k_mac_vif_tx_unlock_all(struct ath10k_vif *arvif)
{
int i;
for (i = 0; i < BITS_PER_LONG; i++)
ath10k_mac_vif_tx_unlock(arvif, i);
}
static void ath10k_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
int ret;
cancel_work_sync(&arvif->ap_csa_work);
cancel_delayed_work_sync(&arvif->connection_loss_work);
mutex_lock(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
ath10k_mac_vif_beacon_cleanup(arvif);
spin_unlock_bh(&ar->data_lock);
ret = ath10k_spectral_vif_stop(arvif);
if (ret)
ath10k_warn(ar, "failed to stop spectral for vdev %i: %d\n",
arvif->vdev_id, ret);
ar->free_vdev_map |= 1LL << arvif->vdev_id;
list_del(&arvif->list);
if (arvif->vdev_type == WMI_VDEV_TYPE_AP ||
arvif->vdev_type == WMI_VDEV_TYPE_IBSS) {
ret = ath10k_wmi_peer_delete(arvif->ar, arvif->vdev_id,
vif->addr);
if (ret)
ath10k_warn(ar, "failed to submit AP/IBSS self-peer removal on vdev %i: %d\n",
arvif->vdev_id, ret);
kfree(arvif->u.ap.noa_data);
}
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %i delete (remove interface)\n",
arvif->vdev_id);
ret = ath10k_wmi_vdev_delete(ar, arvif->vdev_id);
if (ret)
ath10k_warn(ar, "failed to delete WMI vdev %i: %d\n",
arvif->vdev_id, ret);
/* Some firmware revisions don't notify host about self-peer removal
* until after associated vdev is deleted.
*/
if (arvif->vdev_type == WMI_VDEV_TYPE_AP ||
arvif->vdev_type == WMI_VDEV_TYPE_IBSS) {
ret = ath10k_wait_for_peer_deleted(ar, arvif->vdev_id,
vif->addr);
if (ret)
ath10k_warn(ar, "failed to remove AP self-peer on vdev %i: %d\n",
arvif->vdev_id, ret);
spin_lock_bh(&ar->data_lock);
ar->num_peers--;
spin_unlock_bh(&ar->data_lock);
}
ath10k_peer_cleanup(ar, arvif->vdev_id);
if (vif->type == NL80211_IFTYPE_MONITOR) {
ar->monitor_arvif = NULL;
ret = ath10k_monitor_recalc(ar);
if (ret)
ath10k_warn(ar, "failed to recalc monitor: %d\n", ret);
}
spin_lock_bh(&ar->htt.tx_lock);
ath10k_mac_vif_tx_unlock_all(arvif);
spin_unlock_bh(&ar->htt.tx_lock);
mutex_unlock(&ar->conf_mutex);
}
/*
* FIXME: Has to be verified.
*/
#define SUPPORTED_FILTERS \
(FIF_ALLMULTI | \
FIF_CONTROL | \
FIF_PSPOLL | \
FIF_OTHER_BSS | \
FIF_BCN_PRBRESP_PROMISC | \
FIF_PROBE_REQ | \
FIF_FCSFAIL)
static void ath10k_configure_filter(struct ieee80211_hw *hw,
unsigned int changed_flags,
unsigned int *total_flags,
u64 multicast)
{
struct ath10k *ar = hw->priv;
int ret;
mutex_lock(&ar->conf_mutex);
changed_flags &= SUPPORTED_FILTERS;
*total_flags &= SUPPORTED_FILTERS;
ar->filter_flags = *total_flags;
ret = ath10k_monitor_recalc(ar);
if (ret)
ath10k_warn(ar, "failed to recalc montior: %d\n", ret);
mutex_unlock(&ar->conf_mutex);
}
static void ath10k_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *info,
u32 changed)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
int ret = 0;
u32 vdev_param, pdev_param, slottime, preamble;
mutex_lock(&ar->conf_mutex);
if (changed & BSS_CHANGED_IBSS)
ath10k_control_ibss(arvif, info, vif->addr);
if (changed & BSS_CHANGED_BEACON_INT) {
arvif->beacon_interval = info->beacon_int;
vdev_param = ar->wmi.vdev_param->beacon_interval;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
arvif->beacon_interval);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac vdev %d beacon_interval %d\n",
arvif->vdev_id, arvif->beacon_interval);
if (ret)
ath10k_warn(ar, "failed to set beacon interval for vdev %d: %i\n",
arvif->vdev_id, ret);
}
if (changed & BSS_CHANGED_BEACON) {
ath10k_dbg(ar, ATH10K_DBG_MAC,
"vdev %d set beacon tx mode to staggered\n",
arvif->vdev_id);
pdev_param = ar->wmi.pdev_param->beacon_tx_mode;
ret = ath10k_wmi_pdev_set_param(ar, pdev_param,
WMI_BEACON_STAGGERED_MODE);
if (ret)
ath10k_warn(ar, "failed to set beacon mode for vdev %d: %i\n",
arvif->vdev_id, ret);
ret = ath10k_mac_setup_bcn_tmpl(arvif);
if (ret)
ath10k_warn(ar, "failed to update beacon template: %d\n",
ret);
if (ieee80211_vif_is_mesh(vif)) {
/* mesh doesn't use SSID but firmware needs it */
strncpy(arvif->u.ap.ssid, "mesh",
sizeof(arvif->u.ap.ssid));
arvif->u.ap.ssid_len = 4;
}
}
if (changed & BSS_CHANGED_AP_PROBE_RESP) {
ret = ath10k_mac_setup_prb_tmpl(arvif);
if (ret)
ath10k_warn(ar, "failed to setup probe resp template on vdev %i: %d\n",
arvif->vdev_id, ret);
}
if (changed & (BSS_CHANGED_BEACON_INFO | BSS_CHANGED_BEACON)) {
arvif->dtim_period = info->dtim_period;
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac vdev %d dtim_period %d\n",
arvif->vdev_id, arvif->dtim_period);
vdev_param = ar->wmi.vdev_param->dtim_period;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
arvif->dtim_period);
if (ret)
ath10k_warn(ar, "failed to set dtim period for vdev %d: %i\n",
arvif->vdev_id, ret);
}
if (changed & BSS_CHANGED_SSID &&
vif->type == NL80211_IFTYPE_AP) {
arvif->u.ap.ssid_len = info->ssid_len;
if (info->ssid_len)
memcpy(arvif->u.ap.ssid, info->ssid, info->ssid_len);
arvif->u.ap.hidden_ssid = info->hidden_ssid;
}
if (changed & BSS_CHANGED_BSSID && !is_zero_ether_addr(info->bssid))
ether_addr_copy(arvif->bssid, info->bssid);
if (changed & BSS_CHANGED_BEACON_ENABLED)
ath10k_control_beaconing(arvif, info);
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
arvif->use_cts_prot = info->use_cts_prot;
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %d cts_prot %d\n",
arvif->vdev_id, info->use_cts_prot);
ret = ath10k_recalc_rtscts_prot(arvif);
if (ret)
ath10k_warn(ar, "failed to recalculate rts/cts prot for vdev %d: %d\n",
arvif->vdev_id, ret);
vdev_param = ar->wmi.vdev_param->protection_mode;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
info->use_cts_prot ? 1 : 0);
if (ret)
ath10k_warn(ar, "failed to set protection mode %d on vdev %i: %d\n",
info->use_cts_prot, arvif->vdev_id, ret);
}
if (changed & BSS_CHANGED_ERP_SLOT) {
if (info->use_short_slot)
slottime = WMI_VDEV_SLOT_TIME_SHORT; /* 9us */
else
slottime = WMI_VDEV_SLOT_TIME_LONG; /* 20us */
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %d slot_time %d\n",
arvif->vdev_id, slottime);
vdev_param = ar->wmi.vdev_param->slot_time;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
slottime);
if (ret)
ath10k_warn(ar, "failed to set erp slot for vdev %d: %i\n",
arvif->vdev_id, ret);
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
if (info->use_short_preamble)
preamble = WMI_VDEV_PREAMBLE_SHORT;
else
preamble = WMI_VDEV_PREAMBLE_LONG;
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac vdev %d preamble %dn",
arvif->vdev_id, preamble);
vdev_param = ar->wmi.vdev_param->preamble;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
preamble);
if (ret)
ath10k_warn(ar, "failed to set preamble for vdev %d: %i\n",
arvif->vdev_id, ret);
}
if (changed & BSS_CHANGED_ASSOC) {
if (info->assoc) {
/* Workaround: Make sure monitor vdev is not running
* when associating to prevent some firmware revisions
* (e.g. 10.1 and 10.2) from crashing.
*/
if (ar->monitor_started)
ath10k_monitor_stop(ar);
ath10k_bss_assoc(hw, vif, info);
ath10k_monitor_recalc(ar);
} else {
ath10k_bss_disassoc(hw, vif);
}
}
if (changed & BSS_CHANGED_TXPOWER) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev_id %i txpower %d\n",
arvif->vdev_id, info->txpower);
arvif->txpower = info->txpower;
ret = ath10k_mac_txpower_recalc(ar);
if (ret)
ath10k_warn(ar, "failed to recalc tx power: %d\n", ret);
}
if (changed & BSS_CHANGED_PS) {
arvif->ps = vif->bss_conf.ps;
ret = ath10k_config_ps(ar);
if (ret)
ath10k_warn(ar, "failed to setup ps on vdev %i: %d\n",
arvif->vdev_id, ret);
}
mutex_unlock(&ar->conf_mutex);
}
static int ath10k_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_scan_request *hw_req)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct cfg80211_scan_request *req = &hw_req->req;
struct wmi_start_scan_arg arg;
int ret = 0;
int i;
mutex_lock(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
switch (ar->scan.state) {
case ATH10K_SCAN_IDLE:
reinit_completion(&ar->scan.started);
reinit_completion(&ar->scan.completed);
ar->scan.state = ATH10K_SCAN_STARTING;
ar->scan.is_roc = false;
ar->scan.vdev_id = arvif->vdev_id;
ret = 0;
break;
case ATH10K_SCAN_STARTING:
case ATH10K_SCAN_RUNNING:
case ATH10K_SCAN_ABORTING:
ret = -EBUSY;
break;
}
spin_unlock_bh(&ar->data_lock);
if (ret)
goto exit;
memset(&arg, 0, sizeof(arg));
ath10k_wmi_start_scan_init(ar, &arg);
arg.vdev_id = arvif->vdev_id;
arg.scan_id = ATH10K_SCAN_ID;
if (req->ie_len) {
arg.ie_len = req->ie_len;
memcpy(arg.ie, req->ie, arg.ie_len);
}
if (req->n_ssids) {
arg.n_ssids = req->n_ssids;
for (i = 0; i < arg.n_ssids; i++) {
arg.ssids[i].len = req->ssids[i].ssid_len;
arg.ssids[i].ssid = req->ssids[i].ssid;
}
} else {
arg.scan_ctrl_flags |= WMI_SCAN_FLAG_PASSIVE;
}
if (req->n_channels) {
arg.n_channels = req->n_channels;
for (i = 0; i < arg.n_channels; i++)
arg.channels[i] = req->channels[i]->center_freq;
}
ret = ath10k_start_scan(ar, &arg);
if (ret) {
ath10k_warn(ar, "failed to start hw scan: %d\n", ret);
spin_lock_bh(&ar->data_lock);
ar->scan.state = ATH10K_SCAN_IDLE;
spin_unlock_bh(&ar->data_lock);
}
/* Add a 200ms margin to account for event/command processing */
ieee80211_queue_delayed_work(ar->hw, &ar->scan.timeout,
msecs_to_jiffies(arg.max_scan_time +
200));
exit:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static void ath10k_cancel_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ath10k *ar = hw->priv;
mutex_lock(&ar->conf_mutex);
ath10k_scan_abort(ar);
mutex_unlock(&ar->conf_mutex);
cancel_delayed_work_sync(&ar->scan.timeout);
}
static void ath10k_set_key_h_def_keyidx(struct ath10k *ar,
struct ath10k_vif *arvif,
enum set_key_cmd cmd,
struct ieee80211_key_conf *key)
{
u32 vdev_param = arvif->ar->wmi.vdev_param->def_keyid;
int ret;
/* 10.1 firmware branch requires default key index to be set to group
* key index after installing it. Otherwise FW/HW Txes corrupted
* frames with multi-vif APs. This is not required for main firmware
* branch (e.g. 636).
*
* This is also needed for 636 fw for IBSS-RSN to work more reliably.
*
* FIXME: It remains unknown if this is required for multi-vif STA
* interfaces on 10.1.
*/
if (arvif->vdev_type != WMI_VDEV_TYPE_AP &&
arvif->vdev_type != WMI_VDEV_TYPE_IBSS)
return;
if (key->cipher == WLAN_CIPHER_SUITE_WEP40)
return;
if (key->cipher == WLAN_CIPHER_SUITE_WEP104)
return;
if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE)
return;
if (cmd != SET_KEY)
return;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param,
key->keyidx);
if (ret)
ath10k_warn(ar, "failed to set vdev %i group key as default key: %d\n",
arvif->vdev_id, ret);
}
static int ath10k_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct ath10k_peer *peer;
const u8 *peer_addr;
bool is_wep = key->cipher == WLAN_CIPHER_SUITE_WEP40 ||
key->cipher == WLAN_CIPHER_SUITE_WEP104;
int ret = 0;
int ret2;
u32 flags = 0;
u32 flags2;
/* this one needs to be done in software */
if (key->cipher == WLAN_CIPHER_SUITE_AES_CMAC)
return 1;
if (arvif->nohwcrypt)
return 1;
if (key->keyidx > WMI_MAX_KEY_INDEX)
return -ENOSPC;
mutex_lock(&ar->conf_mutex);
if (sta)
peer_addr = sta->addr;
else if (arvif->vdev_type == WMI_VDEV_TYPE_STA)
peer_addr = vif->bss_conf.bssid;
else
peer_addr = vif->addr;
key->hw_key_idx = key->keyidx;
if (is_wep) {
if (cmd == SET_KEY)
arvif->wep_keys[key->keyidx] = key;
else
arvif->wep_keys[key->keyidx] = NULL;
}
/* the peer should not disappear in mid-way (unless FW goes awry) since
* we already hold conf_mutex. we just make sure its there now. */
spin_lock_bh(&ar->data_lock);
peer = ath10k_peer_find(ar, arvif->vdev_id, peer_addr);
spin_unlock_bh(&ar->data_lock);
if (!peer) {
if (cmd == SET_KEY) {
ath10k_warn(ar, "failed to install key for non-existent peer %pM\n",
peer_addr);
ret = -EOPNOTSUPP;
goto exit;
} else {
/* if the peer doesn't exist there is no key to disable
* anymore */
goto exit;
}
}
if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE)
flags |= WMI_KEY_PAIRWISE;
else
flags |= WMI_KEY_GROUP;
if (is_wep) {
if (cmd == DISABLE_KEY)
ath10k_clear_vdev_key(arvif, key);
/* When WEP keys are uploaded it's possible that there are
* stations associated already (e.g. when merging) without any
* keys. Static WEP needs an explicit per-peer key upload.
*/
if (vif->type == NL80211_IFTYPE_ADHOC &&
cmd == SET_KEY)
ath10k_mac_vif_update_wep_key(arvif, key);
/* 802.1x never sets the def_wep_key_idx so each set_key()
* call changes default tx key.
*
* Static WEP sets def_wep_key_idx via .set_default_unicast_key
* after first set_key().
*/
if (cmd == SET_KEY && arvif->def_wep_key_idx == -1)
flags |= WMI_KEY_TX_USAGE;
}
ret = ath10k_install_key(arvif, key, cmd, peer_addr, flags);
if (ret) {
WARN_ON(ret > 0);
ath10k_warn(ar, "failed to install key for vdev %i peer %pM: %d\n",
arvif->vdev_id, peer_addr, ret);
goto exit;
}
/* mac80211 sets static WEP keys as groupwise while firmware requires
* them to be installed twice as both pairwise and groupwise.
*/
if (is_wep && !sta && vif->type == NL80211_IFTYPE_STATION) {
flags2 = flags;
flags2 &= ~WMI_KEY_GROUP;
flags2 |= WMI_KEY_PAIRWISE;
ret = ath10k_install_key(arvif, key, cmd, peer_addr, flags2);
if (ret) {
WARN_ON(ret > 0);
ath10k_warn(ar, "failed to install (ucast) key for vdev %i peer %pM: %d\n",
arvif->vdev_id, peer_addr, ret);
ret2 = ath10k_install_key(arvif, key, DISABLE_KEY,
peer_addr, flags);
if (ret2) {
WARN_ON(ret2 > 0);
ath10k_warn(ar, "failed to disable (mcast) key for vdev %i peer %pM: %d\n",
arvif->vdev_id, peer_addr, ret2);
}
goto exit;
}
}
ath10k_set_key_h_def_keyidx(ar, arvif, cmd, key);
spin_lock_bh(&ar->data_lock);
peer = ath10k_peer_find(ar, arvif->vdev_id, peer_addr);
if (peer && cmd == SET_KEY)
peer->keys[key->keyidx] = key;
else if (peer && cmd == DISABLE_KEY)
peer->keys[key->keyidx] = NULL;
else if (peer == NULL)
/* impossible unless FW goes crazy */
ath10k_warn(ar, "Peer %pM disappeared!\n", peer_addr);
spin_unlock_bh(&ar->data_lock);
exit:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static void ath10k_set_default_unicast_key(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
int keyidx)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
int ret;
mutex_lock(&arvif->ar->conf_mutex);
if (arvif->ar->state != ATH10K_STATE_ON)
goto unlock;
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %d set keyidx %d\n",
arvif->vdev_id, keyidx);
ret = ath10k_wmi_vdev_set_param(arvif->ar,
arvif->vdev_id,
arvif->ar->wmi.vdev_param->def_keyid,
keyidx);
if (ret) {
ath10k_warn(ar, "failed to update wep key index for vdev %d: %d\n",
arvif->vdev_id,
ret);
goto unlock;
}
arvif->def_wep_key_idx = keyidx;
unlock:
mutex_unlock(&arvif->ar->conf_mutex);
}
static void ath10k_sta_rc_update_wk(struct work_struct *wk)
{
struct ath10k *ar;
struct ath10k_vif *arvif;
struct ath10k_sta *arsta;
struct ieee80211_sta *sta;
struct cfg80211_chan_def def;
enum ieee80211_band band;
const u8 *ht_mcs_mask;
const u16 *vht_mcs_mask;
u32 changed, bw, nss, smps;
int err;
arsta = container_of(wk, struct ath10k_sta, update_wk);
sta = container_of((void *)arsta, struct ieee80211_sta, drv_priv);
arvif = arsta->arvif;
ar = arvif->ar;
if (WARN_ON(ath10k_mac_vif_chan(arvif->vif, &def)))
return;
band = def.chan->band;
ht_mcs_mask = arvif->bitrate_mask.control[band].ht_mcs;
vht_mcs_mask = arvif->bitrate_mask.control[band].vht_mcs;
spin_lock_bh(&ar->data_lock);
changed = arsta->changed;
arsta->changed = 0;
bw = arsta->bw;
nss = arsta->nss;
smps = arsta->smps;
spin_unlock_bh(&ar->data_lock);
mutex_lock(&ar->conf_mutex);
nss = max_t(u32, 1, nss);
nss = min(nss, max(ath10k_mac_max_ht_nss(ht_mcs_mask),
ath10k_mac_max_vht_nss(vht_mcs_mask)));
if (changed & IEEE80211_RC_BW_CHANGED) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac update sta %pM peer bw %d\n",
sta->addr, bw);
err = ath10k_wmi_peer_set_param(ar, arvif->vdev_id, sta->addr,
WMI_PEER_CHAN_WIDTH, bw);
if (err)
ath10k_warn(ar, "failed to update STA %pM peer bw %d: %d\n",
sta->addr, bw, err);
}
if (changed & IEEE80211_RC_NSS_CHANGED) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac update sta %pM nss %d\n",
sta->addr, nss);
err = ath10k_wmi_peer_set_param(ar, arvif->vdev_id, sta->addr,
WMI_PEER_NSS, nss);
if (err)
ath10k_warn(ar, "failed to update STA %pM nss %d: %d\n",
sta->addr, nss, err);
}
if (changed & IEEE80211_RC_SMPS_CHANGED) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac update sta %pM smps %d\n",
sta->addr, smps);
err = ath10k_wmi_peer_set_param(ar, arvif->vdev_id, sta->addr,
WMI_PEER_SMPS_STATE, smps);
if (err)
ath10k_warn(ar, "failed to update STA %pM smps %d: %d\n",
sta->addr, smps, err);
}
if (changed & IEEE80211_RC_SUPP_RATES_CHANGED ||
changed & IEEE80211_RC_NSS_CHANGED) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac update sta %pM supp rates/nss\n",
sta->addr);
err = ath10k_station_assoc(ar, arvif->vif, sta, true);
if (err)
ath10k_warn(ar, "failed to reassociate station: %pM\n",
sta->addr);
}
mutex_unlock(&ar->conf_mutex);
}
static int ath10k_mac_inc_num_stations(struct ath10k_vif *arvif,
struct ieee80211_sta *sta)
{
struct ath10k *ar = arvif->ar;
lockdep_assert_held(&ar->conf_mutex);
if (arvif->vdev_type == WMI_VDEV_TYPE_STA && !sta->tdls)
return 0;
if (ar->num_stations >= ar->max_num_stations)
return -ENOBUFS;
ar->num_stations++;
return 0;
}
static void ath10k_mac_dec_num_stations(struct ath10k_vif *arvif,
struct ieee80211_sta *sta)
{
struct ath10k *ar = arvif->ar;
lockdep_assert_held(&ar->conf_mutex);
if (arvif->vdev_type == WMI_VDEV_TYPE_STA && !sta->tdls)
return;
ar->num_stations--;
}
struct ath10k_mac_tdls_iter_data {
u32 num_tdls_stations;
struct ieee80211_vif *curr_vif;
};
static void ath10k_mac_tdls_vif_stations_count_iter(void *data,
struct ieee80211_sta *sta)
{
struct ath10k_mac_tdls_iter_data *iter_data = data;
struct ath10k_sta *arsta = (struct ath10k_sta *)sta->drv_priv;
struct ieee80211_vif *sta_vif = arsta->arvif->vif;
if (sta->tdls && sta_vif == iter_data->curr_vif)
iter_data->num_tdls_stations++;
}
static int ath10k_mac_tdls_vif_stations_count(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ath10k_mac_tdls_iter_data data = {};
data.curr_vif = vif;
ieee80211_iterate_stations_atomic(hw,
ath10k_mac_tdls_vif_stations_count_iter,
&data);
return data.num_tdls_stations;
}
static void ath10k_mac_tdls_vifs_count_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
int *num_tdls_vifs = data;
if (vif->type != NL80211_IFTYPE_STATION)
return;
if (ath10k_mac_tdls_vif_stations_count(arvif->ar->hw, vif) > 0)
(*num_tdls_vifs)++;
}
static int ath10k_mac_tdls_vifs_count(struct ieee80211_hw *hw)
{
int num_tdls_vifs = 0;
ieee80211_iterate_active_interfaces_atomic(hw,
IEEE80211_IFACE_ITER_NORMAL,
ath10k_mac_tdls_vifs_count_iter,
&num_tdls_vifs);
return num_tdls_vifs;
}
static int ath10k_sta_state(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
enum ieee80211_sta_state old_state,
enum ieee80211_sta_state new_state)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct ath10k_sta *arsta = (struct ath10k_sta *)sta->drv_priv;
int ret = 0;
if (old_state == IEEE80211_STA_NOTEXIST &&
new_state == IEEE80211_STA_NONE) {
memset(arsta, 0, sizeof(*arsta));
arsta->arvif = arvif;
INIT_WORK(&arsta->update_wk, ath10k_sta_rc_update_wk);
}
/* cancel must be done outside the mutex to avoid deadlock */
if ((old_state == IEEE80211_STA_NONE &&
new_state == IEEE80211_STA_NOTEXIST))
cancel_work_sync(&arsta->update_wk);
mutex_lock(&ar->conf_mutex);
if (old_state == IEEE80211_STA_NOTEXIST &&
new_state == IEEE80211_STA_NONE) {
/*
* New station addition.
*/
enum wmi_peer_type peer_type = WMI_PEER_TYPE_DEFAULT;
u32 num_tdls_stations;
u32 num_tdls_vifs;
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac vdev %d peer create %pM (new sta) sta %d / %d peer %d / %d\n",
arvif->vdev_id, sta->addr,
ar->num_stations + 1, ar->max_num_stations,
ar->num_peers + 1, ar->max_num_peers);
ret = ath10k_mac_inc_num_stations(arvif, sta);
if (ret) {
ath10k_warn(ar, "refusing to associate station: too many connected already (%d)\n",
ar->max_num_stations);
goto exit;
}
if (sta->tdls)
peer_type = WMI_PEER_TYPE_TDLS;
ret = ath10k_peer_create(ar, arvif->vdev_id, sta->addr,
peer_type);
if (ret) {
ath10k_warn(ar, "failed to add peer %pM for vdev %d when adding a new sta: %i\n",
sta->addr, arvif->vdev_id, ret);
ath10k_mac_dec_num_stations(arvif, sta);
goto exit;
}
if (!sta->tdls)
goto exit;
num_tdls_stations = ath10k_mac_tdls_vif_stations_count(hw, vif);
num_tdls_vifs = ath10k_mac_tdls_vifs_count(hw);
if (num_tdls_vifs >= ar->max_num_tdls_vdevs &&
num_tdls_stations == 0) {
ath10k_warn(ar, "vdev %i exceeded maximum number of tdls vdevs %i\n",
arvif->vdev_id, ar->max_num_tdls_vdevs);
ath10k_peer_delete(ar, arvif->vdev_id, sta->addr);
ath10k_mac_dec_num_stations(arvif, sta);
ret = -ENOBUFS;
goto exit;
}
if (num_tdls_stations == 0) {
/* This is the first tdls peer in current vif */
enum wmi_tdls_state state = WMI_TDLS_ENABLE_ACTIVE;
ret = ath10k_wmi_update_fw_tdls_state(ar, arvif->vdev_id,
state);
if (ret) {
ath10k_warn(ar, "failed to update fw tdls state on vdev %i: %i\n",
arvif->vdev_id, ret);
ath10k_peer_delete(ar, arvif->vdev_id,
sta->addr);
ath10k_mac_dec_num_stations(arvif, sta);
goto exit;
}
}
ret = ath10k_mac_tdls_peer_update(ar, arvif->vdev_id, sta,
WMI_TDLS_PEER_STATE_PEERING);
if (ret) {
ath10k_warn(ar,
"failed to update tdls peer %pM for vdev %d when adding a new sta: %i\n",
sta->addr, arvif->vdev_id, ret);
ath10k_peer_delete(ar, arvif->vdev_id, sta->addr);
ath10k_mac_dec_num_stations(arvif, sta);
if (num_tdls_stations != 0)
goto exit;
ath10k_wmi_update_fw_tdls_state(ar, arvif->vdev_id,
WMI_TDLS_DISABLE);
}
} else if ((old_state == IEEE80211_STA_NONE &&
new_state == IEEE80211_STA_NOTEXIST)) {
/*
* Existing station deletion.
*/
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac vdev %d peer delete %pM (sta gone)\n",
arvif->vdev_id, sta->addr);
ret = ath10k_peer_delete(ar, arvif->vdev_id, sta->addr);
if (ret)
ath10k_warn(ar, "failed to delete peer %pM for vdev %d: %i\n",
sta->addr, arvif->vdev_id, ret);
ath10k_mac_dec_num_stations(arvif, sta);
if (!sta->tdls)
goto exit;
if (ath10k_mac_tdls_vif_stations_count(hw, vif))
goto exit;
/* This was the last tdls peer in current vif */
ret = ath10k_wmi_update_fw_tdls_state(ar, arvif->vdev_id,
WMI_TDLS_DISABLE);
if (ret) {
ath10k_warn(ar, "failed to update fw tdls state on vdev %i: %i\n",
arvif->vdev_id, ret);
}
} else if (old_state == IEEE80211_STA_AUTH &&
new_state == IEEE80211_STA_ASSOC &&
(vif->type == NL80211_IFTYPE_AP ||
vif->type == NL80211_IFTYPE_MESH_POINT ||
vif->type == NL80211_IFTYPE_ADHOC)) {
/*
* New association.
*/
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac sta %pM associated\n",
sta->addr);
ret = ath10k_station_assoc(ar, vif, sta, false);
if (ret)
ath10k_warn(ar, "failed to associate station %pM for vdev %i: %i\n",
sta->addr, arvif->vdev_id, ret);
} else if (old_state == IEEE80211_STA_ASSOC &&
new_state == IEEE80211_STA_AUTHORIZED &&
sta->tdls) {
/*
* Tdls station authorized.
*/
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac tdls sta %pM authorized\n",
sta->addr);
ret = ath10k_station_assoc(ar, vif, sta, false);
if (ret) {
ath10k_warn(ar, "failed to associate tdls station %pM for vdev %i: %i\n",
sta->addr, arvif->vdev_id, ret);
goto exit;
}
ret = ath10k_mac_tdls_peer_update(ar, arvif->vdev_id, sta,
WMI_TDLS_PEER_STATE_CONNECTED);
if (ret)
ath10k_warn(ar, "failed to update tdls peer %pM for vdev %i: %i\n",
sta->addr, arvif->vdev_id, ret);
} else if (old_state == IEEE80211_STA_ASSOC &&
new_state == IEEE80211_STA_AUTH &&
(vif->type == NL80211_IFTYPE_AP ||
vif->type == NL80211_IFTYPE_MESH_POINT ||
vif->type == NL80211_IFTYPE_ADHOC)) {
/*
* Disassociation.
*/
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac sta %pM disassociated\n",
sta->addr);
ret = ath10k_station_disassoc(ar, vif, sta);
if (ret)
ath10k_warn(ar, "failed to disassociate station: %pM vdev %i: %i\n",
sta->addr, arvif->vdev_id, ret);
}
exit:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static int ath10k_conf_tx_uapsd(struct ath10k *ar, struct ieee80211_vif *vif,
u16 ac, bool enable)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct wmi_sta_uapsd_auto_trig_arg arg = {};
u32 prio = 0, acc = 0;
u32 value = 0;
int ret = 0;
lockdep_assert_held(&ar->conf_mutex);
if (arvif->vdev_type != WMI_VDEV_TYPE_STA)
return 0;
switch (ac) {
case IEEE80211_AC_VO:
value = WMI_STA_PS_UAPSD_AC3_DELIVERY_EN |
WMI_STA_PS_UAPSD_AC3_TRIGGER_EN;
prio = 7;
acc = 3;
break;
case IEEE80211_AC_VI:
value = WMI_STA_PS_UAPSD_AC2_DELIVERY_EN |
WMI_STA_PS_UAPSD_AC2_TRIGGER_EN;
prio = 5;
acc = 2;
break;
case IEEE80211_AC_BE:
value = WMI_STA_PS_UAPSD_AC1_DELIVERY_EN |
WMI_STA_PS_UAPSD_AC1_TRIGGER_EN;
prio = 2;
acc = 1;
break;
case IEEE80211_AC_BK:
value = WMI_STA_PS_UAPSD_AC0_DELIVERY_EN |
WMI_STA_PS_UAPSD_AC0_TRIGGER_EN;
prio = 0;
acc = 0;
break;
}
if (enable)
arvif->u.sta.uapsd |= value;
else
arvif->u.sta.uapsd &= ~value;
ret = ath10k_wmi_set_sta_ps_param(ar, arvif->vdev_id,
WMI_STA_PS_PARAM_UAPSD,
arvif->u.sta.uapsd);
if (ret) {
ath10k_warn(ar, "failed to set uapsd params: %d\n", ret);
goto exit;
}
if (arvif->u.sta.uapsd)
value = WMI_STA_PS_RX_WAKE_POLICY_POLL_UAPSD;
else
value = WMI_STA_PS_RX_WAKE_POLICY_WAKE;
ret = ath10k_wmi_set_sta_ps_param(ar, arvif->vdev_id,
WMI_STA_PS_PARAM_RX_WAKE_POLICY,
value);
if (ret)
ath10k_warn(ar, "failed to set rx wake param: %d\n", ret);
ret = ath10k_mac_vif_recalc_ps_wake_threshold(arvif);
if (ret) {
ath10k_warn(ar, "failed to recalc ps wake threshold on vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
ret = ath10k_mac_vif_recalc_ps_poll_count(arvif);
if (ret) {
ath10k_warn(ar, "failed to recalc ps poll count on vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
if (test_bit(WMI_SERVICE_STA_UAPSD_BASIC_AUTO_TRIG, ar->wmi.svc_map) ||
test_bit(WMI_SERVICE_STA_UAPSD_VAR_AUTO_TRIG, ar->wmi.svc_map)) {
/* Only userspace can make an educated decision when to send
* trigger frame. The following effectively disables u-UAPSD
* autotrigger in firmware (which is enabled by default
* provided the autotrigger service is available).
*/
arg.wmm_ac = acc;
arg.user_priority = prio;
arg.service_interval = 0;
arg.suspend_interval = WMI_STA_UAPSD_MAX_INTERVAL_MSEC;
arg.delay_interval = WMI_STA_UAPSD_MAX_INTERVAL_MSEC;
ret = ath10k_wmi_vdev_sta_uapsd(ar, arvif->vdev_id,
arvif->bssid, &arg, 1);
if (ret) {
ath10k_warn(ar, "failed to set uapsd auto trigger %d\n",
ret);
return ret;
}
}
exit:
return ret;
}
static int ath10k_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 ac,
const struct ieee80211_tx_queue_params *params)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct wmi_wmm_params_arg *p = NULL;
int ret;
mutex_lock(&ar->conf_mutex);
switch (ac) {
case IEEE80211_AC_VO:
p = &arvif->wmm_params.ac_vo;
break;
case IEEE80211_AC_VI:
p = &arvif->wmm_params.ac_vi;
break;
case IEEE80211_AC_BE:
p = &arvif->wmm_params.ac_be;
break;
case IEEE80211_AC_BK:
p = &arvif->wmm_params.ac_bk;
break;
}
if (WARN_ON(!p)) {
ret = -EINVAL;
goto exit;
}
p->cwmin = params->cw_min;
p->cwmax = params->cw_max;
p->aifs = params->aifs;
/*
* The channel time duration programmed in the HW is in absolute
* microseconds, while mac80211 gives the txop in units of
* 32 microseconds.
*/
p->txop = params->txop * 32;
if (ar->wmi.ops->gen_vdev_wmm_conf) {
ret = ath10k_wmi_vdev_wmm_conf(ar, arvif->vdev_id,
&arvif->wmm_params);
if (ret) {
ath10k_warn(ar, "failed to set vdev wmm params on vdev %i: %d\n",
arvif->vdev_id, ret);
goto exit;
}
} else {
/* This won't work well with multi-interface cases but it's
* better than nothing.
*/
ret = ath10k_wmi_pdev_set_wmm_params(ar, &arvif->wmm_params);
if (ret) {
ath10k_warn(ar, "failed to set wmm params: %d\n", ret);
goto exit;
}
}
ret = ath10k_conf_tx_uapsd(ar, vif, ac, params->uapsd);
if (ret)
ath10k_warn(ar, "failed to set sta uapsd: %d\n", ret);
exit:
mutex_unlock(&ar->conf_mutex);
return ret;
}
#define ATH10K_ROC_TIMEOUT_HZ (2*HZ)
static int ath10k_remain_on_channel(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_channel *chan,
int duration,
enum ieee80211_roc_type type)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct wmi_start_scan_arg arg;
int ret = 0;
u32 scan_time_msec;
mutex_lock(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
switch (ar->scan.state) {
case ATH10K_SCAN_IDLE:
reinit_completion(&ar->scan.started);
reinit_completion(&ar->scan.completed);
reinit_completion(&ar->scan.on_channel);
ar->scan.state = ATH10K_SCAN_STARTING;
ar->scan.is_roc = true;
ar->scan.vdev_id = arvif->vdev_id;
ar->scan.roc_freq = chan->center_freq;
ar->scan.roc_notify = true;
ret = 0;
break;
case ATH10K_SCAN_STARTING:
case ATH10K_SCAN_RUNNING:
case ATH10K_SCAN_ABORTING:
ret = -EBUSY;
break;
}
spin_unlock_bh(&ar->data_lock);
if (ret)
goto exit;
scan_time_msec = ar->hw->wiphy->max_remain_on_channel_duration * 2;
memset(&arg, 0, sizeof(arg));
ath10k_wmi_start_scan_init(ar, &arg);
arg.vdev_id = arvif->vdev_id;
arg.scan_id = ATH10K_SCAN_ID;
arg.n_channels = 1;
arg.channels[0] = chan->center_freq;
arg.dwell_time_active = scan_time_msec;
arg.dwell_time_passive = scan_time_msec;
arg.max_scan_time = scan_time_msec;
arg.scan_ctrl_flags |= WMI_SCAN_FLAG_PASSIVE;
arg.scan_ctrl_flags |= WMI_SCAN_FILTER_PROBE_REQ;
arg.burst_duration_ms = duration;
ret = ath10k_start_scan(ar, &arg);
if (ret) {
ath10k_warn(ar, "failed to start roc scan: %d\n", ret);
spin_lock_bh(&ar->data_lock);
ar->scan.state = ATH10K_SCAN_IDLE;
spin_unlock_bh(&ar->data_lock);
goto exit;
}
ret = wait_for_completion_timeout(&ar->scan.on_channel, 3*HZ);
if (ret == 0) {
ath10k_warn(ar, "failed to switch to channel for roc scan\n");
ret = ath10k_scan_stop(ar);
if (ret)
ath10k_warn(ar, "failed to stop scan: %d\n", ret);
ret = -ETIMEDOUT;
goto exit;
}
ieee80211_queue_delayed_work(ar->hw, &ar->scan.timeout,
msecs_to_jiffies(duration));
ret = 0;
exit:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static int ath10k_cancel_remain_on_channel(struct ieee80211_hw *hw)
{
struct ath10k *ar = hw->priv;
mutex_lock(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
ar->scan.roc_notify = false;
spin_unlock_bh(&ar->data_lock);
ath10k_scan_abort(ar);
mutex_unlock(&ar->conf_mutex);
cancel_delayed_work_sync(&ar->scan.timeout);
return 0;
}
/*
* Both RTS and Fragmentation threshold are interface-specific
* in ath10k, but device-specific in mac80211.
*/
static int ath10k_set_rts_threshold(struct ieee80211_hw *hw, u32 value)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif;
int ret = 0;
mutex_lock(&ar->conf_mutex);
list_for_each_entry(arvif, &ar->arvifs, list) {
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac vdev %d rts threshold %d\n",
arvif->vdev_id, value);
ret = ath10k_mac_set_rts(arvif, value);
if (ret) {
ath10k_warn(ar, "failed to set rts threshold for vdev %d: %d\n",
arvif->vdev_id, ret);
break;
}
}
mutex_unlock(&ar->conf_mutex);
return ret;
}
static int ath10k_mac_op_set_frag_threshold(struct ieee80211_hw *hw, u32 value)
{
/* Even though there's a WMI enum for fragmentation threshold no known
* firmware actually implements it. Moreover it is not possible to rely
* frame fragmentation to mac80211 because firmware clears the "more
* fragments" bit in frame control making it impossible for remote
* devices to reassemble frames.
*
* Hence implement a dummy callback just to say fragmentation isn't
* supported. This effectively prevents mac80211 from doing frame
* fragmentation in software.
*/
return -EOPNOTSUPP;
}
static void ath10k_flush(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
u32 queues, bool drop)
{
struct ath10k *ar = hw->priv;
bool skip;
long time_left;
/* mac80211 doesn't care if we really xmit queued frames or not
* we'll collect those frames either way if we stop/delete vdevs */
if (drop)
return;
mutex_lock(&ar->conf_mutex);
if (ar->state == ATH10K_STATE_WEDGED)
goto skip;
time_left = wait_event_timeout(ar->htt.empty_tx_wq, ({
bool empty;
spin_lock_bh(&ar->htt.tx_lock);
empty = (ar->htt.num_pending_tx == 0);
spin_unlock_bh(&ar->htt.tx_lock);
skip = (ar->state == ATH10K_STATE_WEDGED) ||
test_bit(ATH10K_FLAG_CRASH_FLUSH,
&ar->dev_flags);
(empty || skip);
}), ATH10K_FLUSH_TIMEOUT_HZ);
if (time_left == 0 || skip)
ath10k_warn(ar, "failed to flush transmit queue (skip %i ar-state %i): %ld\n",
skip, ar->state, time_left);
skip:
mutex_unlock(&ar->conf_mutex);
}
/* TODO: Implement this function properly
* For now it is needed to reply to Probe Requests in IBSS mode.
* Propably we need this information from FW.
*/
static int ath10k_tx_last_beacon(struct ieee80211_hw *hw)
{
return 1;
}
static void ath10k_reconfig_complete(struct ieee80211_hw *hw,
enum ieee80211_reconfig_type reconfig_type)
{
struct ath10k *ar = hw->priv;
if (reconfig_type != IEEE80211_RECONFIG_TYPE_RESTART)
return;
mutex_lock(&ar->conf_mutex);
/* If device failed to restart it will be in a different state, e.g.
* ATH10K_STATE_WEDGED */
if (ar->state == ATH10K_STATE_RESTARTED) {
ath10k_info(ar, "device successfully recovered\n");
ar->state = ATH10K_STATE_ON;
ieee80211_wake_queues(ar->hw);
}
mutex_unlock(&ar->conf_mutex);
}
static int ath10k_get_survey(struct ieee80211_hw *hw, int idx,
struct survey_info *survey)
{
struct ath10k *ar = hw->priv;
struct ieee80211_supported_band *sband;
struct survey_info *ar_survey = &ar->survey[idx];
int ret = 0;
mutex_lock(&ar->conf_mutex);
sband = hw->wiphy->bands[IEEE80211_BAND_2GHZ];
if (sband && idx >= sband->n_channels) {
idx -= sband->n_channels;
sband = NULL;
}
if (!sband)
sband = hw->wiphy->bands[IEEE80211_BAND_5GHZ];
if (!sband || idx >= sband->n_channels) {
ret = -ENOENT;
goto exit;
}
spin_lock_bh(&ar->data_lock);
memcpy(survey, ar_survey, sizeof(*survey));
spin_unlock_bh(&ar->data_lock);
survey->channel = &sband->channels[idx];
if (ar->rx_channel == survey->channel)
survey->filled |= SURVEY_INFO_IN_USE;
exit:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static bool
ath10k_mac_bitrate_mask_has_single_rate(struct ath10k *ar,
enum ieee80211_band band,
const struct cfg80211_bitrate_mask *mask)
{
int num_rates = 0;
int i;
num_rates += hweight32(mask->control[band].legacy);
for (i = 0; i < ARRAY_SIZE(mask->control[band].ht_mcs); i++)
num_rates += hweight8(mask->control[band].ht_mcs[i]);
for (i = 0; i < ARRAY_SIZE(mask->control[band].vht_mcs); i++)
num_rates += hweight16(mask->control[band].vht_mcs[i]);
return num_rates == 1;
}
static bool
ath10k_mac_bitrate_mask_get_single_nss(struct ath10k *ar,
enum ieee80211_band band,
const struct cfg80211_bitrate_mask *mask,
int *nss)
{
struct ieee80211_supported_band *sband = &ar->mac.sbands[band];
u16 vht_mcs_map = le16_to_cpu(sband->vht_cap.vht_mcs.tx_mcs_map);
u8 ht_nss_mask = 0;
u8 vht_nss_mask = 0;
int i;
if (mask->control[band].legacy)
return false;
for (i = 0; i < ARRAY_SIZE(mask->control[band].ht_mcs); i++) {
if (mask->control[band].ht_mcs[i] == 0)
continue;
else if (mask->control[band].ht_mcs[i] ==
sband->ht_cap.mcs.rx_mask[i])
ht_nss_mask |= BIT(i);
else
return false;
}
for (i = 0; i < ARRAY_SIZE(mask->control[band].vht_mcs); i++) {
if (mask->control[band].vht_mcs[i] == 0)
continue;
else if (mask->control[band].vht_mcs[i] ==
ath10k_mac_get_max_vht_mcs_map(vht_mcs_map, i))
vht_nss_mask |= BIT(i);
else
return false;
}
if (ht_nss_mask != vht_nss_mask)
return false;
if (ht_nss_mask == 0)
return false;
if (BIT(fls(ht_nss_mask)) - 1 != ht_nss_mask)
return false;
*nss = fls(ht_nss_mask);
return true;
}
static int
ath10k_mac_bitrate_mask_get_single_rate(struct ath10k *ar,
enum ieee80211_band band,
const struct cfg80211_bitrate_mask *mask,
u8 *rate, u8 *nss)
{
struct ieee80211_supported_band *sband = &ar->mac.sbands[band];
int rate_idx;
int i;
u16 bitrate;
u8 preamble;
u8 hw_rate;
if (hweight32(mask->control[band].legacy) == 1) {
rate_idx = ffs(mask->control[band].legacy) - 1;
hw_rate = sband->bitrates[rate_idx].hw_value;
bitrate = sband->bitrates[rate_idx].bitrate;
if (ath10k_mac_bitrate_is_cck(bitrate))
preamble = WMI_RATE_PREAMBLE_CCK;
else
preamble = WMI_RATE_PREAMBLE_OFDM;
*nss = 1;
*rate = preamble << 6 |
(*nss - 1) << 4 |
hw_rate << 0;
return 0;
}
for (i = 0; i < ARRAY_SIZE(mask->control[band].ht_mcs); i++) {
if (hweight8(mask->control[band].ht_mcs[i]) == 1) {
*nss = i + 1;
*rate = WMI_RATE_PREAMBLE_HT << 6 |
(*nss - 1) << 4 |
(ffs(mask->control[band].ht_mcs[i]) - 1);
return 0;
}
}
for (i = 0; i < ARRAY_SIZE(mask->control[band].vht_mcs); i++) {
if (hweight16(mask->control[band].vht_mcs[i]) == 1) {
*nss = i + 1;
*rate = WMI_RATE_PREAMBLE_VHT << 6 |
(*nss - 1) << 4 |
(ffs(mask->control[band].vht_mcs[i]) - 1);
return 0;
}
}
return -EINVAL;
}
static int ath10k_mac_set_fixed_rate_params(struct ath10k_vif *arvif,
u8 rate, u8 nss, u8 sgi, u8 ldpc)
{
struct ath10k *ar = arvif->ar;
u32 vdev_param;
int ret;
lockdep_assert_held(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac set fixed rate params vdev %i rate 0x%02hhx nss %hhu sgi %hhu\n",
arvif->vdev_id, rate, nss, sgi);
vdev_param = ar->wmi.vdev_param->fixed_rate;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param, rate);
if (ret) {
ath10k_warn(ar, "failed to set fixed rate param 0x%02x: %d\n",
rate, ret);
return ret;
}
vdev_param = ar->wmi.vdev_param->nss;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param, nss);
if (ret) {
ath10k_warn(ar, "failed to set nss param %d: %d\n", nss, ret);
return ret;
}
vdev_param = ar->wmi.vdev_param->sgi;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param, sgi);
if (ret) {
ath10k_warn(ar, "failed to set sgi param %d: %d\n", sgi, ret);
return ret;
}
vdev_param = ar->wmi.vdev_param->ldpc;
ret = ath10k_wmi_vdev_set_param(ar, arvif->vdev_id, vdev_param, ldpc);
if (ret) {
ath10k_warn(ar, "failed to set ldpc param %d: %d\n", ldpc, ret);
return ret;
}
return 0;
}
static bool
ath10k_mac_can_set_bitrate_mask(struct ath10k *ar,
enum ieee80211_band band,
const struct cfg80211_bitrate_mask *mask)
{
int i;
u16 vht_mcs;
/* Due to firmware limitation in WMI_PEER_ASSOC_CMDID it is impossible
* to express all VHT MCS rate masks. Effectively only the following
* ranges can be used: none, 0-7, 0-8 and 0-9.
*/
for (i = 0; i < NL80211_VHT_NSS_MAX; i++) {
vht_mcs = mask->control[band].vht_mcs[i];
switch (vht_mcs) {
case 0:
case BIT(8) - 1:
case BIT(9) - 1:
case BIT(10) - 1:
break;
default:
ath10k_warn(ar, "refusing bitrate mask with missing 0-7 VHT MCS rates\n");
return false;
}
}
return true;
}
static void ath10k_mac_set_bitrate_mask_iter(void *data,
struct ieee80211_sta *sta)
{
struct ath10k_vif *arvif = data;
struct ath10k_sta *arsta = (struct ath10k_sta *)sta->drv_priv;
struct ath10k *ar = arvif->ar;
if (arsta->arvif != arvif)
return;
spin_lock_bh(&ar->data_lock);
arsta->changed |= IEEE80211_RC_SUPP_RATES_CHANGED;
spin_unlock_bh(&ar->data_lock);
ieee80211_queue_work(ar->hw, &arsta->update_wk);
}
static int ath10k_mac_op_set_bitrate_mask(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const struct cfg80211_bitrate_mask *mask)
{
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
struct cfg80211_chan_def def;
struct ath10k *ar = arvif->ar;
enum ieee80211_band band;
const u8 *ht_mcs_mask;
const u16 *vht_mcs_mask;
u8 rate;
u8 nss;
u8 sgi;
u8 ldpc;
int single_nss;
int ret;
if (ath10k_mac_vif_chan(vif, &def))
return -EPERM;
band = def.chan->band;
ht_mcs_mask = mask->control[band].ht_mcs;
vht_mcs_mask = mask->control[band].vht_mcs;
ldpc = !!(ar->ht_cap_info & WMI_HT_CAP_LDPC);
sgi = mask->control[band].gi;
if (sgi == NL80211_TXRATE_FORCE_LGI)
return -EINVAL;
if (ath10k_mac_bitrate_mask_has_single_rate(ar, band, mask)) {
ret = ath10k_mac_bitrate_mask_get_single_rate(ar, band, mask,
&rate, &nss);
if (ret) {
ath10k_warn(ar, "failed to get single rate for vdev %i: %d\n",
arvif->vdev_id, ret);
return ret;
}
} else if (ath10k_mac_bitrate_mask_get_single_nss(ar, band, mask,
&single_nss)) {
rate = WMI_FIXED_RATE_NONE;
nss = single_nss;
} else {
rate = WMI_FIXED_RATE_NONE;
nss = min(ar->num_rf_chains,
max(ath10k_mac_max_ht_nss(ht_mcs_mask),
ath10k_mac_max_vht_nss(vht_mcs_mask)));
if (!ath10k_mac_can_set_bitrate_mask(ar, band, mask))
return -EINVAL;
mutex_lock(&ar->conf_mutex);
arvif->bitrate_mask = *mask;
ieee80211_iterate_stations_atomic(ar->hw,
ath10k_mac_set_bitrate_mask_iter,
arvif);
mutex_unlock(&ar->conf_mutex);
}
mutex_lock(&ar->conf_mutex);
ret = ath10k_mac_set_fixed_rate_params(arvif, rate, nss, sgi, ldpc);
if (ret) {
ath10k_warn(ar, "failed to set fixed rate params on vdev %i: %d\n",
arvif->vdev_id, ret);
goto exit;
}
exit:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static void ath10k_sta_rc_update(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
u32 changed)
{
struct ath10k *ar = hw->priv;
struct ath10k_sta *arsta = (struct ath10k_sta *)sta->drv_priv;
u32 bw, smps;
spin_lock_bh(&ar->data_lock);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac sta rc update for %pM changed %08x bw %d nss %d smps %d\n",
sta->addr, changed, sta->bandwidth, sta->rx_nss,
sta->smps_mode);
if (changed & IEEE80211_RC_BW_CHANGED) {
bw = WMI_PEER_CHWIDTH_20MHZ;
switch (sta->bandwidth) {
case IEEE80211_STA_RX_BW_20:
bw = WMI_PEER_CHWIDTH_20MHZ;
break;
case IEEE80211_STA_RX_BW_40:
bw = WMI_PEER_CHWIDTH_40MHZ;
break;
case IEEE80211_STA_RX_BW_80:
bw = WMI_PEER_CHWIDTH_80MHZ;
break;
case IEEE80211_STA_RX_BW_160:
ath10k_warn(ar, "Invalid bandwidth %d in rc update for %pM\n",
sta->bandwidth, sta->addr);
bw = WMI_PEER_CHWIDTH_20MHZ;
break;
}
arsta->bw = bw;
}
if (changed & IEEE80211_RC_NSS_CHANGED)
arsta->nss = sta->rx_nss;
if (changed & IEEE80211_RC_SMPS_CHANGED) {
smps = WMI_PEER_SMPS_PS_NONE;
switch (sta->smps_mode) {
case IEEE80211_SMPS_AUTOMATIC:
case IEEE80211_SMPS_OFF:
smps = WMI_PEER_SMPS_PS_NONE;
break;
case IEEE80211_SMPS_STATIC:
smps = WMI_PEER_SMPS_STATIC;
break;
case IEEE80211_SMPS_DYNAMIC:
smps = WMI_PEER_SMPS_DYNAMIC;
break;
case IEEE80211_SMPS_NUM_MODES:
ath10k_warn(ar, "Invalid smps %d in sta rc update for %pM\n",
sta->smps_mode, sta->addr);
smps = WMI_PEER_SMPS_PS_NONE;
break;
}
arsta->smps = smps;
}
arsta->changed |= changed;
spin_unlock_bh(&ar->data_lock);
ieee80211_queue_work(hw, &arsta->update_wk);
}
static u64 ath10k_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
/*
* FIXME: Return 0 for time being. Need to figure out whether FW
* has the API to fetch 64-bit local TSF
*/
return 0;
}
static int ath10k_ampdu_action(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum ieee80211_ampdu_mlme_action action,
struct ieee80211_sta *sta, u16 tid, u16 *ssn,
u8 buf_size, bool amsdu)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
ath10k_dbg(ar, ATH10K_DBG_MAC, "mac ampdu vdev_id %i sta %pM tid %hu action %d\n",
arvif->vdev_id, sta->addr, tid, action);
switch (action) {
case IEEE80211_AMPDU_RX_START:
case IEEE80211_AMPDU_RX_STOP:
/* HTT AddBa/DelBa events trigger mac80211 Rx BA session
* creation/removal. Do we need to verify this?
*/
return 0;
case IEEE80211_AMPDU_TX_START:
case IEEE80211_AMPDU_TX_STOP_CONT:
case IEEE80211_AMPDU_TX_STOP_FLUSH:
case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT:
case IEEE80211_AMPDU_TX_OPERATIONAL:
/* Firmware offloads Tx aggregation entirely so deny mac80211
* Tx aggregation requests.
*/
return -EOPNOTSUPP;
}
return -EINVAL;
}
static void
ath10k_mac_update_rx_channel(struct ath10k *ar,
struct ieee80211_chanctx_conf *ctx,
struct ieee80211_vif_chanctx_switch *vifs,
int n_vifs)
{
struct cfg80211_chan_def *def = NULL;
/* Both locks are required because ar->rx_channel is modified. This
* allows readers to hold either lock.
*/
lockdep_assert_held(&ar->conf_mutex);
lockdep_assert_held(&ar->data_lock);
WARN_ON(ctx && vifs);
WARN_ON(vifs && n_vifs != 1);
/* FIXME: Sort of an optimization and a workaround. Peers and vifs are
* on a linked list now. Doing a lookup peer -> vif -> chanctx for each
* ppdu on Rx may reduce performance on low-end systems. It should be
* possible to make tables/hashmaps to speed the lookup up (be vary of
* cpu data cache lines though regarding sizes) but to keep the initial
* implementation simple and less intrusive fallback to the slow lookup
* only for multi-channel cases. Single-channel cases will remain to
* use the old channel derival and thus performance should not be
* affected much.
*/
rcu_read_lock();
if (!ctx && ath10k_mac_num_chanctxs(ar) == 1) {
ieee80211_iter_chan_contexts_atomic(ar->hw,
ath10k_mac_get_any_chandef_iter,
&def);
if (vifs)
def = &vifs[0].new_ctx->def;
ar->rx_channel = def->chan;
} else if (ctx && ath10k_mac_num_chanctxs(ar) == 0) {
ar->rx_channel = ctx->def.chan;
} else {
ar->rx_channel = NULL;
}
rcu_read_unlock();
}
static void
ath10k_mac_update_vif_chan(struct ath10k *ar,
struct ieee80211_vif_chanctx_switch *vifs,
int n_vifs)
{
struct ath10k_vif *arvif;
int ret;
int i;
lockdep_assert_held(&ar->conf_mutex);
/* First stop monitor interface. Some FW versions crash if there's a
* lone monitor interface.
*/
if (ar->monitor_started)
ath10k_monitor_stop(ar);
for (i = 0; i < n_vifs; i++) {
arvif = ath10k_vif_to_arvif(vifs[i].vif);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac chanctx switch vdev_id %i freq %hu->%hu width %d->%d\n",
arvif->vdev_id,
vifs[i].old_ctx->def.chan->center_freq,
vifs[i].new_ctx->def.chan->center_freq,
vifs[i].old_ctx->def.width,
vifs[i].new_ctx->def.width);
if (WARN_ON(!arvif->is_started))
continue;
if (WARN_ON(!arvif->is_up))
continue;
ret = ath10k_wmi_vdev_down(ar, arvif->vdev_id);
if (ret) {
ath10k_warn(ar, "failed to down vdev %d: %d\n",
arvif->vdev_id, ret);
continue;
}
}
/* All relevant vdevs are downed and associated channel resources
* should be available for the channel switch now.
*/
spin_lock_bh(&ar->data_lock);
ath10k_mac_update_rx_channel(ar, NULL, vifs, n_vifs);
spin_unlock_bh(&ar->data_lock);
for (i = 0; i < n_vifs; i++) {
arvif = ath10k_vif_to_arvif(vifs[i].vif);
if (WARN_ON(!arvif->is_started))
continue;
if (WARN_ON(!arvif->is_up))
continue;
ret = ath10k_mac_setup_bcn_tmpl(arvif);
if (ret)
ath10k_warn(ar, "failed to update bcn tmpl during csa: %d\n",
ret);
ret = ath10k_mac_setup_prb_tmpl(arvif);
if (ret)
ath10k_warn(ar, "failed to update prb tmpl during csa: %d\n",
ret);
ret = ath10k_vdev_restart(arvif, &vifs[i].new_ctx->def);
if (ret) {
ath10k_warn(ar, "failed to restart vdev %d: %d\n",
arvif->vdev_id, ret);
continue;
}
ret = ath10k_wmi_vdev_up(arvif->ar, arvif->vdev_id, arvif->aid,
arvif->bssid);
if (ret) {
ath10k_warn(ar, "failed to bring vdev up %d: %d\n",
arvif->vdev_id, ret);
continue;
}
}
ath10k_monitor_recalc(ar);
}
static int
ath10k_mac_op_add_chanctx(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *ctx)
{
struct ath10k *ar = hw->priv;
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac chanctx add freq %hu width %d ptr %p\n",
ctx->def.chan->center_freq, ctx->def.width, ctx);
mutex_lock(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
ath10k_mac_update_rx_channel(ar, ctx, NULL, 0);
spin_unlock_bh(&ar->data_lock);
ath10k_recalc_radar_detection(ar);
ath10k_monitor_recalc(ar);
mutex_unlock(&ar->conf_mutex);
return 0;
}
static void
ath10k_mac_op_remove_chanctx(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *ctx)
{
struct ath10k *ar = hw->priv;
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac chanctx remove freq %hu width %d ptr %p\n",
ctx->def.chan->center_freq, ctx->def.width, ctx);
mutex_lock(&ar->conf_mutex);
spin_lock_bh(&ar->data_lock);
ath10k_mac_update_rx_channel(ar, NULL, NULL, 0);
spin_unlock_bh(&ar->data_lock);
ath10k_recalc_radar_detection(ar);
ath10k_monitor_recalc(ar);
mutex_unlock(&ar->conf_mutex);
}
struct ath10k_mac_change_chanctx_arg {
struct ieee80211_chanctx_conf *ctx;
struct ieee80211_vif_chanctx_switch *vifs;
int n_vifs;
int next_vif;
};
static void
ath10k_mac_change_chanctx_cnt_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct ath10k_mac_change_chanctx_arg *arg = data;
if (rcu_access_pointer(vif->chanctx_conf) != arg->ctx)
return;
arg->n_vifs++;
}
static void
ath10k_mac_change_chanctx_fill_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct ath10k_mac_change_chanctx_arg *arg = data;
struct ieee80211_chanctx_conf *ctx;
ctx = rcu_access_pointer(vif->chanctx_conf);
if (ctx != arg->ctx)
return;
if (WARN_ON(arg->next_vif == arg->n_vifs))
return;
arg->vifs[arg->next_vif].vif = vif;
arg->vifs[arg->next_vif].old_ctx = ctx;
arg->vifs[arg->next_vif].new_ctx = ctx;
arg->next_vif++;
}
static void
ath10k_mac_op_change_chanctx(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *ctx,
u32 changed)
{
struct ath10k *ar = hw->priv;
struct ath10k_mac_change_chanctx_arg arg = { .ctx = ctx };
mutex_lock(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac chanctx change freq %hu width %d ptr %p changed %x\n",
ctx->def.chan->center_freq, ctx->def.width, ctx, changed);
/* This shouldn't really happen because channel switching should use
* switch_vif_chanctx().
*/
if (WARN_ON(changed & IEEE80211_CHANCTX_CHANGE_CHANNEL))
goto unlock;
if (changed & IEEE80211_CHANCTX_CHANGE_WIDTH) {
ieee80211_iterate_active_interfaces_atomic(
hw,
IEEE80211_IFACE_ITER_NORMAL,
ath10k_mac_change_chanctx_cnt_iter,
&arg);
if (arg.n_vifs == 0)
goto radar;
arg.vifs = kcalloc(arg.n_vifs, sizeof(arg.vifs[0]),
GFP_KERNEL);
if (!arg.vifs)
goto radar;
ieee80211_iterate_active_interfaces_atomic(
hw,
IEEE80211_IFACE_ITER_NORMAL,
ath10k_mac_change_chanctx_fill_iter,
&arg);
ath10k_mac_update_vif_chan(ar, arg.vifs, arg.n_vifs);
kfree(arg.vifs);
}
radar:
ath10k_recalc_radar_detection(ar);
/* FIXME: How to configure Rx chains properly? */
/* No other actions are actually necessary. Firmware maintains channel
* definitions per vdev internally and there's no host-side channel
* context abstraction to configure, e.g. channel width.
*/
unlock:
mutex_unlock(&ar->conf_mutex);
}
static int
ath10k_mac_op_assign_vif_chanctx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_chanctx_conf *ctx)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = (void *)vif->drv_priv;
int ret;
mutex_lock(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac chanctx assign ptr %p vdev_id %i\n",
ctx, arvif->vdev_id);
if (WARN_ON(arvif->is_started)) {
mutex_unlock(&ar->conf_mutex);
return -EBUSY;
}
ret = ath10k_vdev_start(arvif, &ctx->def);
if (ret) {
ath10k_warn(ar, "failed to start vdev %i addr %pM on freq %d: %d\n",
arvif->vdev_id, vif->addr,
ctx->def.chan->center_freq, ret);
goto err;
}
arvif->is_started = true;
ret = ath10k_mac_vif_setup_ps(arvif);
if (ret) {
ath10k_warn(ar, "failed to update vdev %i ps: %d\n",
arvif->vdev_id, ret);
goto err_stop;
}
if (vif->type == NL80211_IFTYPE_MONITOR) {
ret = ath10k_wmi_vdev_up(ar, arvif->vdev_id, 0, vif->addr);
if (ret) {
ath10k_warn(ar, "failed to up monitor vdev %i: %d\n",
arvif->vdev_id, ret);
goto err_stop;
}
arvif->is_up = true;
}
mutex_unlock(&ar->conf_mutex);
return 0;
err_stop:
ath10k_vdev_stop(arvif);
arvif->is_started = false;
ath10k_mac_vif_setup_ps(arvif);
err:
mutex_unlock(&ar->conf_mutex);
return ret;
}
static void
ath10k_mac_op_unassign_vif_chanctx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_chanctx_conf *ctx)
{
struct ath10k *ar = hw->priv;
struct ath10k_vif *arvif = (void *)vif->drv_priv;
int ret;
mutex_lock(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac chanctx unassign ptr %p vdev_id %i\n",
ctx, arvif->vdev_id);
WARN_ON(!arvif->is_started);
if (vif->type == NL80211_IFTYPE_MONITOR) {
WARN_ON(!arvif->is_up);
ret = ath10k_wmi_vdev_down(ar, arvif->vdev_id);
if (ret)
ath10k_warn(ar, "failed to down monitor vdev %i: %d\n",
arvif->vdev_id, ret);
arvif->is_up = false;
}
ret = ath10k_vdev_stop(arvif);
if (ret)
ath10k_warn(ar, "failed to stop vdev %i: %d\n",
arvif->vdev_id, ret);
arvif->is_started = false;
mutex_unlock(&ar->conf_mutex);
}
static int
ath10k_mac_op_switch_vif_chanctx(struct ieee80211_hw *hw,
struct ieee80211_vif_chanctx_switch *vifs,
int n_vifs,
enum ieee80211_chanctx_switch_mode mode)
{
struct ath10k *ar = hw->priv;
mutex_lock(&ar->conf_mutex);
ath10k_dbg(ar, ATH10K_DBG_MAC,
"mac chanctx switch n_vifs %d mode %d\n",
n_vifs, mode);
ath10k_mac_update_vif_chan(ar, vifs, n_vifs);
mutex_unlock(&ar->conf_mutex);
return 0;
}
static const struct ieee80211_ops ath10k_ops = {
.tx = ath10k_tx,
.start = ath10k_start,
.stop = ath10k_stop,
.config = ath10k_config,
.add_interface = ath10k_add_interface,
.remove_interface = ath10k_remove_interface,
.configure_filter = ath10k_configure_filter,
.bss_info_changed = ath10k_bss_info_changed,
.hw_scan = ath10k_hw_scan,
.cancel_hw_scan = ath10k_cancel_hw_scan,
.set_key = ath10k_set_key,
.set_default_unicast_key = ath10k_set_default_unicast_key,
.sta_state = ath10k_sta_state,
.conf_tx = ath10k_conf_tx,
.remain_on_channel = ath10k_remain_on_channel,
.cancel_remain_on_channel = ath10k_cancel_remain_on_channel,
.set_rts_threshold = ath10k_set_rts_threshold,
.set_frag_threshold = ath10k_mac_op_set_frag_threshold,
.flush = ath10k_flush,
.tx_last_beacon = ath10k_tx_last_beacon,
.set_antenna = ath10k_set_antenna,
.get_antenna = ath10k_get_antenna,
.reconfig_complete = ath10k_reconfig_complete,
.get_survey = ath10k_get_survey,
.set_bitrate_mask = ath10k_mac_op_set_bitrate_mask,
.sta_rc_update = ath10k_sta_rc_update,
.get_tsf = ath10k_get_tsf,
.ampdu_action = ath10k_ampdu_action,
.get_et_sset_count = ath10k_debug_get_et_sset_count,
.get_et_stats = ath10k_debug_get_et_stats,
.get_et_strings = ath10k_debug_get_et_strings,
.add_chanctx = ath10k_mac_op_add_chanctx,
.remove_chanctx = ath10k_mac_op_remove_chanctx,
.change_chanctx = ath10k_mac_op_change_chanctx,
.assign_vif_chanctx = ath10k_mac_op_assign_vif_chanctx,
.unassign_vif_chanctx = ath10k_mac_op_unassign_vif_chanctx,
.switch_vif_chanctx = ath10k_mac_op_switch_vif_chanctx,
CFG80211_TESTMODE_CMD(ath10k_tm_cmd)
#ifdef CONFIG_PM
.suspend = ath10k_wow_op_suspend,
.resume = ath10k_wow_op_resume,
#endif
#ifdef CONFIG_MAC80211_DEBUGFS
.sta_add_debugfs = ath10k_sta_add_debugfs,
#endif
};
#define CHAN2G(_channel, _freq, _flags) { \
.band = IEEE80211_BAND_2GHZ, \
.hw_value = (_channel), \
.center_freq = (_freq), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
#define CHAN5G(_channel, _freq, _flags) { \
.band = IEEE80211_BAND_5GHZ, \
.hw_value = (_channel), \
.center_freq = (_freq), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static const struct ieee80211_channel ath10k_2ghz_channels[] = {
CHAN2G(1, 2412, 0),
CHAN2G(2, 2417, 0),
CHAN2G(3, 2422, 0),
CHAN2G(4, 2427, 0),
CHAN2G(5, 2432, 0),
CHAN2G(6, 2437, 0),
CHAN2G(7, 2442, 0),
CHAN2G(8, 2447, 0),
CHAN2G(9, 2452, 0),
CHAN2G(10, 2457, 0),
CHAN2G(11, 2462, 0),
CHAN2G(12, 2467, 0),
CHAN2G(13, 2472, 0),
CHAN2G(14, 2484, 0),
};
static const struct ieee80211_channel ath10k_5ghz_channels[] = {
CHAN5G(36, 5180, 0),
CHAN5G(40, 5200, 0),
CHAN5G(44, 5220, 0),
CHAN5G(48, 5240, 0),
CHAN5G(52, 5260, 0),
CHAN5G(56, 5280, 0),
CHAN5G(60, 5300, 0),
CHAN5G(64, 5320, 0),
CHAN5G(100, 5500, 0),
CHAN5G(104, 5520, 0),
CHAN5G(108, 5540, 0),
CHAN5G(112, 5560, 0),
CHAN5G(116, 5580, 0),
CHAN5G(120, 5600, 0),
CHAN5G(124, 5620, 0),
CHAN5G(128, 5640, 0),
CHAN5G(132, 5660, 0),
CHAN5G(136, 5680, 0),
CHAN5G(140, 5700, 0),
CHAN5G(144, 5720, 0),
CHAN5G(149, 5745, 0),
CHAN5G(153, 5765, 0),
CHAN5G(157, 5785, 0),
CHAN5G(161, 5805, 0),
CHAN5G(165, 5825, 0),
};
struct ath10k *ath10k_mac_create(size_t priv_size)
{
struct ieee80211_hw *hw;
struct ath10k *ar;
hw = ieee80211_alloc_hw(sizeof(struct ath10k) + priv_size, &ath10k_ops);
if (!hw)
return NULL;
ar = hw->priv;
ar->hw = hw;
return ar;
}
void ath10k_mac_destroy(struct ath10k *ar)
{
ieee80211_free_hw(ar->hw);
}
static const struct ieee80211_iface_limit ath10k_if_limits[] = {
{
.max = 8,
.types = BIT(NL80211_IFTYPE_STATION)
| BIT(NL80211_IFTYPE_P2P_CLIENT)
},
{
.max = 3,
.types = BIT(NL80211_IFTYPE_P2P_GO)
},
{
.max = 1,
.types = BIT(NL80211_IFTYPE_P2P_DEVICE)
},
{
.max = 7,
.types = BIT(NL80211_IFTYPE_AP)
#ifdef CONFIG_MAC80211_MESH
| BIT(NL80211_IFTYPE_MESH_POINT)
#endif
},
};
static const struct ieee80211_iface_limit ath10k_10x_if_limits[] = {
{
.max = 8,
.types = BIT(NL80211_IFTYPE_AP)
#ifdef CONFIG_MAC80211_MESH
| BIT(NL80211_IFTYPE_MESH_POINT)
#endif
},
};
static const struct ieee80211_iface_combination ath10k_if_comb[] = {
{
.limits = ath10k_if_limits,
.n_limits = ARRAY_SIZE(ath10k_if_limits),
.max_interfaces = 8,
.num_different_channels = 1,
.beacon_int_infra_match = true,
},
};
static const struct ieee80211_iface_combination ath10k_10x_if_comb[] = {
{
.limits = ath10k_10x_if_limits,
.n_limits = ARRAY_SIZE(ath10k_10x_if_limits),
.max_interfaces = 8,
.num_different_channels = 1,
.beacon_int_infra_match = true,
#ifdef CONFIG_ATH10K_DFS_CERTIFIED
.radar_detect_widths = BIT(NL80211_CHAN_WIDTH_20_NOHT) |
BIT(NL80211_CHAN_WIDTH_20) |
BIT(NL80211_CHAN_WIDTH_40) |
BIT(NL80211_CHAN_WIDTH_80),
#endif
},
};
static const struct ieee80211_iface_limit ath10k_tlv_if_limit[] = {
{
.max = 2,
.types = BIT(NL80211_IFTYPE_STATION),
},
{
.max = 2,
.types = BIT(NL80211_IFTYPE_AP) |
#ifdef CONFIG_MAC80211_MESH
BIT(NL80211_IFTYPE_MESH_POINT) |
#endif
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO),
},
{
.max = 1,
.types = BIT(NL80211_IFTYPE_P2P_DEVICE),
},
};
static const struct ieee80211_iface_limit ath10k_tlv_qcs_if_limit[] = {
{
.max = 2,
.types = BIT(NL80211_IFTYPE_STATION),
},
{
.max = 2,
.types = BIT(NL80211_IFTYPE_P2P_CLIENT),
},
{
.max = 1,
.types = BIT(NL80211_IFTYPE_AP) |
#ifdef CONFIG_MAC80211_MESH
BIT(NL80211_IFTYPE_MESH_POINT) |
#endif
BIT(NL80211_IFTYPE_P2P_GO),
},
{
.max = 1,
.types = BIT(NL80211_IFTYPE_P2P_DEVICE),
},
};
static const struct ieee80211_iface_limit ath10k_tlv_if_limit_ibss[] = {
{
.max = 1,
.types = BIT(NL80211_IFTYPE_STATION),
},
{
.max = 1,
.types = BIT(NL80211_IFTYPE_ADHOC),
},
};
/* FIXME: This is not thouroughly tested. These combinations may over- or
* underestimate hw/fw capabilities.
*/
static struct ieee80211_iface_combination ath10k_tlv_if_comb[] = {
{
.limits = ath10k_tlv_if_limit,
.num_different_channels = 1,
.max_interfaces = 4,
.n_limits = ARRAY_SIZE(ath10k_tlv_if_limit),
},
{
.limits = ath10k_tlv_if_limit_ibss,
.num_different_channels = 1,
.max_interfaces = 2,
.n_limits = ARRAY_SIZE(ath10k_tlv_if_limit_ibss),
},
};
static struct ieee80211_iface_combination ath10k_tlv_qcs_if_comb[] = {
{
.limits = ath10k_tlv_if_limit,
.num_different_channels = 1,
.max_interfaces = 4,
.n_limits = ARRAY_SIZE(ath10k_tlv_if_limit),
},
{
.limits = ath10k_tlv_qcs_if_limit,
.num_different_channels = 2,
.max_interfaces = 4,
.n_limits = ARRAY_SIZE(ath10k_tlv_qcs_if_limit),
},
{
.limits = ath10k_tlv_if_limit_ibss,
.num_different_channels = 1,
.max_interfaces = 2,
.n_limits = ARRAY_SIZE(ath10k_tlv_if_limit_ibss),
},
};
static const struct ieee80211_iface_limit ath10k_10_4_if_limits[] = {
{
.max = 1,
.types = BIT(NL80211_IFTYPE_STATION),
},
{
.max = 16,
.types = BIT(NL80211_IFTYPE_AP)
#ifdef CONFIG_MAC80211_MESH
| BIT(NL80211_IFTYPE_MESH_POINT)
#endif
},
};
static const struct ieee80211_iface_combination ath10k_10_4_if_comb[] = {
{
.limits = ath10k_10_4_if_limits,
.n_limits = ARRAY_SIZE(ath10k_10_4_if_limits),
.max_interfaces = 16,
.num_different_channels = 1,
.beacon_int_infra_match = true,
#ifdef CONFIG_ATH10K_DFS_CERTIFIED
.radar_detect_widths = BIT(NL80211_CHAN_WIDTH_20_NOHT) |
BIT(NL80211_CHAN_WIDTH_20) |
BIT(NL80211_CHAN_WIDTH_40) |
BIT(NL80211_CHAN_WIDTH_80),
#endif
},
};
static void ath10k_get_arvif_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct ath10k_vif_iter *arvif_iter = data;
struct ath10k_vif *arvif = ath10k_vif_to_arvif(vif);
if (arvif->vdev_id == arvif_iter->vdev_id)
arvif_iter->arvif = arvif;
}
struct ath10k_vif *ath10k_get_arvif(struct ath10k *ar, u32 vdev_id)
{
struct ath10k_vif_iter arvif_iter;
u32 flags;
memset(&arvif_iter, 0, sizeof(struct ath10k_vif_iter));
arvif_iter.vdev_id = vdev_id;
flags = IEEE80211_IFACE_ITER_RESUME_ALL;
ieee80211_iterate_active_interfaces_atomic(ar->hw,
flags,
ath10k_get_arvif_iter,
&arvif_iter);
if (!arvif_iter.arvif) {
ath10k_warn(ar, "No VIF found for vdev %d\n", vdev_id);
return NULL;
}
return arvif_iter.arvif;
}
int ath10k_mac_register(struct ath10k *ar)
{
static const u32 cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
WLAN_CIPHER_SUITE_AES_CMAC,
};
struct ieee80211_supported_band *band;
void *channels;
int ret;
SET_IEEE80211_PERM_ADDR(ar->hw, ar->mac_addr);
SET_IEEE80211_DEV(ar->hw, ar->dev);
BUILD_BUG_ON((ARRAY_SIZE(ath10k_2ghz_channels) +
ARRAY_SIZE(ath10k_5ghz_channels)) !=
ATH10K_NUM_CHANS);
if (ar->phy_capability & WHAL_WLAN_11G_CAPABILITY) {
channels = kmemdup(ath10k_2ghz_channels,
sizeof(ath10k_2ghz_channels),
GFP_KERNEL);
if (!channels) {
ret = -ENOMEM;
goto err_free;
}
band = &ar->mac.sbands[IEEE80211_BAND_2GHZ];
band->n_channels = ARRAY_SIZE(ath10k_2ghz_channels);
band->channels = channels;
band->n_bitrates = ath10k_g_rates_size;
band->bitrates = ath10k_g_rates;
ar->hw->wiphy->bands[IEEE80211_BAND_2GHZ] = band;
}
if (ar->phy_capability & WHAL_WLAN_11A_CAPABILITY) {
channels = kmemdup(ath10k_5ghz_channels,
sizeof(ath10k_5ghz_channels),
GFP_KERNEL);
if (!channels) {
ret = -ENOMEM;
goto err_free;
}
band = &ar->mac.sbands[IEEE80211_BAND_5GHZ];
band->n_channels = ARRAY_SIZE(ath10k_5ghz_channels);
band->channels = channels;
band->n_bitrates = ath10k_a_rates_size;
band->bitrates = ath10k_a_rates;
ar->hw->wiphy->bands[IEEE80211_BAND_5GHZ] = band;
}
ath10k_mac_setup_ht_vht_cap(ar);
ar->hw->wiphy->interface_modes =
BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_MESH_POINT);
ar->hw->wiphy->available_antennas_rx = ar->cfg_rx_chainmask;
ar->hw->wiphy->available_antennas_tx = ar->cfg_tx_chainmask;
if (!test_bit(ATH10K_FW_FEATURE_NO_P2P, ar->fw_features))
ar->hw->wiphy->interface_modes |=
BIT(NL80211_IFTYPE_P2P_DEVICE) |
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO);
ieee80211_hw_set(ar->hw, SIGNAL_DBM);
ieee80211_hw_set(ar->hw, SUPPORTS_PS);
ieee80211_hw_set(ar->hw, SUPPORTS_DYNAMIC_PS);
ieee80211_hw_set(ar->hw, MFP_CAPABLE);
ieee80211_hw_set(ar->hw, REPORTS_TX_ACK_STATUS);
ieee80211_hw_set(ar->hw, HAS_RATE_CONTROL);
ieee80211_hw_set(ar->hw, AP_LINK_PS);
ieee80211_hw_set(ar->hw, SPECTRUM_MGMT);
ieee80211_hw_set(ar->hw, SUPPORT_FAST_XMIT);
ieee80211_hw_set(ar->hw, CONNECTION_MONITOR);
ieee80211_hw_set(ar->hw, SUPPORTS_PER_STA_GTK);
ieee80211_hw_set(ar->hw, WANT_MONITOR_VIF);
ieee80211_hw_set(ar->hw, CHANCTX_STA_CSA);
ieee80211_hw_set(ar->hw, QUEUE_CONTROL);
if (!test_bit(ATH10K_FLAG_RAW_MODE, &ar->dev_flags))
ieee80211_hw_set(ar->hw, SW_CRYPTO_CONTROL);
ar->hw->wiphy->features |= NL80211_FEATURE_STATIC_SMPS;
ar->hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN;
if (ar->ht_cap_info & WMI_HT_CAP_DYNAMIC_SMPS)
ar->hw->wiphy->features |= NL80211_FEATURE_DYNAMIC_SMPS;
if (ar->ht_cap_info & WMI_HT_CAP_ENABLED) {
ieee80211_hw_set(ar->hw, AMPDU_AGGREGATION);
ieee80211_hw_set(ar->hw, TX_AMPDU_SETUP_IN_HW);
}
ar->hw->wiphy->max_scan_ssids = WLAN_SCAN_PARAMS_MAX_SSID;
ar->hw->wiphy->max_scan_ie_len = WLAN_SCAN_PARAMS_MAX_IE_LEN;
ar->hw->vif_data_size = sizeof(struct ath10k_vif);
ar->hw->sta_data_size = sizeof(struct ath10k_sta);
ar->hw->max_listen_interval = ATH10K_MAX_HW_LISTEN_INTERVAL;
if (test_bit(WMI_SERVICE_BEACON_OFFLOAD, ar->wmi.svc_map)) {
ar->hw->wiphy->flags |= WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD;
/* Firmware delivers WPS/P2P Probe Requests frames to driver so
* that userspace (e.g. wpa_supplicant/hostapd) can generate
* correct Probe Responses. This is more of a hack advert..
*/
ar->hw->wiphy->probe_resp_offload |=
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS |
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2 |
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P;
}
if (test_bit(WMI_SERVICE_TDLS, ar->wmi.svc_map))
ar->hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS;
ar->hw->wiphy->flags |= WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
ar->hw->wiphy->flags |= WIPHY_FLAG_HAS_CHANNEL_SWITCH;
ar->hw->wiphy->max_remain_on_channel_duration = 5000;
ar->hw->wiphy->flags |= WIPHY_FLAG_AP_UAPSD;
ar->hw->wiphy->features |= NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE;
ar->hw->wiphy->max_ap_assoc_sta = ar->max_num_stations;
ret = ath10k_wow_init(ar);
if (ret) {
ath10k_warn(ar, "failed to init wow: %d\n", ret);
goto err_free;
}
wiphy_ext_feature_set(ar->hw->wiphy, NL80211_EXT_FEATURE_VHT_IBSS);
/*
* on LL hardware queues are managed entirely by the FW
* so we only advertise to mac we can do the queues thing
*/
ar->hw->queues = IEEE80211_MAX_QUEUES;
/* vdev_ids are used as hw queue numbers. Make sure offchan tx queue is
* something that vdev_ids can't reach so that we don't stop the queue
* accidentally.
*/
ar->hw->offchannel_tx_hw_queue = IEEE80211_MAX_QUEUES - 1;
switch (ar->wmi.op_version) {
case ATH10K_FW_WMI_OP_VERSION_MAIN:
ar->hw->wiphy->iface_combinations = ath10k_if_comb;
ar->hw->wiphy->n_iface_combinations =
ARRAY_SIZE(ath10k_if_comb);
ar->hw->wiphy->interface_modes |= BIT(NL80211_IFTYPE_ADHOC);
break;
case ATH10K_FW_WMI_OP_VERSION_TLV:
if (test_bit(WMI_SERVICE_ADAPTIVE_OCS, ar->wmi.svc_map)) {
ar->hw->wiphy->iface_combinations =
ath10k_tlv_qcs_if_comb;
ar->hw->wiphy->n_iface_combinations =
ARRAY_SIZE(ath10k_tlv_qcs_if_comb);
} else {
ar->hw->wiphy->iface_combinations = ath10k_tlv_if_comb;
ar->hw->wiphy->n_iface_combinations =
ARRAY_SIZE(ath10k_tlv_if_comb);
}
ar->hw->wiphy->interface_modes |= BIT(NL80211_IFTYPE_ADHOC);
break;
case ATH10K_FW_WMI_OP_VERSION_10_1:
case ATH10K_FW_WMI_OP_VERSION_10_2:
case ATH10K_FW_WMI_OP_VERSION_10_2_4:
ar->hw->wiphy->iface_combinations = ath10k_10x_if_comb;
ar->hw->wiphy->n_iface_combinations =
ARRAY_SIZE(ath10k_10x_if_comb);
break;
case ATH10K_FW_WMI_OP_VERSION_10_4:
ar->hw->wiphy->iface_combinations = ath10k_10_4_if_comb;
ar->hw->wiphy->n_iface_combinations =
ARRAY_SIZE(ath10k_10_4_if_comb);
break;
case ATH10K_FW_WMI_OP_VERSION_UNSET:
case ATH10K_FW_WMI_OP_VERSION_MAX:
WARN_ON(1);
ret = -EINVAL;
goto err_free;
}
if (!test_bit(ATH10K_FLAG_RAW_MODE, &ar->dev_flags))
ar->hw->netdev_features = NETIF_F_HW_CSUM;
if (config_enabled(CONFIG_ATH10K_DFS_CERTIFIED)) {
/* Init ath dfs pattern detector */
ar->ath_common.debug_mask = ATH_DBG_DFS;
ar->dfs_detector = dfs_pattern_detector_init(&ar->ath_common,
NL80211_DFS_UNSET);
if (!ar->dfs_detector)
ath10k_warn(ar, "failed to initialise DFS pattern detector\n");
}
ret = ath_regd_init(&ar->ath_common.regulatory, ar->hw->wiphy,
ath10k_reg_notifier);
if (ret) {
ath10k_err(ar, "failed to initialise regulatory: %i\n", ret);
goto err_dfs_detector_exit;
}
ar->hw->wiphy->cipher_suites = cipher_suites;
ar->hw->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites);
ret = ieee80211_register_hw(ar->hw);
if (ret) {
ath10k_err(ar, "failed to register ieee80211: %d\n", ret);
goto err_dfs_detector_exit;
}
if (!ath_is_world_regd(&ar->ath_common.regulatory)) {
ret = regulatory_hint(ar->hw->wiphy,
ar->ath_common.regulatory.alpha2);
if (ret)
goto err_unregister;
}
return 0;
err_unregister:
ieee80211_unregister_hw(ar->hw);
err_dfs_detector_exit:
if (config_enabled(CONFIG_ATH10K_DFS_CERTIFIED) && ar->dfs_detector)
ar->dfs_detector->exit(ar->dfs_detector);
err_free:
kfree(ar->mac.sbands[IEEE80211_BAND_2GHZ].channels);
kfree(ar->mac.sbands[IEEE80211_BAND_5GHZ].channels);
SET_IEEE80211_DEV(ar->hw, NULL);
return ret;
}
void ath10k_mac_unregister(struct ath10k *ar)
{
ieee80211_unregister_hw(ar->hw);
if (config_enabled(CONFIG_ATH10K_DFS_CERTIFIED) && ar->dfs_detector)
ar->dfs_detector->exit(ar->dfs_detector);
kfree(ar->mac.sbands[IEEE80211_BAND_2GHZ].channels);
kfree(ar->mac.sbands[IEEE80211_BAND_5GHZ].channels);
SET_IEEE80211_DEV(ar->hw, NULL);
}
| AiJiaZone/linux-4.0 | virt/drivers/net/wireless/ath/ath10k/mac.c | C | gpl-2.0 | 189,014 |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* sun4i-ss-core.c - hardware cryptographic accelerator for Allwinner A20 SoC
*
* Copyright (C) 2013-2015 Corentin LABBE <[email protected]>
*
* Core file which registers crypto algorithms supported by the SS.
*
* You could find a link for the datasheet in Documentation/arm/sunxi.rst
*/
#include <linux/clk.h>
#include <linux/crypto.h>
#include <linux/debugfs.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <crypto/scatterwalk.h>
#include <linux/scatterlist.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/reset.h>
#include "sun4i-ss.h"
static const struct ss_variant ss_a10_variant = {
.sha1_in_be = false,
};
static const struct ss_variant ss_a33_variant = {
.sha1_in_be = true,
};
static struct sun4i_ss_alg_template ss_algs[] = {
{ .type = CRYPTO_ALG_TYPE_AHASH,
.mode = SS_OP_MD5,
.alg.hash = {
.init = sun4i_hash_init,
.update = sun4i_hash_update,
.final = sun4i_hash_final,
.finup = sun4i_hash_finup,
.digest = sun4i_hash_digest,
.export = sun4i_hash_export_md5,
.import = sun4i_hash_import_md5,
.halg = {
.digestsize = MD5_DIGEST_SIZE,
.statesize = sizeof(struct md5_state),
.base = {
.cra_name = "md5",
.cra_driver_name = "md5-sun4i-ss",
.cra_priority = 300,
.cra_alignmask = 3,
.cra_blocksize = MD5_HMAC_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct sun4i_req_ctx),
.cra_module = THIS_MODULE,
.cra_init = sun4i_hash_crainit,
.cra_exit = sun4i_hash_craexit,
}
}
}
},
{ .type = CRYPTO_ALG_TYPE_AHASH,
.mode = SS_OP_SHA1,
.alg.hash = {
.init = sun4i_hash_init,
.update = sun4i_hash_update,
.final = sun4i_hash_final,
.finup = sun4i_hash_finup,
.digest = sun4i_hash_digest,
.export = sun4i_hash_export_sha1,
.import = sun4i_hash_import_sha1,
.halg = {
.digestsize = SHA1_DIGEST_SIZE,
.statesize = sizeof(struct sha1_state),
.base = {
.cra_name = "sha1",
.cra_driver_name = "sha1-sun4i-ss",
.cra_priority = 300,
.cra_alignmask = 3,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct sun4i_req_ctx),
.cra_module = THIS_MODULE,
.cra_init = sun4i_hash_crainit,
.cra_exit = sun4i_hash_craexit,
}
}
}
},
{ .type = CRYPTO_ALG_TYPE_SKCIPHER,
.alg.crypto = {
.setkey = sun4i_ss_aes_setkey,
.encrypt = sun4i_ss_cbc_aes_encrypt,
.decrypt = sun4i_ss_cbc_aes_decrypt,
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.base = {
.cra_name = "cbc(aes)",
.cra_driver_name = "cbc-aes-sun4i-ss",
.cra_priority = 300,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_NEED_FALLBACK,
.cra_ctxsize = sizeof(struct sun4i_tfm_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_init = sun4i_ss_cipher_init,
.cra_exit = sun4i_ss_cipher_exit,
}
}
},
{ .type = CRYPTO_ALG_TYPE_SKCIPHER,
.alg.crypto = {
.setkey = sun4i_ss_aes_setkey,
.encrypt = sun4i_ss_ecb_aes_encrypt,
.decrypt = sun4i_ss_ecb_aes_decrypt,
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.base = {
.cra_name = "ecb(aes)",
.cra_driver_name = "ecb-aes-sun4i-ss",
.cra_priority = 300,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_NEED_FALLBACK,
.cra_ctxsize = sizeof(struct sun4i_tfm_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_init = sun4i_ss_cipher_init,
.cra_exit = sun4i_ss_cipher_exit,
}
}
},
{ .type = CRYPTO_ALG_TYPE_SKCIPHER,
.alg.crypto = {
.setkey = sun4i_ss_des_setkey,
.encrypt = sun4i_ss_cbc_des_encrypt,
.decrypt = sun4i_ss_cbc_des_decrypt,
.min_keysize = DES_KEY_SIZE,
.max_keysize = DES_KEY_SIZE,
.ivsize = DES_BLOCK_SIZE,
.base = {
.cra_name = "cbc(des)",
.cra_driver_name = "cbc-des-sun4i-ss",
.cra_priority = 300,
.cra_blocksize = DES_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_NEED_FALLBACK,
.cra_ctxsize = sizeof(struct sun4i_req_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_init = sun4i_ss_cipher_init,
.cra_exit = sun4i_ss_cipher_exit,
}
}
},
{ .type = CRYPTO_ALG_TYPE_SKCIPHER,
.alg.crypto = {
.setkey = sun4i_ss_des_setkey,
.encrypt = sun4i_ss_ecb_des_encrypt,
.decrypt = sun4i_ss_ecb_des_decrypt,
.min_keysize = DES_KEY_SIZE,
.max_keysize = DES_KEY_SIZE,
.base = {
.cra_name = "ecb(des)",
.cra_driver_name = "ecb-des-sun4i-ss",
.cra_priority = 300,
.cra_blocksize = DES_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_NEED_FALLBACK,
.cra_ctxsize = sizeof(struct sun4i_req_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_init = sun4i_ss_cipher_init,
.cra_exit = sun4i_ss_cipher_exit,
}
}
},
{ .type = CRYPTO_ALG_TYPE_SKCIPHER,
.alg.crypto = {
.setkey = sun4i_ss_des3_setkey,
.encrypt = sun4i_ss_cbc_des3_encrypt,
.decrypt = sun4i_ss_cbc_des3_decrypt,
.min_keysize = DES3_EDE_KEY_SIZE,
.max_keysize = DES3_EDE_KEY_SIZE,
.ivsize = DES3_EDE_BLOCK_SIZE,
.base = {
.cra_name = "cbc(des3_ede)",
.cra_driver_name = "cbc-des3-sun4i-ss",
.cra_priority = 300,
.cra_blocksize = DES3_EDE_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_NEED_FALLBACK,
.cra_ctxsize = sizeof(struct sun4i_req_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_init = sun4i_ss_cipher_init,
.cra_exit = sun4i_ss_cipher_exit,
}
}
},
{ .type = CRYPTO_ALG_TYPE_SKCIPHER,
.alg.crypto = {
.setkey = sun4i_ss_des3_setkey,
.encrypt = sun4i_ss_ecb_des3_encrypt,
.decrypt = sun4i_ss_ecb_des3_decrypt,
.min_keysize = DES3_EDE_KEY_SIZE,
.max_keysize = DES3_EDE_KEY_SIZE,
.base = {
.cra_name = "ecb(des3_ede)",
.cra_driver_name = "ecb-des3-sun4i-ss",
.cra_priority = 300,
.cra_blocksize = DES3_EDE_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_NEED_FALLBACK,
.cra_ctxsize = sizeof(struct sun4i_req_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_init = sun4i_ss_cipher_init,
.cra_exit = sun4i_ss_cipher_exit,
}
}
},
#ifdef CONFIG_CRYPTO_DEV_SUN4I_SS_PRNG
{
.type = CRYPTO_ALG_TYPE_RNG,
.alg.rng = {
.base = {
.cra_name = "stdrng",
.cra_driver_name = "sun4i_ss_rng",
.cra_priority = 300,
.cra_ctxsize = 0,
.cra_module = THIS_MODULE,
},
.generate = sun4i_ss_prng_generate,
.seed = sun4i_ss_prng_seed,
.seedsize = SS_SEED_LEN / BITS_PER_BYTE,
}
},
#endif
};
static int sun4i_ss_dbgfs_read(struct seq_file *seq, void *v)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(ss_algs); i++) {
if (!ss_algs[i].ss)
continue;
switch (ss_algs[i].type) {
case CRYPTO_ALG_TYPE_SKCIPHER:
seq_printf(seq, "%s %s reqs=%lu opti=%lu fallback=%lu tsize=%lu\n",
ss_algs[i].alg.crypto.base.cra_driver_name,
ss_algs[i].alg.crypto.base.cra_name,
ss_algs[i].stat_req, ss_algs[i].stat_opti, ss_algs[i].stat_fb,
ss_algs[i].stat_bytes);
break;
case CRYPTO_ALG_TYPE_RNG:
seq_printf(seq, "%s %s reqs=%lu tsize=%lu\n",
ss_algs[i].alg.rng.base.cra_driver_name,
ss_algs[i].alg.rng.base.cra_name,
ss_algs[i].stat_req, ss_algs[i].stat_bytes);
break;
case CRYPTO_ALG_TYPE_AHASH:
seq_printf(seq, "%s %s reqs=%lu\n",
ss_algs[i].alg.hash.halg.base.cra_driver_name,
ss_algs[i].alg.hash.halg.base.cra_name,
ss_algs[i].stat_req);
break;
}
}
return 0;
}
static int sun4i_ss_dbgfs_open(struct inode *inode, struct file *file)
{
return single_open(file, sun4i_ss_dbgfs_read, inode->i_private);
}
static const struct file_operations sun4i_ss_debugfs_fops = {
.owner = THIS_MODULE,
.open = sun4i_ss_dbgfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/*
* Power management strategy: The device is suspended unless a TFM exists for
* one of the algorithms proposed by this driver.
*/
static int sun4i_ss_pm_suspend(struct device *dev)
{
struct sun4i_ss_ctx *ss = dev_get_drvdata(dev);
reset_control_assert(ss->reset);
clk_disable_unprepare(ss->ssclk);
clk_disable_unprepare(ss->busclk);
return 0;
}
static int sun4i_ss_pm_resume(struct device *dev)
{
struct sun4i_ss_ctx *ss = dev_get_drvdata(dev);
int err;
err = clk_prepare_enable(ss->busclk);
if (err) {
dev_err(ss->dev, "Cannot prepare_enable busclk\n");
goto err_enable;
}
err = clk_prepare_enable(ss->ssclk);
if (err) {
dev_err(ss->dev, "Cannot prepare_enable ssclk\n");
goto err_enable;
}
err = reset_control_deassert(ss->reset);
if (err) {
dev_err(ss->dev, "Cannot deassert reset control\n");
goto err_enable;
}
return err;
err_enable:
sun4i_ss_pm_suspend(dev);
return err;
}
static const struct dev_pm_ops sun4i_ss_pm_ops = {
SET_RUNTIME_PM_OPS(sun4i_ss_pm_suspend, sun4i_ss_pm_resume, NULL)
};
/*
* When power management is enabled, this function enables the PM and set the
* device as suspended
* When power management is disabled, this function just enables the device
*/
static int sun4i_ss_pm_init(struct sun4i_ss_ctx *ss)
{
int err;
pm_runtime_use_autosuspend(ss->dev);
pm_runtime_set_autosuspend_delay(ss->dev, 2000);
err = pm_runtime_set_suspended(ss->dev);
if (err)
return err;
pm_runtime_enable(ss->dev);
return err;
}
static void sun4i_ss_pm_exit(struct sun4i_ss_ctx *ss)
{
pm_runtime_disable(ss->dev);
}
static int sun4i_ss_probe(struct platform_device *pdev)
{
u32 v;
int err, i;
unsigned long cr;
const unsigned long cr_ahb = 24 * 1000 * 1000;
const unsigned long cr_mod = 150 * 1000 * 1000;
struct sun4i_ss_ctx *ss;
if (!pdev->dev.of_node)
return -ENODEV;
ss = devm_kzalloc(&pdev->dev, sizeof(*ss), GFP_KERNEL);
if (!ss)
return -ENOMEM;
ss->base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(ss->base)) {
dev_err(&pdev->dev, "Cannot request MMIO\n");
return PTR_ERR(ss->base);
}
ss->variant = of_device_get_match_data(&pdev->dev);
if (!ss->variant) {
dev_err(&pdev->dev, "Missing Security System variant\n");
return -EINVAL;
}
ss->ssclk = devm_clk_get(&pdev->dev, "mod");
if (IS_ERR(ss->ssclk)) {
err = PTR_ERR(ss->ssclk);
dev_err(&pdev->dev, "Cannot get SS clock err=%d\n", err);
return err;
}
dev_dbg(&pdev->dev, "clock ss acquired\n");
ss->busclk = devm_clk_get(&pdev->dev, "ahb");
if (IS_ERR(ss->busclk)) {
err = PTR_ERR(ss->busclk);
dev_err(&pdev->dev, "Cannot get AHB SS clock err=%d\n", err);
return err;
}
dev_dbg(&pdev->dev, "clock ahb_ss acquired\n");
ss->reset = devm_reset_control_get_optional(&pdev->dev, "ahb");
if (IS_ERR(ss->reset))
return PTR_ERR(ss->reset);
if (!ss->reset)
dev_info(&pdev->dev, "no reset control found\n");
/*
* Check that clock have the correct rates given in the datasheet
* Try to set the clock to the maximum allowed
*/
err = clk_set_rate(ss->ssclk, cr_mod);
if (err) {
dev_err(&pdev->dev, "Cannot set clock rate to ssclk\n");
return err;
}
/*
* The only impact on clocks below requirement are bad performance,
* so do not print "errors"
* warn on Overclocked clocks
*/
cr = clk_get_rate(ss->busclk);
if (cr >= cr_ahb)
dev_dbg(&pdev->dev, "Clock bus %lu (%lu MHz) (must be >= %lu)\n",
cr, cr / 1000000, cr_ahb);
else
dev_warn(&pdev->dev, "Clock bus %lu (%lu MHz) (must be >= %lu)\n",
cr, cr / 1000000, cr_ahb);
cr = clk_get_rate(ss->ssclk);
if (cr <= cr_mod)
if (cr < cr_mod)
dev_warn(&pdev->dev, "Clock ss %lu (%lu MHz) (must be <= %lu)\n",
cr, cr / 1000000, cr_mod);
else
dev_dbg(&pdev->dev, "Clock ss %lu (%lu MHz) (must be <= %lu)\n",
cr, cr / 1000000, cr_mod);
else
dev_warn(&pdev->dev, "Clock ss is at %lu (%lu MHz) (must be <= %lu)\n",
cr, cr / 1000000, cr_mod);
ss->dev = &pdev->dev;
platform_set_drvdata(pdev, ss);
spin_lock_init(&ss->slock);
err = sun4i_ss_pm_init(ss);
if (err)
return err;
/*
* Datasheet named it "Die Bonding ID"
* I expect to be a sort of Security System Revision number.
* Since the A80 seems to have an other version of SS
* this info could be useful
*/
err = pm_runtime_resume_and_get(ss->dev);
if (err < 0)
goto error_pm;
writel(SS_ENABLED, ss->base + SS_CTL);
v = readl(ss->base + SS_CTL);
v >>= 16;
v &= 0x07;
dev_info(&pdev->dev, "Die ID %d\n", v);
writel(0, ss->base + SS_CTL);
pm_runtime_put_sync(ss->dev);
for (i = 0; i < ARRAY_SIZE(ss_algs); i++) {
ss_algs[i].ss = ss;
switch (ss_algs[i].type) {
case CRYPTO_ALG_TYPE_SKCIPHER:
err = crypto_register_skcipher(&ss_algs[i].alg.crypto);
if (err) {
dev_err(ss->dev, "Fail to register %s\n",
ss_algs[i].alg.crypto.base.cra_name);
goto error_alg;
}
break;
case CRYPTO_ALG_TYPE_AHASH:
err = crypto_register_ahash(&ss_algs[i].alg.hash);
if (err) {
dev_err(ss->dev, "Fail to register %s\n",
ss_algs[i].alg.hash.halg.base.cra_name);
goto error_alg;
}
break;
case CRYPTO_ALG_TYPE_RNG:
err = crypto_register_rng(&ss_algs[i].alg.rng);
if (err) {
dev_err(ss->dev, "Fail to register %s\n",
ss_algs[i].alg.rng.base.cra_name);
}
break;
}
}
/* Ignore error of debugfs */
ss->dbgfs_dir = debugfs_create_dir("sun4i-ss", NULL);
ss->dbgfs_stats = debugfs_create_file("stats", 0444, ss->dbgfs_dir, ss,
&sun4i_ss_debugfs_fops);
return 0;
error_alg:
i--;
for (; i >= 0; i--) {
switch (ss_algs[i].type) {
case CRYPTO_ALG_TYPE_SKCIPHER:
crypto_unregister_skcipher(&ss_algs[i].alg.crypto);
break;
case CRYPTO_ALG_TYPE_AHASH:
crypto_unregister_ahash(&ss_algs[i].alg.hash);
break;
case CRYPTO_ALG_TYPE_RNG:
crypto_unregister_rng(&ss_algs[i].alg.rng);
break;
}
}
error_pm:
sun4i_ss_pm_exit(ss);
return err;
}
static int sun4i_ss_remove(struct platform_device *pdev)
{
int i;
struct sun4i_ss_ctx *ss = platform_get_drvdata(pdev);
for (i = 0; i < ARRAY_SIZE(ss_algs); i++) {
switch (ss_algs[i].type) {
case CRYPTO_ALG_TYPE_SKCIPHER:
crypto_unregister_skcipher(&ss_algs[i].alg.crypto);
break;
case CRYPTO_ALG_TYPE_AHASH:
crypto_unregister_ahash(&ss_algs[i].alg.hash);
break;
case CRYPTO_ALG_TYPE_RNG:
crypto_unregister_rng(&ss_algs[i].alg.rng);
break;
}
}
sun4i_ss_pm_exit(ss);
return 0;
}
static const struct of_device_id a20ss_crypto_of_match_table[] = {
{ .compatible = "allwinner,sun4i-a10-crypto",
.data = &ss_a10_variant
},
{ .compatible = "allwinner,sun8i-a33-crypto",
.data = &ss_a33_variant
},
{}
};
MODULE_DEVICE_TABLE(of, a20ss_crypto_of_match_table);
static struct platform_driver sun4i_ss_driver = {
.probe = sun4i_ss_probe,
.remove = sun4i_ss_remove,
.driver = {
.name = "sun4i-ss",
.pm = &sun4i_ss_pm_ops,
.of_match_table = a20ss_crypto_of_match_table,
},
};
module_platform_driver(sun4i_ss_driver);
MODULE_ALIAS("platform:sun4i-ss");
MODULE_DESCRIPTION("Allwinner Security System cryptographic accelerator");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Corentin LABBE <[email protected]>");
| rperier/linux-rockchip | drivers/crypto/allwinner/sun4i-ss/sun4i-ss-core.c | C | gpl-2.0 | 15,364 |
module Fog
module Compute
class Cloudstack
class Real
# Creates a Load Balancer
#
# {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.4/root_admin/createLoadBalancer.html]
def create_load_balancer(*args)
options = {}
if args[0].is_a? Hash
options = args[0]
options.merge!('command' => 'createLoadBalancer')
else
options.merge!('command' => 'createLoadBalancer',
'sourceipaddressnetworkid' => args[0],
'algorithm' => args[1],
'networkid' => args[2],
'instanceport' => args[3],
'scheme' => args[4],
'name' => args[5],
'sourceport' => args[6])
end
request(options)
end
end
end
end
end
| jonpstone/portfolio-project-rails-mean-movie-reviews | vendor/bundle/ruby/2.3.0/gems/fog-1.42.0/lib/fog/cloudstack/requests/compute/create_load_balancer.rb | Ruby | mit | 852 |
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('sv');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('sv', {
'plural': true,
'months': 'januari,februari,mars,april,maj,juni,juli,augusti,september,oktober,november,december',
'weekdays': 'söndag|sondag,måndag:|en+mandag:|en,tisdag,onsdag,torsdag,fredag,lördag|lordag',
'units': 'millisekund:|er,sekund:|er,minut:|er,timm:e|ar,dag:|ar,veck:a|or|an,månad:|er|en+manad:|er|en,år:||et+ar:||et',
'numbers': 'en|ett,två|tva,tre,fyra,fem,sex,sju,åtta|atta,nio,tio',
'tokens': 'den,för|for',
'articles': 'den',
'short':'den {d} {month} {yyyy}',
'long': 'den {d} {month} {yyyy} {H}:{mm}',
'full': '{Weekday} den {d} {month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'förrgår|i förrgår|iförrgår|forrgar|i forrgar|iforrgar', 'value': -2 },
{ 'name': 'day', 'src': 'går|i går|igår|gar|i gar|igar', 'value': -1 },
{ 'name': 'day', 'src': 'dag|i dag|idag', 'value': 0 },
{ 'name': 'day', 'src': 'morgon|i morgon|imorgon', 'value': 1 },
{ 'name': 'day', 'src': 'över morgon|övermorgon|i över morgon|i övermorgon|iövermorgon|over morgon|overmorgon|i over morgon|i overmorgon|iovermorgon', 'value': 2 },
{ 'name': 'sign', 'src': 'sedan|sen', 'value': -1 },
{ 'name': 'sign', 'src': 'om', 'value': 1 },
{ 'name': 'shift', 'src': 'i förra|förra|i forra|forra', 'value': -1 },
{ 'name': 'shift', 'src': 'denna', 'value': 0 },
{ 'name': 'shift', 'src': 'nästa|nasta', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{1?} {num} {unit} {sign}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{0?} {weekday?} {date?} {month} {year}',
'{date} {month}',
'{shift} {weekday}'
]
});
| highflying/heroku-oauthd | plugins/slashme/node_modules/sugar/lib/locales/sv.js | JavaScript | apache-2.0 | 3,517 |
cask 'aether' do
version '1.2.3'
sha256 '04ca7fbd693bda438436b46315616660ff123ec9d817d802c8c14dcb13711338'
# github.com/nehbit/aether-public was verified as official when first introduced to the cask
url "https://github.com/nehbit/aether-public/releases/download/v#{version}-OSX/Aether.#{version}.dmg"
appcast 'https://github.com/nehbit/aether-public/releases.atom',
checkpoint: '950d21a97d51a45b278ec5efea34a815662be861234c79030d215c1afbcd4fbb'
name 'Aether'
homepage 'http://getaether.net/'
license :affero
app 'Aether.app'
end
| lukeadams/homebrew-cask | Casks/aether.rb | Ruby | bsd-2-clause | 560 |
<!-- Blend a background image and a background color specifying background-position in percentage, such as 50% 50% -->
<!DOCTYPE HTML>
<html>
<head>
<style>
div {
background: url('resources/white_square.svg'), #777777;
background-position: 10% 10%;
width: 200px;
height: 200px;
margin: 10px;
background-blend-mode: multiply;
}
</style>
</head>
<body>
<div></div>
</body>
</html> | scheib/chromium | third_party/blink/web_tests/css3/blending/background-blend-mode-background-position-percentage.html | HTML | bsd-3-clause | 391 |
/*
* 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.
*/
#ifndef _LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H
#define _LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H
#include "filter.h"
namespace log4cxx
{
class XMLFilenameFilter : public Filter
{
public:
XMLFilenameFilter(const std::string& actual, const std::string& expected);
};
}
#endif //_LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H
| johnkit/log4cxx | src/test/cpp/util/xmlfilenamefilter.h | C | apache-2.0 | 1,151 |
// SPDX-License-Identifier: ISC
/* Copyright (C) 2019 MediaTek Inc.
*
* Author: Ryder Lee <[email protected]>
* Felix Fietkau <[email protected]>
*/
#include <linux/of.h>
#include "mt7615.h"
#include "eeprom.h"
static int mt7615_efuse_read(struct mt7615_dev *dev, u32 base,
u16 addr, u8 *data)
{
u32 val;
int i;
val = mt76_rr(dev, base + MT_EFUSE_CTRL);
val &= ~(MT_EFUSE_CTRL_AIN | MT_EFUSE_CTRL_MODE);
val |= FIELD_PREP(MT_EFUSE_CTRL_AIN, addr & ~0xf);
val |= MT_EFUSE_CTRL_KICK;
mt76_wr(dev, base + MT_EFUSE_CTRL, val);
if (!mt76_poll(dev, base + MT_EFUSE_CTRL, MT_EFUSE_CTRL_KICK, 0, 1000))
return -ETIMEDOUT;
udelay(2);
val = mt76_rr(dev, base + MT_EFUSE_CTRL);
if ((val & MT_EFUSE_CTRL_AOUT) == MT_EFUSE_CTRL_AOUT ||
WARN_ON_ONCE(!(val & MT_EFUSE_CTRL_VALID))) {
memset(data, 0x0, 16);
return 0;
}
for (i = 0; i < 4; i++) {
val = mt76_rr(dev, base + MT_EFUSE_RDATA(i));
put_unaligned_le32(val, data + 4 * i);
}
return 0;
}
static int mt7615_efuse_init(struct mt7615_dev *dev, u32 base)
{
int i, len = MT7615_EEPROM_SIZE;
void *buf;
u32 val;
val = mt76_rr(dev, base + MT_EFUSE_BASE_CTRL);
if (val & MT_EFUSE_BASE_CTRL_EMPTY)
return 0;
dev->mt76.otp.data = devm_kzalloc(dev->mt76.dev, len, GFP_KERNEL);
dev->mt76.otp.size = len;
if (!dev->mt76.otp.data)
return -ENOMEM;
buf = dev->mt76.otp.data;
for (i = 0; i + 16 <= len; i += 16) {
int ret;
ret = mt7615_efuse_read(dev, base, i, buf + i);
if (ret)
return ret;
}
return 0;
}
static int mt7615_eeprom_load(struct mt7615_dev *dev, u32 addr)
{
int ret;
ret = mt76_eeprom_init(&dev->mt76, MT7615_EEPROM_FULL_SIZE);
if (ret < 0)
return ret;
return mt7615_efuse_init(dev, addr);
}
static int mt7615_check_eeprom(struct mt76_dev *dev)
{
u16 val = get_unaligned_le16(dev->eeprom.data);
switch (val) {
case 0x7615:
case 0x7622:
case 0x7663:
return 0;
default:
return -EINVAL;
}
}
static void
mt7615_eeprom_parse_hw_band_cap(struct mt7615_dev *dev)
{
u8 val, *eeprom = dev->mt76.eeprom.data;
if (is_mt7663(&dev->mt76)) {
/* dual band */
dev->mphy.cap.has_2ghz = true;
dev->mphy.cap.has_5ghz = true;
return;
}
if (is_mt7622(&dev->mt76)) {
/* 2GHz only */
dev->mphy.cap.has_2ghz = true;
return;
}
if (is_mt7611(&dev->mt76)) {
/* 5GHz only */
dev->mphy.cap.has_5ghz = true;
return;
}
val = FIELD_GET(MT_EE_NIC_WIFI_CONF_BAND_SEL,
eeprom[MT_EE_WIFI_CONF]);
switch (val) {
case MT_EE_5GHZ:
dev->mphy.cap.has_5ghz = true;
break;
case MT_EE_2GHZ:
dev->mphy.cap.has_2ghz = true;
break;
case MT_EE_DBDC:
dev->dbdc_support = true;
fallthrough;
default:
dev->mphy.cap.has_2ghz = true;
dev->mphy.cap.has_5ghz = true;
break;
}
}
static void mt7615_eeprom_parse_hw_cap(struct mt7615_dev *dev)
{
u8 *eeprom = dev->mt76.eeprom.data;
u8 tx_mask, max_nss;
mt7615_eeprom_parse_hw_band_cap(dev);
if (is_mt7663(&dev->mt76)) {
max_nss = 2;
tx_mask = FIELD_GET(MT_EE_HW_CONF1_TX_MASK,
eeprom[MT7663_EE_HW_CONF1]);
} else {
u32 val;
/* read tx-rx mask from eeprom */
val = mt76_rr(dev, MT_TOP_STRAP_STA);
max_nss = val & MT_TOP_3NSS ? 3 : 4;
tx_mask = FIELD_GET(MT_EE_NIC_CONF_TX_MASK,
eeprom[MT_EE_NIC_CONF_0]);
}
if (!tx_mask || tx_mask > max_nss)
tx_mask = max_nss;
dev->chainmask = BIT(tx_mask) - 1;
dev->mphy.antenna_mask = dev->chainmask;
dev->mphy.chainmask = dev->chainmask;
}
static int mt7663_eeprom_get_target_power_index(struct mt7615_dev *dev,
struct ieee80211_channel *chan,
u8 chain_idx)
{
int index, group;
if (chain_idx > 1)
return -EINVAL;
if (chan->band == NL80211_BAND_2GHZ)
return MT7663_EE_TX0_2G_TARGET_POWER + (chain_idx << 4);
group = mt7615_get_channel_group(chan->hw_value);
if (chain_idx == 1)
index = MT7663_EE_TX1_5G_G0_TARGET_POWER;
else
index = MT7663_EE_TX0_5G_G0_TARGET_POWER;
return index + group * 3;
}
int mt7615_eeprom_get_target_power_index(struct mt7615_dev *dev,
struct ieee80211_channel *chan,
u8 chain_idx)
{
int index;
if (is_mt7663(&dev->mt76))
return mt7663_eeprom_get_target_power_index(dev, chan,
chain_idx);
if (chain_idx > 3)
return -EINVAL;
/* TSSI disabled */
if (mt7615_ext_pa_enabled(dev, chan->band)) {
if (chan->band == NL80211_BAND_2GHZ)
return MT_EE_EXT_PA_2G_TARGET_POWER;
else
return MT_EE_EXT_PA_5G_TARGET_POWER;
}
/* TSSI enabled */
if (chan->band == NL80211_BAND_2GHZ) {
index = MT_EE_TX0_2G_TARGET_POWER + chain_idx * 6;
} else {
int group = mt7615_get_channel_group(chan->hw_value);
switch (chain_idx) {
case 1:
index = MT_EE_TX1_5G_G0_TARGET_POWER;
break;
case 2:
index = MT_EE_TX2_5G_G0_TARGET_POWER;
break;
case 3:
index = MT_EE_TX3_5G_G0_TARGET_POWER;
break;
case 0:
default:
index = MT_EE_TX0_5G_G0_TARGET_POWER;
break;
}
index += 5 * group;
}
return index;
}
int mt7615_eeprom_get_power_delta_index(struct mt7615_dev *dev,
enum nl80211_band band)
{
/* assume the first rate has the highest power offset */
if (is_mt7663(&dev->mt76)) {
if (band == NL80211_BAND_2GHZ)
return MT_EE_TX0_5G_G0_TARGET_POWER;
else
return MT7663_EE_5G_RATE_POWER;
}
if (band == NL80211_BAND_2GHZ)
return MT_EE_2G_RATE_POWER;
else
return MT_EE_5G_RATE_POWER;
}
static void mt7615_apply_cal_free_data(struct mt7615_dev *dev)
{
static const u16 ical[] = {
0x53, 0x54, 0x55, 0x56, 0x57, 0x5c, 0x5d, 0x62, 0x63, 0x68,
0x69, 0x6e, 0x6f, 0x73, 0x74, 0x78, 0x79, 0x82, 0x83, 0x87,
0x88, 0x8c, 0x8d, 0x91, 0x92, 0x96, 0x97, 0x9b, 0x9c, 0xa0,
0xa1, 0xaa, 0xab, 0xaf, 0xb0, 0xb4, 0xb5, 0xb9, 0xba, 0xf4,
0xf7, 0xff,
0x140, 0x141, 0x145, 0x146, 0x14a, 0x14b, 0x154, 0x155, 0x159,
0x15a, 0x15e, 0x15f, 0x163, 0x164, 0x168, 0x169, 0x16d, 0x16e,
0x172, 0x173, 0x17c, 0x17d, 0x181, 0x182, 0x186, 0x187, 0x18b,
0x18c
};
static const u16 ical_nocheck[] = {
0x110, 0x111, 0x112, 0x113, 0x114, 0x115, 0x116, 0x117, 0x118,
0x1b5, 0x1b6, 0x1b7, 0x3ac, 0x3ad, 0x3ae, 0x3af, 0x3b0, 0x3b1,
0x3b2
};
u8 *eeprom = dev->mt76.eeprom.data;
u8 *otp = dev->mt76.otp.data;
int i;
if (!otp)
return;
for (i = 0; i < ARRAY_SIZE(ical); i++)
if (!otp[ical[i]])
return;
for (i = 0; i < ARRAY_SIZE(ical); i++)
eeprom[ical[i]] = otp[ical[i]];
for (i = 0; i < ARRAY_SIZE(ical_nocheck); i++)
eeprom[ical_nocheck[i]] = otp[ical_nocheck[i]];
}
static void mt7622_apply_cal_free_data(struct mt7615_dev *dev)
{
static const u16 ical[] = {
0x53, 0x54, 0x55, 0x56, 0xf4, 0xf7, 0x144, 0x156, 0x15b
};
u8 *eeprom = dev->mt76.eeprom.data;
u8 *otp = dev->mt76.otp.data;
int i;
if (!otp)
return;
for (i = 0; i < ARRAY_SIZE(ical); i++) {
if (!otp[ical[i]])
continue;
eeprom[ical[i]] = otp[ical[i]];
}
}
static void mt7615_cal_free_data(struct mt7615_dev *dev)
{
struct device_node *np = dev->mt76.dev->of_node;
if (!np || !of_property_read_bool(np, "mediatek,eeprom-merge-otp"))
return;
switch (mt76_chip(&dev->mt76)) {
case 0x7622:
mt7622_apply_cal_free_data(dev);
break;
case 0x7615:
case 0x7611:
mt7615_apply_cal_free_data(dev);
break;
}
}
int mt7615_eeprom_init(struct mt7615_dev *dev, u32 addr)
{
int ret;
ret = mt7615_eeprom_load(dev, addr);
if (ret < 0)
return ret;
ret = mt7615_check_eeprom(&dev->mt76);
if (ret && dev->mt76.otp.data) {
memcpy(dev->mt76.eeprom.data, dev->mt76.otp.data,
MT7615_EEPROM_SIZE);
} else {
dev->flash_eeprom = true;
mt7615_cal_free_data(dev);
}
mt7615_eeprom_parse_hw_cap(dev);
memcpy(dev->mphy.macaddr, dev->mt76.eeprom.data + MT_EE_MAC_ADDR,
ETH_ALEN);
mt76_eeprom_override(&dev->mphy);
return 0;
}
EXPORT_SYMBOL_GPL(mt7615_eeprom_init);
| HinTak/linux | drivers/net/wireless/mediatek/mt76/mt7615/eeprom.c | C | gpl-2.0 | 7,702 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-mu",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | CrystalZYH/amazing-works | works/ng-BookStore/src/framework/angular-1.3.0.14/i18n/angular-locale_en-mu.js | JavaScript | mit | 2,325 |
module.exports = {
'handles belongsTo (blog, site)': {
mysql: {
result: {
id: 2,
name: 'bookshelfjs.org'
}
},
postgresql: {
result: {
id: 2,
name: 'bookshelfjs.org'
}
},
sqlite3: {
result: {
id: 2,
name: 'bookshelfjs.org'
}
}
},
'handles hasMany (posts)': {
mysql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},
postgresql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},
sqlite3: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}
},
'handles hasOne (meta)': {
mysql: {
result: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},
postgresql: {
result: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},
sqlite3: {
result: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},
'handles belongsToMany (posts)': {
mysql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},
postgresql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},
sqlite3: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
}
},
'eager loads "hasOne" relationships correctly (site -> meta)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
}
},
'eager loads "hasMany" relationships correctly (site -> authors, blogs)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}],
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
}
},
'eager loads "belongsTo" relationships correctly (blog -> site)': {
mysql: {
result: {
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}
},
postgresql: {
result: {
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}
},
sqlite3: {
result: {
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}
}
},
'eager loads "belongsToMany" models correctly (post -> tags)': {
mysql: {
result: {
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
}
},
postgresql: {
result: {
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
}
},
sqlite3: {
result: {
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
}
}
},
'Attaches an empty related model or collection if the `EagerRelation` comes back blank': {
mysql: {
result: {
id: 3,
name: 'backbonejs.org',
meta: {
},
blogs: [],
authors: []
}
},
postgresql: {
result: {
id: 3,
name: 'backbonejs.org',
meta: {
},
authors: [],
blogs: []
}
},
sqlite3: {
result: {
id: 3,
name: 'backbonejs.org',
meta: {
},
blogs: [],
authors: []
}
}
},
'eager loads "hasOne" models correctly (sites -> meta)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},{
id: 2,
name: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
},{
id: 3,
name: 'backbonejs.org',
meta: {
}
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},{
id: 2,
name: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
},{
id: 3,
name: 'backbonejs.org',
meta: {
}
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
},{
id: 2,
name: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
},{
id: 3,
name: 'backbonejs.org',
meta: {
}
}]
}
},
'eager loads "belongsTo" models correctly (blogs -> site)': {
mysql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}]
},
postgresql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}]
},
sqlite3: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 3,
site_id: 2,
name: 'Main Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
site: {
id: 2,
name: 'bookshelfjs.org'
}
}]
}
},
'eager loads "hasMany" models correctly (site -> blogs)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog'
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog'
}]
}
}
},
'eager loads "belongsToMany" models correctly (posts -> tags)': {
mysql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.',
tags: []
}]
},
postgresql: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.',
tags: []
}]
},
sqlite3: {
result: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
tags: [{
id: 1,
name: 'cool',
_pivot_post_id: 1,
_pivot_tag_id: 1
},{
id: 2,
name: 'boring',
_pivot_post_id: 1,
_pivot_tag_id: 2
},{
id: 3,
name: 'exciting',
_pivot_post_id: 1,
_pivot_tag_id: 3
}]
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.',
tags: []
}]
}
},
'eager loads "hasMany" -> "hasMany" (site -> authors.ownPosts)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
}
}
},
'eager loads "hasMany" -> "belongsToMany" (site -> authors.posts)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 2,
_pivot_post_id: 1
},{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.',
_pivot_author_id: 2,
_pivot_post_id: 2
}]
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 2,
_pivot_post_id: 1
},{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.',
_pivot_author_id: 2,
_pivot_post_id: 2
}]
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 1,
_pivot_post_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.',
_pivot_author_id: 2,
_pivot_post_id: 2
},{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.',
_pivot_author_id: 2,
_pivot_post_id: 1
}]
}]
}
}
},
'does multi deep eager loads (site -> authors.ownPosts, authors.site, blogs.posts)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
}]
}]
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
site: {
id: 1,
name: 'knexjs.org'
},
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
site: {
id: 1,
name: 'knexjs.org'
},
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
}]
}]
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}],
site: {
id: 1,
name: 'knexjs.org'
}
}],
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
posts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
posts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
}]
}]
}
}
},
'eager loads "hasMany" -> "hasMany" (sites -> authors.ownPosts)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
},{
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
ownPosts: [{
id: 4,
owner_id: 3,
blog_id: 3,
name: 'This is a new Title 4!',
content: 'Lorem ipsum Anim sed eu sint aute.'
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
ownPosts: [{
id: 5,
owner_id: 4,
blog_id: 4,
name: 'This is a new Title 5!',
content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.'
}]
}]
},{
id: 3,
name: 'backbonejs.org',
authors: []
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
},{
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
ownPosts: [{
id: 4,
owner_id: 3,
blog_id: 3,
name: 'This is a new Title 4!',
content: 'Lorem ipsum Anim sed eu sint aute.'
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
ownPosts: [{
id: 5,
owner_id: 4,
blog_id: 4,
name: 'This is a new Title 5!',
content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.'
}]
}]
},{
id: 3,
name: 'backbonejs.org',
authors: []
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
ownPosts: [{
id: 1,
owner_id: 1,
blog_id: 1,
name: 'This is a new Title!',
content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.'
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
ownPosts: [{
id: 2,
owner_id: 2,
blog_id: 2,
name: 'This is a new Title 2!',
content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.'
},{
id: 3,
owner_id: 2,
blog_id: 1,
name: 'This is a new Title 3!',
content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.'
}]
}]
},{
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
ownPosts: [{
id: 4,
owner_id: 3,
blog_id: 3,
name: 'This is a new Title 4!',
content: 'Lorem ipsum Anim sed eu sint aute.'
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
ownPosts: [{
id: 5,
owner_id: 4,
blog_id: 4,
name: 'This is a new Title 5!',
content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.'
}]
}]
},{
id: 3,
name: 'backbonejs.org',
authors: []
}]
}
},
'eager loads relations on a populated model (site -> blogs, authors.site)': {
mysql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org'
}
}
},
'eager loads attributes on a collection (sites -> blogs, authors.site)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org'
},{
id: 2,
name: 'bookshelfjs.org'
},{
id: 3,
name: 'backbonejs.org'
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org'
},{
id: 2,
name: 'bookshelfjs.org'
},{
id: 3,
name: 'backbonejs.org'
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org'
},{
id: 2,
name: 'bookshelfjs.org'
},{
id: 3,
name: 'backbonejs.org'
}]
}
},
'works with many-to-many (user -> roles)': {
mysql: {
result: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
},
postgresql: {
result: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
},
sqlite3: {
result: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
},
'works with eager loaded many-to-many (user -> roles)': {
mysql: {
result: {
uid: 1,
username: 'root',
roles: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
},
postgresql: {
result: {
uid: 1,
username: 'root',
roles: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
},
sqlite3: {
result: {
uid: 1,
username: 'root',
roles: [{
rid: 4,
name: 'admin',
_pivot_uid: 1,
_pivot_rid: 4
}]
}
}
},
'handles morphOne (photo)': {
mysql: {
result: {
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors'
}
},
postgresql: {
result: {
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors'
}
},
sqlite3: {
result: {
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors'
}
}
},
'handles morphMany (photo)': {
mysql: {
result: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},
postgresql: {
result: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},
sqlite3: {
result: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
}
},
'handles morphTo (imageable "authors")': {
mysql: {
result: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},
postgresql: {
result: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},
sqlite3: {
result: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
}
},
'handles morphTo (imageable "sites")': {
mysql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
postgresql: {
result: {
id: 1,
name: 'knexjs.org'
}
},
sqlite3: {
result: {
id: 1,
name: 'knexjs.org'
}
}
},
'eager loads morphMany (sites -> photos)': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
photos: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},{
id: 2,
name: 'bookshelfjs.org',
photos: [{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
}]
},{
id: 3,
name: 'backbonejs.org',
photos: []
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
photos: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},{
id: 2,
name: 'bookshelfjs.org',
photos: [{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
}]
},{
id: 3,
name: 'backbonejs.org',
photos: []
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
photos: [{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites'
}]
},{
id: 2,
name: 'bookshelfjs.org',
photos: [{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites'
}]
},{
id: 3,
name: 'backbonejs.org',
photos: []
}]
}
},
'eager loads morphTo (photos -> imageable)': {
mysql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
postgresql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
sqlite3: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org'
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org'
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
}
},
'eager loads beyond the morphTo, where possible': {
mysql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
postgresql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
},
sqlite3: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageable: {
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageable: {
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageable: {
id: 1,
name: 'knexjs.org',
authors: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser'
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe'
}]
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageable: {
id: 2,
name: 'bookshelfjs.org',
authors: [{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown'
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy'
}]
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageable: {
}
}]
}
},
'handles hasMany `through`': {
mysql: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},
postgresql: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},
sqlite3: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
}
},
'eager loads hasMany `through`': {
mysql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
},
postgresql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
},
sqlite3: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
}
},
'eager loads hasMany `through` using where / fetchAll': {
mysql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
},
postgresql: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
},
sqlite3: {
result: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
comments: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
_pivot_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
comments: []
}]
}
},
'handles hasOne `through`': {
mysql: {
result: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},
postgresql: {
result: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},
sqlite3: {
result: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
}
},
'eager loads hasOne `through`': {
mysql: {
result: [{
id: 1,
name: 'knexjs.org',
info: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},{
id: 2,
name: 'bookshelfjs.org',
info: {
id: 2,
meta_id: 2,
other_description: 'This is an info block for an eager hasOne -> through test',
_pivot_id: 2,
_pivot_site_id: 2
}
}]
},
postgresql: {
result: [{
id: 1,
name: 'knexjs.org',
info: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},{
id: 2,
name: 'bookshelfjs.org',
info: {
id: 2,
meta_id: 2,
other_description: 'This is an info block for an eager hasOne -> through test',
_pivot_id: 2,
_pivot_site_id: 2
}
}]
},
sqlite3: {
result: [{
id: 1,
name: 'knexjs.org',
info: {
id: 1,
meta_id: 1,
other_description: 'This is an info block for hasOne -> through test',
_pivot_id: 1,
_pivot_site_id: 1
}
},{
id: 2,
name: 'bookshelfjs.org',
info: {
id: 2,
meta_id: 2,
other_description: 'This is an info block for an eager hasOne -> through test',
_pivot_id: 2,
_pivot_site_id: 2
}
}]
}
},
'eager loads belongsToMany `through`': {
mysql: {
result: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_owner_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 3,
_pivot_owner_id: 2,
_pivot_blog_id: 1
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
_pivot_id: 2,
_pivot_owner_id: 2,
_pivot_blog_id: 2
}]
},{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
blogs: [{
id: 3,
site_id: 2,
name: 'Main Site Blog',
_pivot_id: 4,
_pivot_owner_id: 3,
_pivot_blog_id: 3
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
blogs: [{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
_pivot_id: 5,
_pivot_owner_id: 4,
_pivot_blog_id: 4
}]
}]
},
postgresql: {
result: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_owner_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 3,
_pivot_owner_id: 2,
_pivot_blog_id: 1
},{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
_pivot_id: 2,
_pivot_owner_id: 2,
_pivot_blog_id: 2
}]
},{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
blogs: [{
id: 3,
site_id: 2,
name: 'Main Site Blog',
_pivot_id: 4,
_pivot_owner_id: 3,
_pivot_blog_id: 3
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
blogs: [{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
_pivot_id: 5,
_pivot_owner_id: 4,
_pivot_blog_id: 4
}]
}]
},
sqlite3: {
result: [{
id: 1,
site_id: 1,
first_name: 'Tim',
last_name: 'Griesser',
blogs: [{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_owner_id: 1,
_pivot_blog_id: 1
}]
},{
id: 2,
site_id: 1,
first_name: 'Bazooka',
last_name: 'Joe',
blogs: [{
id: 2,
site_id: 1,
name: 'Alternate Site Blog',
_pivot_id: 2,
_pivot_owner_id: 2,
_pivot_blog_id: 2
},{
id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 3,
_pivot_owner_id: 2,
_pivot_blog_id: 1
}]
},{
id: 3,
site_id: 2,
first_name: 'Charlie',
last_name: 'Brown',
blogs: [{
id: 3,
site_id: 2,
name: 'Main Site Blog',
_pivot_id: 4,
_pivot_owner_id: 3,
_pivot_blog_id: 3
}]
},{
id: 4,
site_id: 2,
first_name: 'Ron',
last_name: 'Burgundy',
blogs: [{
id: 4,
site_id: 2,
name: 'Alternate Site Blog',
_pivot_id: 5,
_pivot_owner_id: 4,
_pivot_blog_id: 4
}]
}]
}
},
'eager loads belongsTo `through`': {
mysql: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
blog:
{ id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_blog_id: 1
}
}]
},
postgresql: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
blog:
{ id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_blog_id: 1
}
}]
},
sqlite3: {
result: [{
id: 1,
post_id: 1,
name: '(blank)',
email: '[email protected]',
comment: 'this is neat.',
blog:
{ id: 1,
site_id: 1,
name: 'Main Site Blog',
_pivot_id: 1,
_pivot_blog_id: 1
}
}]
}
},
'#65 - should eager load correctly for models': {
mysql: {
result: {
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
}
},
postgresql: {
result: {
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: '3',
name: 'search engine'
}
}
},
sqlite3: {
result: {
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
}
}
},
'#65 - should eager load correctly for collections': {
mysql: {
result: [{
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
},{
hostname: 'apple.com',
instance_id: 10,
route: null,
instance: {
id: 10,
name: 'computers'
}
}]
},
postgresql: {
result: [{
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: '3',
name: 'search engine'
}
},{
hostname: 'apple.com',
instance_id: 10,
route: null,
instance: {
id: '10',
name: 'computers'
}
}]
},
sqlite3: {
result: [{
hostname: 'google.com',
instance_id: 3,
route: null,
instance: {
id: 3,
name: 'search engine'
}
},{
hostname: 'apple.com',
instance_id: 10,
route: null,
instance: {
id: 10,
name: 'computers'
}
}]
}
},
'parses eager-loaded morphTo relations (model)': {
mysql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 1,
site_id_parsed: 1,
first_name_parsed: 'Tim',
last_name_parsed: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 2,
site_id_parsed: 1,
first_name_parsed: 'Bazooka',
last_name_parsed: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageableParsed: {
}
}]
},
postgresql: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 1,
site_id_parsed: 1,
first_name_parsed: 'Tim',
last_name_parsed: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 2,
site_id_parsed: 1,
first_name_parsed: 'Bazooka',
last_name_parsed: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageableParsed: {
}
}]
},
sqlite3: {
result: [{
id: 1,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 1,
site_id_parsed: 1,
first_name_parsed: 'Tim',
last_name_parsed: 'Griesser'
}
},{
id: 2,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'authors',
imageableParsed: {
id_parsed: 2,
site_id_parsed: 1,
first_name_parsed: 'Bazooka',
last_name_parsed: 'Joe'
}
},{
id: 3,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 4,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 1,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 1,
name_parsed: 'knexjs.org',
meta: {
id: 1,
site_id: 1,
description: 'This is a description for the Knexjs Site'
}
}
},{
id: 5,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 6,
url: 'https://www.google.com/images/srpr/logo4w.png',
caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.',
imageable_id: 2,
imageable_type: 'sites',
imageableParsed: {
id_parsed: 2,
name_parsed: 'bookshelfjs.org',
meta: {
id: 2,
site_id: 2,
description: 'This is a description for the Bookshelfjs Site'
}
}
},{
id: 7,
url: 'http://image.dev',
caption: 'this is a test image',
imageable_id: 10,
imageable_type: 'sites',
imageableParsed: {
}
}]
}
}
};
| kellynloehr/paul | paul/node_modules/bookshelf/test/integration/output/Relations.js | JavaScript | mit | 99,848 |
CKEDITOR.plugins.setLang("colorbutton","lv",{auto:"Automātiska",bgColorTitle:"Fona krāsa",colors:{"000":"Melns",8E5:"Sarkanbrūns","8B4513":"Sedlu brūns","2F4F4F":"Tumšas tāfeles pelēks","008080":"Zili-zaļš","000080":"Jūras","4B0082":"Indigo",696969:"Tumši pelēks",B22222:"Ķieģeļsarkans",A52A2A:"Brūns",DAA520:"Zelta","006400":"Tumši zaļš","40E0D0":"Tirkīzs","0000CD":"Vidēji zils",800080:"Purpurs",808080:"Pelēks",F00:"Sarkans",FF8C00:"Tumši oranžs",FFD700:"Zelta","008000":"Zaļš","0FF":"Tumšzils","00F":"Zils",
EE82EE:"Violets",A9A9A9:"Pelēks",FFA07A:"Gaiši laškrāsas",FFA500:"Oranžs",FFFF00:"Dzeltens","00FF00":"Laima",AFEEEE:"Gaiši tirkīza",ADD8E6:"Gaiši zils",DDA0DD:"Plūmju",D3D3D3:"Gaiši pelēks",FFF0F5:"Lavandas sārts",FAEBD7:"Antīki balts",FFFFE0:"Gaiši dzeltens",F0FFF0:"Meduspile",F0FFFF:"Debesszils",F0F8FF:"Alises zils",E6E6FA:"Lavanda",FFF:"Balts"},more:"Plašāka palete...",panelTitle:"Krāsa",textColorTitle:"Teksta krāsa"}); | hikmahtiar6/camar_erp_ci | web/vendor/plugins-admin/ckeditor/plugins/colorbutton/lang/lv.js | JavaScript | mit | 983 |
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class BFTask;
@class PFObject;
typedef NS_ENUM(NSUInteger, PFCurrentObjectStorageType) {
PFCurrentObjectStorageTypeFile = 1,
PFCurrentObjectStorageTypeOfflineStore,
};
@protocol PFCurrentObjectControlling <NSObject>
@property (nonatomic, assign, readonly) PFCurrentObjectStorageType storageType;
///--------------------------------------
/// @name Current
///--------------------------------------
- (BFTask *)getCurrentObjectAsync;
- (BFTask *)saveCurrentObjectAsync:(PFObject *)object;
@end
NS_ASSUME_NONNULL_END
| patrick-ogrady/godseye-ios | sample/SampleBroadcaster-Swift/Pods/Parse/Parse/Internal/Object/CurrentController/PFCurrentObjectControlling.h | C | mit | 898 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using Microsoft.Test.ModuleCore;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCReadOuterXml : BridgeHelpers
{
// Element names to test ReadOuterXml on
private static string s_EMP1 = "EMPTY1";
private static string s_EMP2 = "EMPTY2";
private static string s_EMP3 = "EMPTY3";
private static string s_EMP4 = "EMPTY4";
private static string s_ENT1 = "ENTITY1";
private static string s_NEMP0 = "NONEMPTY0";
private static string s_NEMP1 = "NONEMPTY1";
private static string s_NEMP2 = "NONEMPTY2";
private static string s_ELEM1 = "CHARS2";
private static string s_ELEM2 = "SKIP3";
private static string s_ELEM3 = "CONTENT";
private static string s_ELEM4 = "COMPLEX";
// Element names after the ReadOuterXml call
private static string s_NEXT1 = "COMPLEX";
private static string s_NEXT2 = "ACT2";
private static string s_NEXT3 = "CHARS_ELEM1";
private static string s_NEXT4 = "AFTERSKIP3";
private static string s_NEXT5 = "TITLE";
private static string s_NEXT6 = "ENTITY2";
private static string s_NEXT7 = "DUMMY";
// Expected strings returned by ReadOuterXml
private static string s_EXP_EMP1 = "<EMPTY1 />";
private static string s_EXP_EMP2 = "<EMPTY2 val=\"abc\" />";
private static string s_EXP_EMP3 = "<EMPTY3></EMPTY3>";
private static string s_EXP_EMP4 = "<EMPTY4 val=\"abc\"></EMPTY4>";
private static string s_EXP_NEMP1 = "<NONEMPTY1>ABCDE</NONEMPTY1>";
private static string s_EXP_NEMP2 = "<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>";
private static string s_EXP_ELEM1 = "<CHARS2>xxx<MARKUP />yyy</CHARS2>";
private static string s_EXP_ELEM2 = "<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3>";
private static string s_EXP_ELEM3 = "<CONTENT><e1 a1=\"a1value\" a2=\"a2value\"><e2 a1=\"a1value\" a2=\"a2value\"><e3 a1=\"a1value\" a2=\"a2value\">leave</e3></e2></e1></CONTENT>";
private static string s_EXP_ELEM4 = "<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>";
private static string s_EXP_ENT1_EXPAND_CHAR = "<ENTITY1 att1=\"xxx<xxxAxxxCxxxe1fooxxx\">xxx>xxxBxxxDxxxe1fooxxx</ENTITY1>";
public override void Init()
{
base.Init();
}
public override void Terminate()
{
base.Terminate();
}
void TestOuterOnText(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnElement(DataReader, strElem);
TestLog.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Text, String.Empty, "\n"), true, "vn2");
}
void TestOuterOnElement(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnElement(DataReader, strElem);
TestLog.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, strNextElemName, String.Empty), true, "vn2");
}
void TestOuterOnAttribute(string strElem, string strName, string strValue)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnElement(DataReader, strElem);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected = String.Format("{0}=\"{1}\"", strName, strValue);
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Attribute, strName, strValue), true, "vn");
}
void TestOuterOnNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnNodeType(DataReader, nt);
DataReader.Read();
XmlNodeType expNt = DataReader.NodeType;
string expName = DataReader.Name;
string expValue = DataReader.Value;
PositionOnNodeType(DataReader, nt);
TestLog.Compare(DataReader.ReadOuterXml(), String.Empty, "outer");
TestLog.Compare(VerifyNode(DataReader, expNt, expName, expValue), true, "vn");
}
//[Variation("ReadOuterXml on empty element w/o attributes", Priority = 0)]
public void ReadOuterXml1()
{
TestOuterOnText(s_EMP1, s_EXP_EMP1, s_EMP2, true);
}
//[Variation("ReadOuterXml on empty element w/ attributes", Priority = 0)]
public void ReadOuterXml2()
{
TestOuterOnText(s_EMP2, s_EXP_EMP2, s_EMP3, true);
}
//[Variation("ReadOuterXml on full empty element w/o attributes")]
public void ReadOuterXml3()
{
TestOuterOnText(s_EMP3, s_EXP_EMP3, s_NEMP0, true);
}
//[Variation("ReadOuterXml on full empty element w/ attributes")]
public void ReadOuterXml4()
{
TestOuterOnText(s_EMP4, s_EXP_EMP4, s_NEXT1, true);
}
//[Variation("ReadOuterXml on element with text content", Priority = 0)]
public void ReadOuterXml5()
{
TestOuterOnText(s_NEMP1, s_EXP_NEMP1, s_NEMP2, true);
}
//[Variation("ReadOuterXml on element with attributes", Priority = 0)]
public void ReadOuterXml6()
{
TestOuterOnText(s_NEMP2, s_EXP_NEMP2, s_NEXT2, true);
}
//[Variation("ReadOuterXml on element with text and markup content")]
public void ReadOuterXml7()
{
TestOuterOnText(s_ELEM1, s_EXP_ELEM1, s_NEXT3, true);
}
//[Variation("ReadOuterXml with multiple level of elements")]
public void ReadOuterXml8()
{
TestOuterOnElement(s_ELEM2, s_EXP_ELEM2, s_NEXT4, false);
}
//[Variation("ReadOuterXml with multiple level of elements, text and attributes", Priority = 0)]
public void ReadOuterXml9()
{
string strExpected = s_EXP_ELEM3;
TestOuterOnText(s_ELEM3, strExpected, s_NEXT5, true);
}
//[Variation("ReadOuterXml on element with complex content (CDATA, PIs, Comments)", Priority = 0)]
public void ReadOuterXml10()
{
TestOuterOnText(s_ELEM4, s_EXP_ELEM4, s_NEXT7, true);
}
//[Variation("ReadOuterXml on attribute node of empty element")]
public void ReadOuterXml12()
{
TestOuterOnAttribute(s_EMP2, "val", "abc");
}
//[Variation("ReadOuterXml on attribute node of full empty element")]
public void ReadOuterXml13()
{
TestOuterOnAttribute(s_EMP4, "val", "abc");
}
//[Variation("ReadOuterXml on attribute node", Priority = 0)]
public void ReadOuterXml14()
{
TestOuterOnAttribute(s_NEMP2, "val", "abc");
}
//[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandEntities", Priority = 0)]
public void ReadOuterXml15()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected = "att1=\"xxx<xxxAxxxCxxxe1fooxxx\"";
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
}
//[Variation("ReadOuterXml on ProcessingInstruction")]
public void ReadOuterXml17()
{
TestOuterOnNodeType(XmlNodeType.ProcessingInstruction);
}
//[Variation("ReadOuterXml on CDATA")]
public void ReadOuterXml24()
{
TestOuterOnNodeType(XmlNodeType.CDATA);
}
[Fact]
[ActiveIssue(641)]
public void ReadOuterXmlOnXmlDeclarationAttributes()
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
DataReader.Read();
try
{
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentOutOfRangeException) { }
Assert.True(TestLog.Compare(DataReader.ReadOuterXml(), String.Empty, "outer"));
Assert.True(TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Attribute, String.Empty, "UTF-8"), false, "vn"));
}
//[Variation("ReadOuterXml on element with entities, EntityHandling = ExpandCharEntities")]
public void TRReadOuterXml27()
{
string strExpected = s_EXP_ENT1_EXPAND_CHAR;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, s_ENT1);
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, s_NEXT6, String.Empty), true, "vn");
}
//[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandCharEntites")]
public void TRReadOuterXml28()
{
string strExpected = "att1=\"xxx<xxxAxxxCxxxe1fooxxx\"";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
}
//[Variation("One large element")]
public void TestTextReadOuterXml29()
{
String strp = "a ";
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
string strxml = "<Name a=\"b\">" + strp + " </Name>";
XmlReader DataReader = GetReaderStr(strxml);
DataReader.Read();
TestLog.Compare(DataReader.ReadOuterXml(), strxml, "rox");
}
//[Variation("Read OuterXml when Namespaces=false and has an attribute xmlns")]
public void ReadOuterXmlWhenNamespacesEqualsToFalseAndHasAnAttributeXmlns()
{
string xml = "<?xml version='1.0' encoding='utf-8' ?> <foo xmlns=\"testing\"><bar id=\"1\" /></foo>";
XmlReader DataReader = GetReaderStr(xml);
DataReader.MoveToContent();
TestLog.Compare(DataReader.ReadOuterXml(), "<foo xmlns=\"testing\"><bar id=\"1\" /></foo>", "mismatch");
}
}
}
}
} | vs-team/corefx | src/System.Xml.XDocument/tests/xNodeReader/ReadOuterXml.cs | C# | mit | 13,201 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="ApiGen 2.8.0" />
<meta name="robots" content="noindex" />
<title>File Mandrill/Exceptions.php</title>
<script type="text/javascript" src="resources/combined.js?394153670"></script>
<script type="text/javascript" src="elementlist.js?882160656"></script>
<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li class="active"><a href="namespace-None.html">None</a>
</li>
<li><a href="namespace-PHP.html">PHP</a>
</li>
</ul>
</div>
<hr />
<div id="elements">
<h3>Classes</h3>
<ul>
<li><a href="class-Mandrill.html">Mandrill</a></li>
<li><a href="class-Mandrill_Exports.html">Mandrill_Exports</a></li>
<li><a href="class-Mandrill_Inbound.html">Mandrill_Inbound</a></li>
<li><a href="class-Mandrill_Internal.html">Mandrill_Internal</a></li>
<li><a href="class-Mandrill_Ips.html">Mandrill_Ips</a></li>
<li><a href="class-Mandrill_Messages.html">Mandrill_Messages</a></li>
<li><a href="class-Mandrill_Metadata.html">Mandrill_Metadata</a></li>
<li><a href="class-Mandrill_Rejects.html">Mandrill_Rejects</a></li>
<li><a href="class-Mandrill_Senders.html">Mandrill_Senders</a></li>
<li><a href="class-Mandrill_Subaccounts.html">Mandrill_Subaccounts</a></li>
<li><a href="class-Mandrill_Tags.html">Mandrill_Tags</a></li>
<li><a href="class-Mandrill_Templates.html">Mandrill_Templates</a></li>
<li><a href="class-Mandrill_Urls.html">Mandrill_Urls</a></li>
<li><a href="class-Mandrill_Users.html">Mandrill_Users</a></li>
<li><a href="class-Mandrill_Webhooks.html">Mandrill_Webhooks</a></li>
<li><a href="class-Mandrill_Whitelists.html">Mandrill_Whitelists</a></li>
</ul>
<h3>Exceptions</h3>
<ul>
<li><a href="class-Mandrill_Error.html">Mandrill_Error</a></li>
<li><a href="class-Mandrill_HttpError.html">Mandrill_HttpError</a></li>
<li><a href="class-Mandrill_Invalid_CustomDNS.html">Mandrill_Invalid_CustomDNS</a></li>
<li><a href="class-Mandrill_Invalid_CustomDNSPending.html">Mandrill_Invalid_CustomDNSPending</a></li>
<li><a href="class-Mandrill_Invalid_DeleteDefaultPool.html">Mandrill_Invalid_DeleteDefaultPool</a></li>
<li><a href="class-Mandrill_Invalid_DeleteNonEmptyPool.html">Mandrill_Invalid_DeleteNonEmptyPool</a></li>
<li><a href="class-Mandrill_Invalid_EmptyDefaultPool.html">Mandrill_Invalid_EmptyDefaultPool</a></li>
<li><a href="class-Mandrill_Invalid_Key.html">Mandrill_Invalid_Key</a></li>
<li><a href="class-Mandrill_Invalid_Reject.html">Mandrill_Invalid_Reject</a></li>
<li><a href="class-Mandrill_Invalid_Tag_Name.html">Mandrill_Invalid_Tag_Name</a></li>
<li><a href="class-Mandrill_Invalid_Template.html">Mandrill_Invalid_Template</a></li>
<li><a href="class-Mandrill_IP_ProvisionLimit.html">Mandrill_IP_ProvisionLimit</a></li>
<li><a href="class-Mandrill_Metadata_FieldLimit.html">Mandrill_Metadata_FieldLimit</a></li>
<li><a href="class-Mandrill_NoSendingHistory.html">Mandrill_NoSendingHistory</a></li>
<li><a href="class-Mandrill_PaymentRequired.html">Mandrill_PaymentRequired</a></li>
<li><a href="class-Mandrill_PoorReputation.html">Mandrill_PoorReputation</a></li>
<li><a href="class-Mandrill_ServiceUnavailable.html">Mandrill_ServiceUnavailable</a></li>
<li><a href="class-Mandrill_Unknown_Export.html">Mandrill_Unknown_Export</a></li>
<li><a href="class-Mandrill_Unknown_InboundDomain.html">Mandrill_Unknown_InboundDomain</a></li>
<li><a href="class-Mandrill_Unknown_InboundRoute.html">Mandrill_Unknown_InboundRoute</a></li>
<li><a href="class-Mandrill_Unknown_IP.html">Mandrill_Unknown_IP</a></li>
<li><a href="class-Mandrill_Unknown_Message.html">Mandrill_Unknown_Message</a></li>
<li><a href="class-Mandrill_Unknown_MetadataField.html">Mandrill_Unknown_MetadataField</a></li>
<li><a href="class-Mandrill_Unknown_Pool.html">Mandrill_Unknown_Pool</a></li>
<li><a href="class-Mandrill_Unknown_Sender.html">Mandrill_Unknown_Sender</a></li>
<li><a href="class-Mandrill_Unknown_Subaccount.html">Mandrill_Unknown_Subaccount</a></li>
<li><a href="class-Mandrill_Unknown_Template.html">Mandrill_Unknown_Template</a></li>
<li><a href="class-Mandrill_Unknown_TrackingDomain.html">Mandrill_Unknown_TrackingDomain</a></li>
<li class="active"><a href="class-Mandrill_Unknown_Url.html">Mandrill_Unknown_Url</a></li>
<li><a href="class-Mandrill_Unknown_Webhook.html">Mandrill_Unknown_Webhook</a></li>
<li><a href="class-Mandrill_ValidationError.html">Mandrill_ValidationError</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="text" />
<input type="submit" value="Search" />
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-None.html" title="Summary of None"><span>Namespace</span></a>
</li>
<li>
<a href="class-Mandrill_Unknown_Url.html" title="Summary of Mandrill_Unknown_Url"><span>Class</span></a>
</li>
</ul>
<ul>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
</ul>
<ul>
</ul>
</div>
<pre><code><span id="1" class="l"><a class="l" href="#1"> 1: </a><span class="xlang"><?php</span>
</span><span id="2" class="l"><a class="l" href="#2"> 2: </a>
</span><span id="3" class="l"><a class="l" href="#3"> 3: </a><span class="php-keyword1">class</span> <a id="Mandrill_Error" href="#Mandrill_Error">Mandrill_Error</a> <span class="php-keyword1">extends</span> Exception {}
</span><span id="4" class="l"><a class="l" href="#4"> 4: </a><span class="php-keyword1">class</span> <a id="Mandrill_HttpError" href="#Mandrill_HttpError">Mandrill_HttpError</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="5" class="l"><a class="l" href="#5"> 5: </a>
</span><span id="6" class="l"><a class="l" href="#6"> 6: </a><span class="php-comment">/**
</span></span><span id="7" class="l"><a class="l" href="#7"> 7: </a><span class="php-comment"> * The parameters passed to the API call are invalid or not provided when required
</span></span><span id="8" class="l"><a class="l" href="#8"> 8: </a><span class="php-comment"> */</span>
</span><span id="9" class="l"><a class="l" href="#9"> 9: </a><span class="php-keyword1">class</span> <a id="Mandrill_ValidationError" href="#Mandrill_ValidationError">Mandrill_ValidationError</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="10" class="l"><a class="l" href="#10"> 10: </a>
</span><span id="11" class="l"><a class="l" href="#11"> 11: </a><span class="php-comment">/**
</span></span><span id="12" class="l"><a class="l" href="#12"> 12: </a><span class="php-comment"> * The provided API key is not a valid Mandrill API key
</span></span><span id="13" class="l"><a class="l" href="#13"> 13: </a><span class="php-comment"> */</span>
</span><span id="14" class="l"><a class="l" href="#14"> 14: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_Key" href="#Mandrill_Invalid_Key">Mandrill_Invalid_Key</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="15" class="l"><a class="l" href="#15"> 15: </a>
</span><span id="16" class="l"><a class="l" href="#16"> 16: </a><span class="php-comment">/**
</span></span><span id="17" class="l"><a class="l" href="#17"> 17: </a><span class="php-comment"> * The requested feature requires payment.
</span></span><span id="18" class="l"><a class="l" href="#18"> 18: </a><span class="php-comment"> */</span>
</span><span id="19" class="l"><a class="l" href="#19"> 19: </a><span class="php-keyword1">class</span> <a id="Mandrill_PaymentRequired" href="#Mandrill_PaymentRequired">Mandrill_PaymentRequired</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="20" class="l"><a class="l" href="#20"> 20: </a>
</span><span id="21" class="l"><a class="l" href="#21"> 21: </a><span class="php-comment">/**
</span></span><span id="22" class="l"><a class="l" href="#22"> 22: </a><span class="php-comment"> * The provided subaccount id does not exist.
</span></span><span id="23" class="l"><a class="l" href="#23"> 23: </a><span class="php-comment"> */</span>
</span><span id="24" class="l"><a class="l" href="#24"> 24: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Subaccount" href="#Mandrill_Unknown_Subaccount">Mandrill_Unknown_Subaccount</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="25" class="l"><a class="l" href="#25"> 25: </a>
</span><span id="26" class="l"><a class="l" href="#26"> 26: </a><span class="php-comment">/**
</span></span><span id="27" class="l"><a class="l" href="#27"> 27: </a><span class="php-comment"> * The requested template does not exist
</span></span><span id="28" class="l"><a class="l" href="#28"> 28: </a><span class="php-comment"> */</span>
</span><span id="29" class="l"><a class="l" href="#29"> 29: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Template" href="#Mandrill_Unknown_Template">Mandrill_Unknown_Template</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="30" class="l"><a class="l" href="#30"> 30: </a>
</span><span id="31" class="l"><a class="l" href="#31"> 31: </a><span class="php-comment">/**
</span></span><span id="32" class="l"><a class="l" href="#32"> 32: </a><span class="php-comment"> * The subsystem providing this API call is down for maintenance
</span></span><span id="33" class="l"><a class="l" href="#33"> 33: </a><span class="php-comment"> */</span>
</span><span id="34" class="l"><a class="l" href="#34"> 34: </a><span class="php-keyword1">class</span> <a id="Mandrill_ServiceUnavailable" href="#Mandrill_ServiceUnavailable">Mandrill_ServiceUnavailable</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="35" class="l"><a class="l" href="#35"> 35: </a>
</span><span id="36" class="l"><a class="l" href="#36"> 36: </a><span class="php-comment">/**
</span></span><span id="37" class="l"><a class="l" href="#37"> 37: </a><span class="php-comment"> * The provided message id does not exist.
</span></span><span id="38" class="l"><a class="l" href="#38"> 38: </a><span class="php-comment"> */</span>
</span><span id="39" class="l"><a class="l" href="#39"> 39: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Message" href="#Mandrill_Unknown_Message">Mandrill_Unknown_Message</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="40" class="l"><a class="l" href="#40"> 40: </a>
</span><span id="41" class="l"><a class="l" href="#41"> 41: </a><span class="php-comment">/**
</span></span><span id="42" class="l"><a class="l" href="#42"> 42: </a><span class="php-comment"> * The requested tag does not exist or contains invalid characters
</span></span><span id="43" class="l"><a class="l" href="#43"> 43: </a><span class="php-comment"> */</span>
</span><span id="44" class="l"><a class="l" href="#44"> 44: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_Tag_Name" href="#Mandrill_Invalid_Tag_Name">Mandrill_Invalid_Tag_Name</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="45" class="l"><a class="l" href="#45"> 45: </a>
</span><span id="46" class="l"><a class="l" href="#46"> 46: </a><span class="php-comment">/**
</span></span><span id="47" class="l"><a class="l" href="#47"> 47: </a><span class="php-comment"> * The requested email is not in the rejection list
</span></span><span id="48" class="l"><a class="l" href="#48"> 48: </a><span class="php-comment"> */</span>
</span><span id="49" class="l"><a class="l" href="#49"> 49: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_Reject" href="#Mandrill_Invalid_Reject">Mandrill_Invalid_Reject</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="50" class="l"><a class="l" href="#50"> 50: </a>
</span><span id="51" class="l"><a class="l" href="#51"> 51: </a><span class="php-comment">/**
</span></span><span id="52" class="l"><a class="l" href="#52"> 52: </a><span class="php-comment"> * The requested sender does not exist
</span></span><span id="53" class="l"><a class="l" href="#53"> 53: </a><span class="php-comment"> */</span>
</span><span id="54" class="l"><a class="l" href="#54"> 54: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Sender" href="#Mandrill_Unknown_Sender">Mandrill_Unknown_Sender</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="55" class="l"><a class="l" href="#55"> 55: </a>
</span><span id="56" class="l"><a class="l" href="#56"> 56: </a><span class="php-comment">/**
</span></span><span id="57" class="l"><a class="l" href="#57"> 57: </a><span class="php-comment"> * The requested URL has not been seen in a tracked link
</span></span><span id="58" class="l"><a class="l" href="#58"> 58: </a><span class="php-comment"> */</span>
</span><span id="59" class="l"><a class="l" href="#59"> 59: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Url" href="#Mandrill_Unknown_Url">Mandrill_Unknown_Url</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="60" class="l"><a class="l" href="#60"> 60: </a>
</span><span id="61" class="l"><a class="l" href="#61"> 61: </a><span class="php-comment">/**
</span></span><span id="62" class="l"><a class="l" href="#62"> 62: </a><span class="php-comment"> * The provided tracking domain does not exist.
</span></span><span id="63" class="l"><a class="l" href="#63"> 63: </a><span class="php-comment"> */</span>
</span><span id="64" class="l"><a class="l" href="#64"> 64: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_TrackingDomain" href="#Mandrill_Unknown_TrackingDomain">Mandrill_Unknown_TrackingDomain</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="65" class="l"><a class="l" href="#65"> 65: </a>
</span><span id="66" class="l"><a class="l" href="#66"> 66: </a><span class="php-comment">/**
</span></span><span id="67" class="l"><a class="l" href="#67"> 67: </a><span class="php-comment"> * The given template name already exists or contains invalid characters
</span></span><span id="68" class="l"><a class="l" href="#68"> 68: </a><span class="php-comment"> */</span>
</span><span id="69" class="l"><a class="l" href="#69"> 69: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_Template" href="#Mandrill_Invalid_Template">Mandrill_Invalid_Template</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="70" class="l"><a class="l" href="#70"> 70: </a>
</span><span id="71" class="l"><a class="l" href="#71"> 71: </a><span class="php-comment">/**
</span></span><span id="72" class="l"><a class="l" href="#72"> 72: </a><span class="php-comment"> * The requested webhook does not exist
</span></span><span id="73" class="l"><a class="l" href="#73"> 73: </a><span class="php-comment"> */</span>
</span><span id="74" class="l"><a class="l" href="#74"> 74: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Webhook" href="#Mandrill_Unknown_Webhook">Mandrill_Unknown_Webhook</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="75" class="l"><a class="l" href="#75"> 75: </a>
</span><span id="76" class="l"><a class="l" href="#76"> 76: </a><span class="php-comment">/**
</span></span><span id="77" class="l"><a class="l" href="#77"> 77: </a><span class="php-comment"> * The requested inbound domain does not exist
</span></span><span id="78" class="l"><a class="l" href="#78"> 78: </a><span class="php-comment"> */</span>
</span><span id="79" class="l"><a class="l" href="#79"> 79: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_InboundDomain" href="#Mandrill_Unknown_InboundDomain">Mandrill_Unknown_InboundDomain</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="80" class="l"><a class="l" href="#80"> 80: </a>
</span><span id="81" class="l"><a class="l" href="#81"> 81: </a><span class="php-comment">/**
</span></span><span id="82" class="l"><a class="l" href="#82"> 82: </a><span class="php-comment"> * The provided inbound route does not exist.
</span></span><span id="83" class="l"><a class="l" href="#83"> 83: </a><span class="php-comment"> */</span>
</span><span id="84" class="l"><a class="l" href="#84"> 84: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_InboundRoute" href="#Mandrill_Unknown_InboundRoute">Mandrill_Unknown_InboundRoute</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="85" class="l"><a class="l" href="#85"> 85: </a>
</span><span id="86" class="l"><a class="l" href="#86"> 86: </a><span class="php-comment">/**
</span></span><span id="87" class="l"><a class="l" href="#87"> 87: </a><span class="php-comment"> * The requested export job does not exist
</span></span><span id="88" class="l"><a class="l" href="#88"> 88: </a><span class="php-comment"> */</span>
</span><span id="89" class="l"><a class="l" href="#89"> 89: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Export" href="#Mandrill_Unknown_Export">Mandrill_Unknown_Export</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="90" class="l"><a class="l" href="#90"> 90: </a>
</span><span id="91" class="l"><a class="l" href="#91"> 91: </a><span class="php-comment">/**
</span></span><span id="92" class="l"><a class="l" href="#92"> 92: </a><span class="php-comment"> * A dedicated IP cannot be provisioned while another request is pending.
</span></span><span id="93" class="l"><a class="l" href="#93"> 93: </a><span class="php-comment"> */</span>
</span><span id="94" class="l"><a class="l" href="#94"> 94: </a><span class="php-keyword1">class</span> <a id="Mandrill_IP_ProvisionLimit" href="#Mandrill_IP_ProvisionLimit">Mandrill_IP_ProvisionLimit</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="95" class="l"><a class="l" href="#95"> 95: </a>
</span><span id="96" class="l"><a class="l" href="#96"> 96: </a><span class="php-comment">/**
</span></span><span id="97" class="l"><a class="l" href="#97"> 97: </a><span class="php-comment"> * The provided dedicated IP pool does not exist.
</span></span><span id="98" class="l"><a class="l" href="#98"> 98: </a><span class="php-comment"> */</span>
</span><span id="99" class="l"><a class="l" href="#99"> 99: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_Pool" href="#Mandrill_Unknown_Pool">Mandrill_Unknown_Pool</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="100" class="l"><a class="l" href="#100">100: </a>
</span><span id="101" class="l"><a class="l" href="#101">101: </a><span class="php-comment">/**
</span></span><span id="102" class="l"><a class="l" href="#102">102: </a><span class="php-comment"> * The user hasn't started sending yet.
</span></span><span id="103" class="l"><a class="l" href="#103">103: </a><span class="php-comment"> */</span>
</span><span id="104" class="l"><a class="l" href="#104">104: </a><span class="php-keyword1">class</span> <a id="Mandrill_NoSendingHistory" href="#Mandrill_NoSendingHistory">Mandrill_NoSendingHistory</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="105" class="l"><a class="l" href="#105">105: </a>
</span><span id="106" class="l"><a class="l" href="#106">106: </a><span class="php-comment">/**
</span></span><span id="107" class="l"><a class="l" href="#107">107: </a><span class="php-comment"> * The user's reputation is too low to continue.
</span></span><span id="108" class="l"><a class="l" href="#108">108: </a><span class="php-comment"> */</span>
</span><span id="109" class="l"><a class="l" href="#109">109: </a><span class="php-keyword1">class</span> <a id="Mandrill_PoorReputation" href="#Mandrill_PoorReputation">Mandrill_PoorReputation</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="110" class="l"><a class="l" href="#110">110: </a>
</span><span id="111" class="l"><a class="l" href="#111">111: </a><span class="php-comment">/**
</span></span><span id="112" class="l"><a class="l" href="#112">112: </a><span class="php-comment"> * The provided dedicated IP does not exist.
</span></span><span id="113" class="l"><a class="l" href="#113">113: </a><span class="php-comment"> */</span>
</span><span id="114" class="l"><a class="l" href="#114">114: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_IP" href="#Mandrill_Unknown_IP">Mandrill_Unknown_IP</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="115" class="l"><a class="l" href="#115">115: </a>
</span><span id="116" class="l"><a class="l" href="#116">116: </a><span class="php-comment">/**
</span></span><span id="117" class="l"><a class="l" href="#117">117: </a><span class="php-comment"> * You cannot remove the last IP from your default IP pool.
</span></span><span id="118" class="l"><a class="l" href="#118">118: </a><span class="php-comment"> */</span>
</span><span id="119" class="l"><a class="l" href="#119">119: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_EmptyDefaultPool" href="#Mandrill_Invalid_EmptyDefaultPool">Mandrill_Invalid_EmptyDefaultPool</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="120" class="l"><a class="l" href="#120">120: </a>
</span><span id="121" class="l"><a class="l" href="#121">121: </a><span class="php-comment">/**
</span></span><span id="122" class="l"><a class="l" href="#122">122: </a><span class="php-comment"> * The default pool cannot be deleted.
</span></span><span id="123" class="l"><a class="l" href="#123">123: </a><span class="php-comment"> */</span>
</span><span id="124" class="l"><a class="l" href="#124">124: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_DeleteDefaultPool" href="#Mandrill_Invalid_DeleteDefaultPool">Mandrill_Invalid_DeleteDefaultPool</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="125" class="l"><a class="l" href="#125">125: </a>
</span><span id="126" class="l"><a class="l" href="#126">126: </a><span class="php-comment">/**
</span></span><span id="127" class="l"><a class="l" href="#127">127: </a><span class="php-comment"> * Non-empty pools cannot be deleted.
</span></span><span id="128" class="l"><a class="l" href="#128">128: </a><span class="php-comment"> */</span>
</span><span id="129" class="l"><a class="l" href="#129">129: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_DeleteNonEmptyPool" href="#Mandrill_Invalid_DeleteNonEmptyPool">Mandrill_Invalid_DeleteNonEmptyPool</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="130" class="l"><a class="l" href="#130">130: </a>
</span><span id="131" class="l"><a class="l" href="#131">131: </a><span class="php-comment">/**
</span></span><span id="132" class="l"><a class="l" href="#132">132: </a><span class="php-comment"> * The domain name is not configured for use as the dedicated IP's custom reverse DNS.
</span></span><span id="133" class="l"><a class="l" href="#133">133: </a><span class="php-comment"> */</span>
</span><span id="134" class="l"><a class="l" href="#134">134: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_CustomDNS" href="#Mandrill_Invalid_CustomDNS">Mandrill_Invalid_CustomDNS</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="135" class="l"><a class="l" href="#135">135: </a>
</span><span id="136" class="l"><a class="l" href="#136">136: </a><span class="php-comment">/**
</span></span><span id="137" class="l"><a class="l" href="#137">137: </a><span class="php-comment"> * A custom DNS change for this dedicated IP is currently pending.
</span></span><span id="138" class="l"><a class="l" href="#138">138: </a><span class="php-comment"> */</span>
</span><span id="139" class="l"><a class="l" href="#139">139: </a><span class="php-keyword1">class</span> <a id="Mandrill_Invalid_CustomDNSPending" href="#Mandrill_Invalid_CustomDNSPending">Mandrill_Invalid_CustomDNSPending</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="140" class="l"><a class="l" href="#140">140: </a>
</span><span id="141" class="l"><a class="l" href="#141">141: </a><span class="php-comment">/**
</span></span><span id="142" class="l"><a class="l" href="#142">142: </a><span class="php-comment"> * Custom metadata field limit reached.
</span></span><span id="143" class="l"><a class="l" href="#143">143: </a><span class="php-comment"> */</span>
</span><span id="144" class="l"><a class="l" href="#144">144: </a><span class="php-keyword1">class</span> <a id="Mandrill_Metadata_FieldLimit" href="#Mandrill_Metadata_FieldLimit">Mandrill_Metadata_FieldLimit</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="145" class="l"><a class="l" href="#145">145: </a>
</span><span id="146" class="l"><a class="l" href="#146">146: </a><span class="php-comment">/**
</span></span><span id="147" class="l"><a class="l" href="#147">147: </a><span class="php-comment"> * The provided metadata field name does not exist.
</span></span><span id="148" class="l"><a class="l" href="#148">148: </a><span class="php-comment"> */</span>
</span><span id="149" class="l"><a class="l" href="#149">149: </a><span class="php-keyword1">class</span> <a id="Mandrill_Unknown_MetadataField" href="#Mandrill_Unknown_MetadataField">Mandrill_Unknown_MetadataField</a> <span class="php-keyword1">extends</span> Mandrill_Error {}
</span><span id="150" class="l"><a class="l" href="#150">150: </a>
</span><span id="151" class="l"><a class="l" href="#151">151: </a>
</span><span id="152" class="l"><a class="l" href="#152">152: </a></span></code></pre>
<div id="footer">
API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a>
</div>
</div>
</div>
</body>
</html>
| usmanasif/Taiche | wp-content/themes/alamindit/mailchimp-mandrill-api-php-e1eda7352f24/docs/source-class-Mandrill_Unknown_Url.html | HTML | gpl-2.0 | 26,565 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8">
<TITLE>NIST DOM HTML Test - FORM</TITLE>
<script type='text/javascript' src='selfhtml.js'></script><script charset='UTF-8' type='text/javascript' src='HTMLFormElement04.js'></script><script type='text/javascript'>function loadComplete() { startTest(); }</script></HEAD>
<BODY onload="loadComplete()">
<FORM ID="form1" ACCEPT-CHARSET="US-ASCII" ACTION="./files/getData.pl" ENCTYPE="application/x-www-form-urlencoded" METHOD="post">
<P>
<TEXTAREA NAME="text1" COLS="20" ROWS="7"></TEXTAREA>
<INPUT TYPE="submit" NAME="submit1" VALUE="Submit" />
<INPUT TYPE="reset" NAME="submit2" VALUE="Reset" />
</P>
</FORM>
</BODY>
</HTML>
| danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/LayoutTests/dom/html/level2/html/HTMLFormElement04.html | HTML | gpl-3.0 | 758 |
<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Automatically generated strings for Moodle installer
*
* Do not edit this file manually! It contains just a subset of strings
* needed during the very first steps of installation. This file was
* generated automatically by export-installer.php (which is part of AMOS
* {@link http://docs.moodle.org/dev/Languages/AMOS}) using the
* list of strings defined in /install/stringnames.txt.
*
* @package installer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['cannotcreatedboninstall'] = '<p>Impossible de crear la basa de donadas.</p>
<p>La basa de donadas indicada existís pas e l\'utilizaire especificat a pas las autorizacions que permeton de crear una basa de donadas.</p>.
<p>L\'administrator del site deu repassar la configuracion de la basa de donadas.</p>';
$string['cannotcreatelangdir'] = 'Creacion del dorsièr lang impossible';
$string['cannotcreatetempdir'] = 'Creacion del dorsièr temp impossibla';
$string['cannotdownloadcomponents'] = 'Telecargament dels components impossible';
$string['cannotdownloadzipfile'] = 'Telecargament del fichièr ZIP impossible';
$string['cannotfindcomponent'] = 'Component introbable';
$string['cannotsavemd5file'] = 'Enregistrament del fichièr md5 impossible';
$string['cannotsavezipfile'] = 'Enregistrament del fichièr ZIP impossible';
$string['cannotunzipfile'] = 'Descompression del fichièr ZIP impossibla';
$string['componentisuptodate'] = 'Lo component es a jorn';
$string['dmlexceptiononinstall'] = '<p>Una error de basa de donadas s\'es produita [{$a->errorcode}].<br />{$a->debuginfo}</p>';
$string['downloadedfilecheckfailed'] = 'La verificacion del fichièr telecargat a fracassat';
$string['invalidmd5'] = 'Lo còdi de contraròtle md5 es pas valid';
$string['missingrequiredfield'] = 'Un camp obligatòri es pas completat';
$string['remotedownloaderror'] = '<p>Lo telecargament del component sus vòstre servidor a fracassat. Verificatz los reglatges de proxy. L\'extension cURL de PHP es bravament recomandada.</p>
<p>Vos cal telecargar manualament lo fichièr <a href="{$a->url}">{$a->url}</a>, lo copiar sus vòstre servidor a l\'emplaçament « {$a->dest} » e lo descompressar a aqueste endreit.</p>';
$string['wrongdestpath'] = 'Camin de destinacion incorrècte';
$string['wrongsourcebase'] = 'Adreça URL de basa de la font incorrècta';
$string['wrongzipfilename'] = 'Nom de fichièr ZIP incorrècte';
| michael-milette/moodle | install/lang/oc_lnc/error.php | PHP | gpl-3.0 | 3,157 |
# We intentionally do not use the `RSpec::Support.require...` methods
# here so that this file can be loaded individually, as documented
# below.
require 'rspec/mocks/argument_matchers'
require 'rspec/support/fuzzy_matcher'
module RSpec
module Mocks
# Wrapper for matching arguments against a list of expected values. Used by
# the `with` method on a `MessageExpectation`:
#
# expect(object).to receive(:message).with(:a, 'b', 3)
# object.message(:a, 'b', 3)
#
# Values passed to `with` can be literal values or argument matchers that
# match against the real objects .e.g.
#
# expect(object).to receive(:message).with(hash_including(:a => 'b'))
#
# Can also be used directly to match the contents of any `Array`. This
# enables 3rd party mocking libs to take advantage of rspec's argument
# matching without using the rest of rspec-mocks.
#
# require 'rspec/mocks/argument_list_matcher'
# include RSpec::Mocks::ArgumentMatchers
#
# arg_list_matcher = RSpec::Mocks::ArgumentListMatcher.new(123, hash_including(:a => 'b'))
# arg_list_matcher.args_match?(123, :a => 'b')
#
# This class is immutable.
#
# @see ArgumentMatchers
class ArgumentListMatcher
# @private
attr_reader :expected_args
# @api public
# @param [Array] expected_args a list of expected literals and/or argument matchers
#
# Initializes an `ArgumentListMatcher` with a collection of literal
# values and/or argument matchers.
#
# @see ArgumentMatchers
# @see #args_match?
def initialize(*expected_args)
@expected_args = expected_args
ensure_expected_args_valid!
end
# @api public
# @param [Array] args
#
# Matches each element in the `expected_args` against the element in the same
# position of the arguments passed to `new`.
#
# @see #initialize
def args_match?(*args)
Support::FuzzyMatcher.values_match?(resolve_expected_args_based_on(args), args)
end
# @private
# Resolves abstract arg placeholders like `no_args` and `any_args` into
# a more concrete arg list based on the provided `actual_args`.
def resolve_expected_args_based_on(actual_args)
return [] if [ArgumentMatchers::NoArgsMatcher::INSTANCE] == expected_args
any_args_index = expected_args.index { |a| ArgumentMatchers::AnyArgsMatcher::INSTANCE == a }
return expected_args unless any_args_index
replace_any_args_with_splat_of_anything(any_args_index, actual_args.count)
end
private
def replace_any_args_with_splat_of_anything(before_count, actual_args_count)
any_args_count = actual_args_count - expected_args.count + 1
after_count = expected_args.count - before_count - 1
any_args = 1.upto(any_args_count).map { ArgumentMatchers::AnyArgMatcher::INSTANCE }
expected_args.first(before_count) + any_args + expected_args.last(after_count)
end
def ensure_expected_args_valid!
if expected_args.count { |a| ArgumentMatchers::AnyArgsMatcher::INSTANCE == a } > 1
raise ArgumentError, "`any_args` can only be passed to " \
"`with` once but you have passed it multiple times."
elsif expected_args.count > 1 && expected_args.any? { |a| ArgumentMatchers::NoArgsMatcher::INSTANCE == a }
raise ArgumentError, "`no_args` can only be passed as a " \
"singleton argument to `with` (i.e. `with(no_args)`), " \
"but you have passed additional arguments."
end
end
# Value that will match all argument lists.
#
# @private
MATCH_ALL = new(ArgumentMatchers::AnyArgsMatcher::INSTANCE)
end
end
end
| BibNumUMontreal/DMPonline_v4 | vendor/ruby/2.1.0/gems/rspec-mocks-3.5.0/lib/rspec/mocks/argument_list_matcher.rb | Ruby | agpl-3.0 | 3,852 |
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* These math functions are taken from newlib-nano-2, the newlib/libm/math
* directory, available from https://github.com/32bitmicro/newlib-nano-2.
*
* Appropriate copyright headers are reproduced below.
*/
/* sf_ldexp.c -- float version of s_ldexp.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected].
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "fdlibm.h"
//#include <errno.h>
#ifdef __STDC__
float ldexpf(float value, int exp)
#else
float ldexpf(value, exp)
float value; int exp;
#endif
{
if(!finitef(value)||value==(float)0.0) return value;
value = scalbnf(value,exp);
//if(!finitef(value)||value==(float)0.0) errno = ERANGE;
return value;
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double ldexp(double value, int exp)
#else
double ldexp(value, exp)
double value; int exp;
#endif
{
return (double) ldexpf((float) value, exp);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| r-lyeh/scriptorium | python/micropython/lib/libm/sf_ldexp.c | C | unlicense | 1,349 |
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M160 64v257.6c-8.2-2.7-17.2-4.1-26.6-4.1-38.3 0-69.4 27.1-69.4 65.4 0 38.3 31.1 65.1 69.4 65.1 38.3 0 69.6-28.2 69.6-69.1V200h202v121.6c-8.2-2.7-17.2-4.1-26.6-4.1-38.3 0-69.4 27.1-69.4 65.4 0 38.3 31.1 65.1 69.4 65.1 38.3 0 69.6-28.2 69.6-69.1V64H160zm245 96H203v-53h202v53z"/></svg>','md-musical-notes'); | matteobortolazzo/matteobortolazzo.github.io | build/app/svg/md-musical-notes.js | JavaScript | mit | 389 |
<?php
/**
* Admin View: Page - Reports
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<div class="wrap woocommerce">
<nav class="nav-tab-wrapper woo-nav-tab-wrapper">
<?php
foreach ( $reports as $key => $report_group ) {
echo '<a href="' . admin_url( 'admin.php?page=wc-reports&tab=' . urlencode( $key ) ) . '" class="nav-tab ';
if ( $current_tab == $key ) {
echo 'nav-tab-active';
}
echo '">' . esc_html( $report_group[ 'title' ] ) . '</a>';
}
do_action( 'wc_reports_tabs' );
?>
</nav>
<?php if ( sizeof( $reports[ $current_tab ]['reports'] ) > 1 ) {
?>
<ul class="subsubsub">
<li><?php
$links = array();
foreach ( $reports[ $current_tab ]['reports'] as $key => $report ) {
$link = '<a href="admin.php?page=wc-reports&tab=' . urlencode( $current_tab ) . '&report=' . urlencode( $key ) . '" class="';
if ( $key == $current_report ) {
$link .= 'current';
}
$link .= '">' . $report['title'] . '</a>';
$links[] = $link;
}
echo implode( ' | </li><li>', $links );
?></li>
</ul>
<br class="clear" />
<?php
}
if ( isset( $reports[ $current_tab ][ 'reports' ][ $current_report ] ) ) {
$report = $reports[ $current_tab ][ 'reports' ][ $current_report ];
if ( ! isset( $report['hide_title'] ) || $report['hide_title'] != true ) {
echo '<h1>' . esc_html( $report['title'] ) . '</h1>';
} else {
echo '<h1 class="screen-reader-text">' . esc_html( $report['title'] ) . '</h1>';
}
if ( $report['description'] ) {
echo '<p>' . $report['description'] . '</p>';
}
if ( $report['callback'] && ( is_callable( $report['callback'] ) ) ) {
call_user_func( $report['callback'], $current_report );
}
}
?>
</div>
| befair/soulShape | wp/soulshape.earth/wp-content/plugins/woocommerce/includes/admin/views/html-admin-page-reports.php | PHP | agpl-3.0 | 1,742 |
/**
* jQuery Galleriffic plugin
*
* Copyright (c) 2008 Trent Foley (http://trentacular.com)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Much thanks to primary contributer Ponticlaro (http://www.ponticlaro.com)
*/
;(function($) {
// Globally keep track of all images by their unique hash. Each item is an image data object.
var allImages = {};
var imageCounter = 0;
// Galleriffic static class
$.galleriffic = {
version: '2.0.1',
// Strips invalid characters and any leading # characters
normalizeHash: function(hash) {
return hash.replace(/^.*#/, '').replace(/\?.*$/, '');
},
getImage: function(hash) {
if (!hash)
return undefined;
hash = $.galleriffic.normalizeHash(hash);
return allImages[hash];
},
// Global function that looks up an image by its hash and displays the image.
// Returns false when an image is not found for the specified hash.
// @param {String} hash This is the unique hash value assigned to an image.
gotoImage: function(hash) {
var imageData = $.galleriffic.getImage(hash);
if (!imageData)
return false;
var gallery = imageData.gallery;
gallery.gotoImage(imageData);
return true;
},
// Removes an image from its respective gallery by its hash.
// Returns false when an image is not found for the specified hash or the
// specified owner gallery does match the located images gallery.
// @param {String} hash This is the unique hash value assigned to an image.
// @param {Object} ownerGallery (Optional) When supplied, the located images
// gallery is verified to be the same as the specified owning gallery before
// performing the remove operation.
removeImageByHash: function(hash, ownerGallery) {
var imageData = $.galleriffic.getImage(hash);
if (!imageData)
return false;
var gallery = imageData.gallery;
if (ownerGallery && ownerGallery != gallery)
return false;
return gallery.removeImageByIndex(imageData.index);
}
};
var defaults = {
delay: 3000,
numThumbs: 20,
preloadAhead: 40, // Set to -1 to preload all images
enableTopPager: false,
enableBottomPager: true,
maxPagesToShow: 7,
imageContainerSel: '',
captionContainerSel: '',
controlsContainerSel: '',
loadingContainerSel: '',
renderSSControls: true,
renderNavControls: true,
playLinkText: 'Play',
pauseLinkText: 'Pause',
prevLinkText: 'Previous',
nextLinkText: 'Next',
nextPageLinkText: 'Next ›',
prevPageLinkText: '‹ Prev',
enableHistory: false,
enableKeyboardNavigation: true,
autoStart: false,
syncTransitions: false,
defaultTransitionDuration: 1000,
onSlideChange: undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
onTransitionOut: undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... }
onTransitionIn: undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... }
onPageTransitionOut: undefined, // accepts a delegate like such: function(callback) { ... }
onPageTransitionIn: undefined, // accepts a delegate like such: function() { ... }
onImageAdded: undefined, // accepts a delegate like such: function(imageData, $li) { ... }
onImageRemoved: undefined // accepts a delegate like such: function(imageData, $li) { ... }
};
// Primary Galleriffic initialization function that should be called on the thumbnail container.
$.fn.galleriffic = function(settings) {
// Extend Gallery Object
$.extend(this, {
// Returns the version of the script
version: $.galleriffic.version,
// Current state of the slideshow
isSlideshowRunning: false,
slideshowTimeout: undefined,
// This function is attached to the click event of generated hyperlinks within the gallery
clickHandler: function(e, link) {
this.pause();
if (!this.enableHistory) {
// The href attribute holds the unique hash for an image
var hash = $.galleriffic.normalizeHash($(link).attr('href'));
$.galleriffic.gotoImage(hash);
e.preventDefault();
}
},
// Appends an image to the end of the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html.
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
appendImage: function(listItem) {
this.addImage(listItem, false, false);
return this;
},
// Inserts an image into the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html.
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
// @param {Integer} position The index within the gallery where the item shouold be added.
insertImage: function(listItem, position) {
this.addImage(listItem, false, true, position);
return this;
},
// Adds an image to the gallery and optionally inserts/appends it to the DOM (thumbExists)
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
// @param {Boolean} thumbExists Specifies whether the thumbnail already exists in the DOM or if it needs to be added.
// @param {Boolean} insert Specifies whether the the image is appended to the end or inserted into the gallery.
// @param {Integer} position The index within the gallery where the item shouold be added.
addImage: function(listItem, thumbExists, insert, position) {
var $li = ( typeof listItem === "string" ) ? $(listItem) : listItem;
var $aThumb = $li.find('a.thumb');
var slideUrl = $aThumb.attr('href');
var title = $aThumb.attr('title');
var $caption = $li.find('.caption').remove();
var hash = $aThumb.attr('name');
// Increment the image counter
imageCounter++;
// Autogenerate a hash value if none is present or if it is a duplicate
if (!hash || allImages[''+hash]) {
hash = imageCounter;
}
// Set position to end when not specified
if (!insert)
position = this.data.length;
var imageData = {
title:title,
slideUrl:slideUrl,
caption:$caption,
hash:hash,
gallery:this,
index:position
};
// Add the imageData to this gallery's array of images
if (insert) {
this.data.splice(position, 0, imageData);
// Reset index value on all imageData objects
this.updateIndices(position);
}
else {
this.data.push(imageData);
}
var gallery = this;
// Add the element to the DOM
if (!thumbExists) {
// Update thumbs passing in addition post transition out handler
this.updateThumbs(function() {
var $thumbsUl = gallery.find('ul.thumbs');
if (insert)
$thumbsUl.children(':eq('+position+')').before($li);
else
$thumbsUl.append($li);
if (gallery.onImageAdded)
gallery.onImageAdded(imageData, $li);
});
}
// Register the image globally
allImages[''+hash] = imageData;
// Setup attributes and click handler
$aThumb.attr('rel', 'history')
.attr('href', '#'+hash)
.removeAttr('name')
.click(function(e) {
gallery.clickHandler(e, this);
});
return this;
},
// Removes an image from the gallery based on its index.
// Returns false when the index is out of range.
removeImageByIndex: function(index) {
if (index < 0 || index >= this.data.length)
return false;
var imageData = this.data[index];
if (!imageData)
return false;
this.removeImage(imageData);
return true;
},
// Convenience method that simply calls the global removeImageByHash method.
removeImageByHash: function(hash) {
return $.galleriffic.removeImageByHash(hash, this);
},
// Removes an image from the gallery.
removeImage: function(imageData) {
var index = imageData.index;
// Remove the image from the gallery data array
this.data.splice(index, 1);
// Remove the global registration
delete allImages[''+imageData.hash];
// Remove the image's list item from the DOM
this.updateThumbs(function() {
var $li = gallery.find('ul.thumbs')
.children(':eq('+index+')')
.remove();
if (gallery.onImageRemoved)
gallery.onImageRemoved(imageData, $li);
});
// Update each image objects index value
this.updateIndices(index);
return this;
},
// Updates the index values of the each of the images in the gallery after the specified index
updateIndices: function(startIndex) {
for (i = startIndex; i < this.data.length; i++) {
this.data[i].index = i;
}
return this;
},
// Scraped the thumbnail container for thumbs and adds each to the gallery
initializeThumbs: function() {
this.data = [];
var gallery = this;
this.find('ul.thumbs > li').each(function(i) {
gallery.addImage($(this), true, false);
});
return this;
},
isPreloadComplete: false,
// Initalizes the image preloader
preloadInit: function() {
if (this.preloadAhead == 0) return this;
this.preloadStartIndex = this.currentImage.index;
var nextIndex = this.getNextIndex(this.preloadStartIndex);
return this.preloadRecursive(this.preloadStartIndex, nextIndex);
},
// Changes the location in the gallery the preloader should work
// @param {Integer} index The index of the image where the preloader should restart at.
preloadRelocate: function(index) {
// By changing this startIndex, the current preload script will restart
this.preloadStartIndex = index;
return this;
},
// Recursive function that performs the image preloading
// @param {Integer} startIndex The index of the first image the current preloader started on.
// @param {Integer} currentIndex The index of the current image to preload.
preloadRecursive: function(startIndex, currentIndex) {
// Check if startIndex has been relocated
if (startIndex != this.preloadStartIndex) {
var nextIndex = this.getNextIndex(this.preloadStartIndex);
return this.preloadRecursive(this.preloadStartIndex, nextIndex);
}
var gallery = this;
// Now check for preloadAhead count
var preloadCount = currentIndex - startIndex;
if (preloadCount < 0)
preloadCount = this.data.length-1-startIndex+currentIndex;
if (this.preloadAhead >= 0 && preloadCount > this.preloadAhead) {
// Do this in order to keep checking for relocated start index
setTimeout(function() { gallery.preloadRecursive(startIndex, currentIndex); }, 500);
return this;
}
var imageData = this.data[currentIndex];
if (!imageData)
return this;
// If already loaded, continue
if (imageData.image)
return this.preloadNext(startIndex, currentIndex);
// Preload the image
var image = new Image();
image.onload = function() {
imageData.image = this;
gallery.preloadNext(startIndex, currentIndex);
};
image.alt = imageData.title;
image.src = imageData.slideUrl;
return this;
},
// Called by preloadRecursive in order to preload the next image after the previous has loaded.
// @param {Integer} startIndex The index of the first image the current preloader started on.
// @param {Integer} currentIndex The index of the current image to preload.
preloadNext: function(startIndex, currentIndex) {
var nextIndex = this.getNextIndex(currentIndex);
if (nextIndex == startIndex) {
this.isPreloadComplete = true;
} else {
// Use setTimeout to free up thread
var gallery = this;
setTimeout(function() { gallery.preloadRecursive(startIndex, nextIndex); }, 100);
}
return this;
},
// Safe way to get the next image index relative to the current image.
// If the current image is the last, returns 0
getNextIndex: function(index) {
var nextIndex = index+1;
if (nextIndex >= this.data.length)
nextIndex = 0;
return nextIndex;
},
// Safe way to get the previous image index relative to the current image.
// If the current image is the first, return the index of the last image in the gallery.
getPrevIndex: function(index) {
var prevIndex = index-1;
if (prevIndex < 0)
prevIndex = this.data.length-1;
return prevIndex;
},
// Pauses the slideshow
pause: function() {
this.isSlideshowRunning = false;
if (this.slideshowTimeout) {
clearTimeout(this.slideshowTimeout);
this.slideshowTimeout = undefined;
}
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.ss-controls a').removeClass().addClass('play')
.attr('title', this.playLinkText)
.attr('href', '#play')
.html(this.playLinkText);
}
return this;
},
// Plays the slideshow
play: function() {
this.isSlideshowRunning = true;
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.ss-controls a').removeClass().addClass('pause')
.attr('title', this.pauseLinkText)
.attr('href', '#pause')
.html(this.pauseLinkText);
}
if (!this.slideshowTimeout) {
var gallery = this;
this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay);
}
return this;
},
// Toggles the state of the slideshow (playing/paused)
toggleSlideshow: function() {
if (this.isSlideshowRunning)
this.pause();
else
this.play();
return this;
},
// Advances the slideshow to the next image and delegates navigation to the
// history plugin when history is enabled
// enableHistory is true
ssAdvance: function() {
if (this.isSlideshowRunning)
this.next(true);
return this;
},
// Advances the gallery to the next image.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
next: function(dontPause, bypassHistory) {
this.gotoIndex(this.getNextIndex(this.currentImage.index), dontPause, bypassHistory);
return this;
},
// Navigates to the previous image in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
previous: function(dontPause, bypassHistory) {
this.gotoIndex(this.getPrevIndex(this.currentImage.index), dontPause, bypassHistory);
return this;
},
// Navigates to the next page in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
nextPage: function(dontPause, bypassHistory) {
var page = this.getCurrentPage();
var lastPage = this.getNumPages() - 1;
if (page < lastPage) {
var startIndex = page * this.numThumbs;
var nextPage = startIndex + this.numThumbs;
this.gotoIndex(nextPage, dontPause, bypassHistory);
}
return this;
},
// Navigates to the previous page in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
previousPage: function(dontPause, bypassHistory) {
var page = this.getCurrentPage();
if (page > 0) {
var startIndex = page * this.numThumbs;
var prevPage = startIndex - this.numThumbs;
this.gotoIndex(prevPage, dontPause, bypassHistory);
}
return this;
},
// Navigates to the image at the specified index in the gallery
// @param {Integer} index The index of the image in the gallery to display.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
gotoIndex: function(index, dontPause, bypassHistory) {
if (!dontPause)
this.pause();
if (index < 0) index = 0;
else if (index >= this.data.length) index = this.data.length-1;
var imageData = this.data[index];
if (!bypassHistory && this.enableHistory)
$.historyLoad(String(imageData.hash)); // At the moment, historyLoad only accepts string arguments
else
this.gotoImage(imageData);
return this;
},
// This function is garaunteed to be called anytime a gallery slide changes.
// @param {Object} imageData An object holding the image metadata of the image to navigate to.
gotoImage: function(imageData) {
var index = imageData.index;
if (this.onSlideChange)
this.onSlideChange(this.currentImage.index, index);
this.currentImage = imageData;
this.preloadRelocate(index);
this.refresh();
return this;
},
// Returns the default transition duration value. The value is halved when not
// performing a synchronized transition.
// @param {Boolean} isSync Specifies whether the transitions are synchronized.
getDefaultTransitionDuration: function(isSync) {
if (isSync)
return this.defaultTransitionDuration;
return this.defaultTransitionDuration / 2;
},
// Rebuilds the slideshow image and controls and performs transitions
refresh: function() {
var imageData = this.currentImage;
if (!imageData)
return this;
var index = imageData.index;
// Update Controls
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.nav-controls a.prev').attr('href', '#'+this.data[this.getPrevIndex(index)].hash).end()
.find('div.nav-controls a.next').attr('href', '#'+this.data[this.getNextIndex(index)].hash);
}
var previousSlide = this.$imageContainer.find('span.current').addClass('previous').removeClass('current');
var previousCaption = 0;
if (this.$captionContainer) {
previousCaption = this.$captionContainer.find('span.current').addClass('previous').removeClass('current');
}
// Perform transitions simultaneously if syncTransitions is true and the next image is already preloaded
var isSync = this.syncTransitions && imageData.image;
// Flag we are transitioning
var isTransitioning = true;
var gallery = this;
var transitionOutCallback = function() {
// Flag that the transition has completed
isTransitioning = false;
// Remove the old slide
previousSlide.remove();
// Remove old caption
if (previousCaption)
previousCaption.remove();
if (!isSync) {
if (imageData.image && imageData.hash == gallery.data[gallery.currentImage.index].hash) {
gallery.buildImage(imageData, isSync);
} else {
// Show loading container
if (gallery.$loadingContainer) {
gallery.$loadingContainer.show();
}
}
}
};
if (previousSlide.length == 0) {
// For the first slide, the previous slide will be empty, so we will call the callback immediately
transitionOutCallback();
} else {
if (this.onTransitionOut) {
this.onTransitionOut(previousSlide, previousCaption, isSync, transitionOutCallback);
} else {
previousSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0, transitionOutCallback);
if (previousCaption)
previousCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0);
}
}
// Go ahead and begin transitioning in of next image
if (isSync)
this.buildImage(imageData, isSync);
if (!imageData.image) {
var image = new Image();
// Wire up mainImage onload event
image.onload = function() {
imageData.image = this;
// Only build image if the out transition has completed and we are still on the same image hash
if (!isTransitioning && imageData.hash == gallery.data[gallery.currentImage.index].hash) {
gallery.buildImage(imageData, isSync);
}
};
// set alt and src
image.alt = imageData.title;
image.src = imageData.slideUrl;
}
// This causes the preloader (if still running) to relocate out from the currentIndex
this.relocatePreload = true;
return this.syncThumbs();
},
// Called by the refresh method after the previous image has been transitioned out or at the same time
// as the out transition when performing a synchronous transition.
// @param {Object} imageData An object holding the image metadata of the image to build.
// @param {Boolean} isSync Specifies whether the transitions are synchronized.
buildImage: function(imageData, isSync) {
var gallery = this;
var nextIndex = this.getNextIndex(imageData.index);
// Construct new hidden span for the image
var newSlide = this.$imageContainer
.append('<span class="image-wrapper current"><a class="advance-link" rel="history" href="#'+this.data[nextIndex].hash+'" title="'+imageData.title+'"> </a></span>')
.find('span.current').css('opacity', '0');
newSlide.find('a')
.append(imageData.image)
.click(function(e) {
gallery.clickHandler(e, this);
});
var newCaption = 0;
if (this.$captionContainer) {
// Construct new hidden caption for the image
newCaption = this.$captionContainer
.append('<span class="image-caption current"></span>')
.find('span.current').css('opacity', '0')
.append(imageData.caption);
}
// Hide the loading conatiner
if (this.$loadingContainer) {
this.$loadingContainer.hide();
}
// Transition in the new image
if (this.onTransitionIn) {
this.onTransitionIn(newSlide, newCaption, isSync);
} else {
newSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
if (newCaption)
newCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
}
if (this.isSlideshowRunning) {
if (this.slideshowTimeout)
clearTimeout(this.slideshowTimeout);
this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay);
}
return this;
},
// Returns the current page index that should be shown for the currentImage
getCurrentPage: function() {
return Math.floor(this.currentImage.index / this.numThumbs);
},
// Applies the selected class to the current image's corresponding thumbnail.
// Also checks if the current page has changed and updates the displayed page of thumbnails if necessary.
syncThumbs: function() {
var page = this.getCurrentPage();
if (page != this.displayedPage)
this.updateThumbs();
// Remove existing selected class and add selected class to new thumb
var $thumbs = this.find('ul.thumbs').children();
$thumbs.filter('.selected').removeClass('selected');
$thumbs.eq(this.currentImage.index).addClass('selected');
return this;
},
// Performs transitions on the thumbnails container and updates the set of
// thumbnails that are to be displayed and the navigation controls.
// @param {Delegate} postTransitionOutHandler An optional delegate that is called after
// the thumbnails container has transitioned out and before the thumbnails are rebuilt.
updateThumbs: function(postTransitionOutHandler) {
var gallery = this;
var transitionOutCallback = function() {
// Call the Post-transition Out Handler
if (postTransitionOutHandler)
postTransitionOutHandler();
gallery.rebuildThumbs();
// Transition In the thumbsContainer
if (gallery.onPageTransitionIn)
gallery.onPageTransitionIn();
else
gallery.show();
};
// Transition Out the thumbsContainer
if (this.onPageTransitionOut) {
this.onPageTransitionOut(transitionOutCallback);
} else {
this.hide();
transitionOutCallback();
}
return this;
},
// Updates the set of thumbnails that are to be displayed and the navigation controls.
rebuildThumbs: function() {
var needsPagination = this.data.length > this.numThumbs;
// Rebuild top pager
if (this.enableTopPager) {
var $topPager = this.find('div.top');
if ($topPager.length == 0)
$topPager = this.prepend('<div class="top pagination"></div>').find('div.top');
else
$topPager.empty();
if (needsPagination)
this.buildPager($topPager);
}
// Rebuild bottom pager
if (this.enableBottomPager) {
var $bottomPager = this.find('div.bottom');
if ($bottomPager.length == 0)
$bottomPager = this.append('<div class="bottom pagination"></div>').find('div.bottom');
else
$bottomPager.empty();
if (needsPagination)
this.buildPager($bottomPager);
}
var page = this.getCurrentPage();
var startIndex = page*this.numThumbs;
var stopIndex = startIndex+this.numThumbs-1;
if (stopIndex >= this.data.length)
stopIndex = this.data.length-1;
// Show/Hide thumbs
var $thumbsUl = this.find('ul.thumbs');
$thumbsUl.find('li').each(function(i) {
var $li = $(this);
if (i >= startIndex && i <= stopIndex) {
$li.show();
} else {
$li.hide();
}
});
this.displayedPage = page;
// Remove the noscript class from the thumbs container ul
$thumbsUl.removeClass('noscript');
return this;
},
// Returns the total number of pages required to display all the thumbnails.
getNumPages: function() {
return Math.ceil(this.data.length/this.numThumbs);
},
// Rebuilds the pager control in the specified matched element.
// @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt.
buildPager: function(pager) {
var gallery = this;
var numPages = this.getNumPages();
var page = this.getCurrentPage();
var startIndex = page * this.numThumbs;
var pagesRemaining = this.maxPagesToShow - 1;
var pageNum = page - Math.floor((this.maxPagesToShow - 1) / 2) + 1;
if (pageNum > 0) {
var remainingPageCount = numPages - pageNum;
if (remainingPageCount < pagesRemaining) {
pageNum = pageNum - (pagesRemaining - remainingPageCount);
}
}
if (pageNum < 0) {
pageNum = 0;
}
// Prev Page Link
if (page > 0) {
var prevPage = startIndex - this.numThumbs;
pager.append('<a rel="history" href="#'+this.data[prevPage].hash+'" title="'+this.prevPageLinkText+'">'+this.prevPageLinkText+'</a>');
}
// Create First Page link if needed
if (pageNum > 0) {
this.buildPageLink(pager, 0, numPages);
if (pageNum > 1)
pager.append('<span class="ellipsis">…</span>');
pagesRemaining--;
}
// Page Index Links
while (pagesRemaining > 0) {
this.buildPageLink(pager, pageNum, numPages);
pagesRemaining--;
pageNum++;
}
// Create Last Page link if needed
if (pageNum < numPages) {
var lastPageNum = numPages - 1;
if (pageNum < lastPageNum)
pager.append('<span class="ellipsis">…</span>');
this.buildPageLink(pager, lastPageNum, numPages);
}
// Next Page Link
var nextPage = startIndex + this.numThumbs;
if (nextPage < this.data.length) {
pager.append('<a rel="history" href="#'+this.data[nextPage].hash+'" title="'+this.nextPageLinkText+'">'+this.nextPageLinkText+'</a>');
}
pager.find('a').click(function(e) {
gallery.clickHandler(e, this);
});
return this;
},
// Builds a single page link within a pager. This function is called by buildPager
// @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt.
// @param {Integer} pageNum The page number of the page link to build.
// @param {Integer} numPages The total number of pages required to display all thumbnails.
buildPageLink: function(pager, pageNum, numPages) {
var pageLabel = pageNum + 1;
var currentPage = this.getCurrentPage();
if (pageNum == currentPage)
pager.append('<span class="current">'+pageLabel+'</span>');
else if (pageNum < numPages) {
var imageIndex = pageNum*this.numThumbs;
pager.append('<a rel="history" href="#'+this.data[imageIndex].hash+'" title="'+pageLabel+'">'+pageLabel+'</a>');
}
return this;
}
});
// Now initialize the gallery
$.extend(this, defaults, settings);
// Verify the history plugin is available
if (this.enableHistory && !$.historyInit)
this.enableHistory = false;
// Select containers
if (this.imageContainerSel) this.$imageContainer = $(this.imageContainerSel);
if (this.captionContainerSel) this.$captionContainer = $(this.captionContainerSel);
if (this.loadingContainerSel) this.$loadingContainer = $(this.loadingContainerSel);
// Initialize the thumbails
this.initializeThumbs();
if (this.maxPagesToShow < 3)
this.maxPagesToShow = 3;
this.displayedPage = -1;
this.currentImage = this.data[0];
var gallery = this;
// Hide the loadingContainer
if (this.$loadingContainer)
this.$loadingContainer.hide();
// Setup controls
if (this.controlsContainerSel) {
this.$controlsContainer = $(this.controlsContainerSel).empty();
if (this.renderSSControls) {
if (this.autoStart) {
this.$controlsContainer
.append('<div class="ss-controls"><a href="#pause" class="pause" title="'+this.pauseLinkText+'">'+this.pauseLinkText+'</a></div>');
} else {
this.$controlsContainer
.append('<div class="ss-controls"><a href="#play" class="play" title="'+this.playLinkText+'">'+this.playLinkText+'</a></div>');
}
this.$controlsContainer.find('div.ss-controls a')
.click(function(e) {
gallery.toggleSlideshow();
e.preventDefault();
return false;
});
}
if (this.renderNavControls) {
this.$controlsContainer
.append('<div class="nav-controls"><a class="prev" rel="history" title="'+this.prevLinkText+'">'+this.prevLinkText+'</a><a class="next" rel="history" title="'+this.nextLinkText+'">'+this.nextLinkText+'</a></div>')
.find('div.nav-controls a')
.click(function(e) {
gallery.clickHandler(e, this);
});
}
}
var initFirstImage = !this.enableHistory || !location.hash;
if (this.enableHistory && location.hash) {
var hash = $.galleriffic.normalizeHash(location.hash);
var imageData = allImages[hash];
if (!imageData)
initFirstImage = true;
}
// Setup gallery to show the first image
if (initFirstImage)
this.gotoIndex(0, false, true);
// Setup Keyboard Navigation
if (this.enableKeyboardNavigation) {
$(document).keydown(function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
switch(key) {
case 32: // space
gallery.next();
e.preventDefault();
break;
case 33: // Page Up
gallery.previousPage();
e.preventDefault();
break;
case 34: // Page Down
gallery.nextPage();
e.preventDefault();
break;
case 35: // End
gallery.gotoIndex(gallery.data.length-1);
e.preventDefault();
break;
case 36: // Home
gallery.gotoIndex(0);
e.preventDefault();
break;
case 37: // left arrow
gallery.previous();
e.preventDefault();
break;
case 39: // right arrow
gallery.next();
e.preventDefault();
break;
}
});
}
// Auto start the slideshow
if (this.autoStart)
this.play();
// Kickoff Image Preloader after 1 second
setTimeout(function() { gallery.preloadInit(); }, 1000);
return this;
};
})(jQuery);
| marcelijanowski/jaxa | wp-content/themes/Loveit-theme/js/jquery.galleriffic.js | JavaScript | gpl-2.0 | 32,119 |
Body Object
===========
The Body object gives you access to the textual body parts of an email.
API
---
* body.bodytext
A String containing the body text. Note that HTML parts will have tags in-tact.
* body.header
The header of this MIME part. See the `Header Object` for details of the API.
* body.children
Any child MIME parts. For example a multipart/alternative mail will have a
main body part with just the MIME preamble in (which is usually either empty,
or reads something like "This is a multipart MIME message"), and two
children, one text/plain and one text/html.
| dweekly/Haraka | docs/Body.md | Markdown | mit | 582 |
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Should=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var should = require('./should');
should
.use(require('./ext/assert'))
.use(require('./ext/chain'))
.use(require('./ext/bool'))
.use(require('./ext/number'))
.use(require('./ext/eql'))
.use(require('./ext/type'))
.use(require('./ext/string'))
.use(require('./ext/property'))
.use(require('./ext/error'))
.use(require('./ext/match'))
.use(require('./ext/browser/jquery'))
.use(require('./ext/deprecated'));
module.exports = should;
},{"./ext/assert":3,"./ext/bool":4,"./ext/browser/jquery":5,"./ext/chain":6,"./ext/deprecated":7,"./ext/eql":8,"./ext/error":9,"./ext/match":10,"./ext/number":11,"./ext/property":12,"./ext/string":13,"./ext/type":14,"./should":15}],2:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
// Taken from node's assert module, because it sucks
// and exposes next to nothing useful.
var util = require('./util');
module.exports = _deepEqual;
var pSlice = Array.prototype.slice;
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function objEquiv (a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (util.isArguments(a)) {
if (!util.isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try{
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
},{"./util":16}],3:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var util = require('../util')
, assert = require('assert')
, AssertionError = assert.AssertionError;
module.exports = function(should) {
var i = should.format;
/**
* Expose assert to should
*
* This allows you to do things like below
* without require()ing the assert module.
*
* should.equal(foo.bar, undefined);
*
*/
util.merge(should, assert);
/**
* Assert _obj_ exists, with optional message.
*
* @param {*} obj
* @param {String} [msg]
* @api public
*/
should.exist = should.exists = function(obj, msg) {
if(null == obj) {
throw new AssertionError({
message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist
});
}
};
/**
* Asserts _obj_ does not exist, with optional message.
*
* @param {*} obj
* @param {String} [msg]
* @api public
*/
should.not = {};
should.not.exist = should.not.exists = function(obj, msg) {
if(null != obj) {
throw new AssertionError({
message: msg || ('expected ' + i(obj) + ' to not exist'), stackStartFunction: should.not.exist
});
}
};
};
},{"../util":16,"assert":17}],4:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
Assertion.add('true', function() {
this.is.exactly(true)
}, true);
Assertion.add('false', function() {
this.is.exactly(false)
}, true);
Assertion.add('ok', function() {
this.params = { operator: 'to be truthy' };
this.assert(this.obj);
}, true);
};
},{}],5:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
/*!
* Portions copyright (c) 2010, 2011, 2012 Wojciech Zawistowski, Travis Jeffery
* From the jasmine-jquery project under the MIT License.
*/
var util = require('../../util');
module.exports = function(should, Assertion) {
var i = should.format;
var $ = this.jQuery || this.$;
/* Otherwise, node's util.inspect loops hangs */
if (typeof HTMLElement !== "undefined" && HTMLElement && !HTMLElement.prototype.inspect) {
HTMLElement.prototype.inspect = function () {
return this.outerHTML;
};
}
if (typeof jQuery !== "undefined" && jQuery && !jQuery.prototype.inspect) {
jQuery.fn.inspect = function () {
var elementList = this.toArray().map(function (e) {
return util.inspect(e);
}).join(", ");
if (this.selector) {
return "SELECTOR(" + this.selector + ") matching " + this.length + " elements" + (elementList.length ? ": " + elementList : "");
} else {
return elementList;
}
};
}
function jQueryAttributeTestHelper(method, singular, plural, nameOrHash, value) {
var keys = util.isObject(nameOrHash) ? Object.keys(nameOrHash) : [nameOrHash];
var allRelevantAttributes = keys.reduce(function (memo, key) {
var value = $(this.obj)[method](key);
if (typeof value !== 'undefined') {
memo[key] = value;
}
return memo;
}.bind(this), {});
if (arguments.length === 4 && util.isObject(nameOrHash)) {
this.params = { operator: 'to have ' + plural + ' ' + i(nameOrHash) };
allRelevantAttributes.should.have.properties(nameOrHash);
} else if (arguments.length === 4) {
this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) };
allRelevantAttributes.should.have.property(nameOrHash);
} else {
this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) + ' with value ' + i(value) };
allRelevantAttributes.should.have.property(nameOrHash, value);
}
}
var browserTagCaseIndependentHtml = function (html) {
return $('<div/>').append(html).html();
};
var addJqPredicateAssertion = function (predicate, nameOverride, operatorOverride) {
Assertion.add(nameOverride || predicate, function() {
this.params = { operator: 'to be ' + (operatorOverride || predicate) };
this.assert($(this.obj).is(':' + predicate));
}, true);
}
Assertion.add('className', function(className) {
this.params = { operator: 'to have class ' + className };
this.assert($(this.obj).hasClass(className));
});
Assertion.add('css', function(css) {
this.params = { operator: 'to have css ' + i(css) };
for (var prop in css) {
var value = css[prop];
if (value === 'auto' && $(this.obj).get(0).style[prop] === 'auto') {
continue;
}
$(this.obj).css(prop).should.eql(value);
}
});
addJqPredicateAssertion('visible');
addJqPredicateAssertion('hidden');
addJqPredicateAssertion('selected');
addJqPredicateAssertion('checked');
addJqPredicateAssertion('disabled');
addJqPredicateAssertion('empty', 'emptyJq');
addJqPredicateAssertion('focus', 'focused', 'focused');
Assertion.add('inDOM', function() {
this.params = { operator: 'to be in the DOM' };
this.assert($.contains(document.documentElement, $(this.obj)[0]));
}, true);
Assertion.add('exist', function() {
this.params = { operator: 'to exist' };
$(this.obj).should.not.have.length(0);
}, true);
Assertion.add('attr', function() {
var args = [
'attr',
'attribute',
'attributes'
].concat(Array.prototype.slice.call(arguments, 0));
jQueryAttributeTestHelper.apply(this, args);
});
Assertion.add('prop', function() {
var args = [
'prop',
'property',
'properties'
].concat(Array.prototype.slice.call(arguments, 0));
jQueryAttributeTestHelper.apply(this, args);
});
Assertion.add('elementId', function(id) {
this.params = { operator: 'to have ID ' + i(id) };
this.obj.should.have.attr('id', id);
});
Assertion.add('html', function(html) {
this.params = { operator: 'to have HTML ' + i(html) };
$(this.obj).html().should.eql(browserTagCaseIndependentHtml(html));
});
Assertion.add('containHtml', function(html) {
this.params = { operator: 'to contain HTML ' + i(html) };
$(this.obj).html().indexOf(browserTagCaseIndependentHtml(html)).should.be.above(-1);
});
Assertion.add('text', function(text) {
this.params = { operator: 'to have text ' + i(text) };
var trimmedText = $.trim($(this.obj).text());
if (util.isRegExp(text)) {
trimmedText.should.match(text);
} else {
trimmedText.should.eql(text);
}
});
Assertion.add('containText', function(text) {
this.params = { operator: 'to contain text ' + i(text) };
var trimmedText = $.trim($(this.obj).text());
if (util.isRegExp(text)) {
trimmedText.should.match(text);
} else {
trimmedText.indexOf(text).should.be.above(-1);
}
});
Assertion.add('value', function(val) {
this.params = { operator: 'to have value ' + i(val) };
$(this.obj).val().should.eql(val);
});
Assertion.add('data', function() {
var args = [
'data',
'data',
'data'
].concat(Array.prototype.slice.call(arguments, 0));
jQueryAttributeTestHelper.apply(this, args);
});
Assertion.add('containElement', function(target) {
this.params = { operator: 'to contain ' + $(target).inspect() };
$(this.obj).find(target).should.not.have.length(0);
});
Assertion.add('matchedBy', function(selector) {
this.params = { operator: 'to be matched by selector ' + selector };
$(this.obj).filter(selector).should.not.have.length(0);
});
Assertion.add('handle', function(event) {
this.params = { operator: 'to handle ' + event };
var events = $._data($(this.obj).get(0), "events");
if (!events || !event || typeof event !== "string") {
return this.assert(false);
}
var namespaces = event.split("."),
eventType = namespaces.shift(),
sortedNamespaces = namespaces.slice(0).sort(),
namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
if (events[eventType] && namespaces.length) {
for (var i = 0; i < events[eventType].length; i++) {
var namespace = events[eventType][i].namespace;
if (namespaceRegExp.test(namespace)) {
return;
}
}
} else {
events.should.have.property(eventType);
events[eventType].should.not.have.length(0);
return;
}
this.assert(false);
});
Assertion.add('handleWith', function(eventName, eventHandler) {
this.params = { operator: 'to handle ' + eventName + ' with ' + eventHandler };
var normalizedEventName = eventName.split('.')[0],
stack = $._data($(this.obj).get(0), "events")[normalizedEventName];
for (var i = 0; i < stack.length; i++) {
if (stack[i].handler == eventHandler) {
return;
}
}
this.assert(false);
});
};
},{"../../util":16}],6:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
function addLink(name) {
Object.defineProperty(Assertion.prototype, name, {
get: function() {
return this;
}
});
}
['an', 'of', 'a', 'and', 'be', 'have', 'with', 'is', 'which'].forEach(addLink);
};
},{}],7:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var util = require('../util'),
eql = require('../eql');
module.exports = function(should, Assertion) {
var i = should.format;
Assertion.add('include', function(obj, description) {
if(!Array.isArray(this.obj) && !util.isString(this.obj)) {
this.params = { operator: 'to include an object equal to ' + i(obj), message: description };
var cmp = {};
for(var key in obj) cmp[key] = this.obj[key];
this.assert(eql(cmp, obj));
} else {
this.params = { operator: 'to include ' + i(obj), message: description };
this.assert(~this.obj.indexOf(obj));
}
});
Assertion.add('includeEql', function(obj, description) {
this.params = { operator: 'to include an object equal to ' + i(obj), message: description };
this.assert(this.obj.some(function(item) {
return eql(obj, item);
}));
});
};
},{"../eql":2,"../util":16}],8:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var eql = require('../eql');
module.exports = function(should, Assertion) {
Assertion.add('eql', function(val, description) {
this.params = { operator: 'to equal', expected: val, showDiff: true, message: description };
this.assert(eql(val, this.obj));
});
Assertion.add('equal', function(val, description) {
this.params = { operator: 'to be', expected: val, showDiff: true, message: description };
this.assert(val === this.obj);
});
Assertion.alias('equal', 'exactly');
};
},{"../eql":2}],9:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
var i = should.format;
Assertion.add('throw', function(message) {
var fn = this.obj
, err = {}
, errorInfo = ''
, ok = true;
try {
fn();
ok = false;
} catch(e) {
err = e;
}
if(ok) {
if('string' == typeof message) {
ok = message == err.message;
} else if(message instanceof RegExp) {
ok = message.test(err.message);
} else if('function' == typeof message) {
ok = err instanceof message;
}
if(message && !ok) {
if('string' == typeof message) {
errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'";
} else if(message instanceof RegExp) {
errorInfo = " with a message matching " + message + ", but got '" + err.message + "'";
} else if('function' == typeof message) {
errorInfo = " of type " + message.name + ", but got " + err.constructor.name;
}
} else {
errorInfo = " (got " + i(err) + ")";
}
}
this.params = { operator: 'to throw exception' + errorInfo };
this.assert(ok);
});
Assertion.alias('throw', 'throwError');
};
},{}],10:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var util = require('../util'),
eql = require('../eql');
module.exports = function(should, Assertion) {
var i = should.format;
Assertion.add('match', function(other, description) {
this.params = { operator: 'to match ' + i(other), message: description };
if(!eql(this.obj, other)) {
if(util.isRegExp(other)) { // something - regex
if(util.isString(this.obj)) {
this.assert(other.exec(this.obj));
} else if(Array.isArray(this.obj)) {
this.obj.forEach(function(item) {
this.assert(other.exec(item));// should we try to convert to String and exec?
}, this);
} else if(util.isObject(this.obj)) {
var notMatchedProps = [], matchedProps = [];
util.forOwn(this.obj, function(value, name) {
if(other.exec(value)) matchedProps.push(i(name));
else notMatchedProps.push(i(name));
}, this);
if(notMatchedProps.length)
this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', ');
if(matchedProps.length)
this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', ');
this.assert(notMatchedProps.length == 0);
} // should we try to convert to String and exec?
} else if(util.isFunction(other)) {
var res;
try {
res = other(this.obj);
} catch(e) {
if(e instanceof should.AssertionError) {
this.params.operator += '\n\t' + e.message;
}
throw e;
}
if(res instanceof Assertion) {
this.params.operator += '\n\t' + res.getMessage();
}
//if we throw exception ok - it is used .should inside
if(util.isBoolean(res)) {
this.assert(res); // if it is just boolean function assert on it
}
} else if(util.isObject(other)) { // try to match properties (for Object and Array)
notMatchedProps = []; matchedProps = [];
util.forOwn(other, function(value, key) {
try {
this.obj[key].should.match(value);
matchedProps.push(key);
} catch(e) {
if(e instanceof should.AssertionError) {
notMatchedProps.push(key);
} else {
throw e;
}
}
}, this);
if(notMatchedProps.length)
this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', ');
if(matchedProps.length)
this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', ');
this.assert(notMatchedProps.length == 0);
} else {
this.assert(false);
}
}
});
Assertion.add('matchEach', function(other, description) {
this.params = { operator: 'to match each ' + i(other), message: description };
var f = other;
if(util.isRegExp(other))
f = function(it) {
return !!other.exec(it);
};
else if(!util.isFunction(other))
f = function(it) {
return eql(it, other);
};
util.forOwn(this.obj, function(value, key) {
var res = f(value, key);
//if we throw exception ok - it is used .should inside
if(util.isBoolean(res)) {
this.assert(res); // if it is just boolean function assert on it
}
}, this);
});
};
},{"../eql":2,"../util":16}],11:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
Assertion.add('NaN', function() {
this.params = { operator: 'to be NaN' };
this.is.a.Number
.and.assert(isNaN(this.obj));
}, true);
Assertion.add('Infinity', function() {
this.params = { operator: 'to be Infinity' };
this.is.a.Number
.and.not.a.NaN
.and.assert(!isFinite(this.obj));
}, true);
Assertion.add('within', function(start, finish, description) {
this.params = { operator: 'to be within ' + start + '..' + finish, message: description };
this.assert(this.obj >= start && this.obj <= finish);
});
Assertion.add('approximately', function(value, delta, description) {
this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description };
this.assert(Math.abs(this.obj - value) <= delta);
});
Assertion.add('above', function(n, description) {
this.params = { operator: 'to be above ' + n, message: description };
this.assert(this.obj > n);
});
Assertion.add('below', function(n, description) {
this.params = { operator: 'to be below ' + n, message: description };
this.assert(this.obj < n);
});
Assertion.alias('above', 'greaterThan');
Assertion.alias('below', 'lessThan');
};
},{}],12:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var util = require('../util'),
eql = require('../eql');
var aSlice = Array.prototype.slice;
module.exports = function(should, Assertion) {
var i = should.format;
Assertion.add('property', function(name, val) {
if(arguments.length > 1) {
var p = {};
p[name] = val;
this.have.properties(p);
} else {
this.have.properties(name);
}
this.obj = this.obj[name];
});
Assertion.add('properties', function(names) {
var values = {};
if(arguments.length > 1) {
names = aSlice.call(arguments);
} else if(!Array.isArray(names)) {
if(util.isString(names)) {
names = [names];
} else {
values = names;
names = Object.keys(names);
}
}
var obj = Object(this.obj), missingProperties = [];
//just enumerate properties and check if they all present
names.forEach(function(name) {
if(!(name in obj)) missingProperties.push(i(name));
});
var props = missingProperties;
if(props.length === 0) {
props = names.map(i);
}
var operator = (props.length === 1 ?
'to have property ' : 'to have properties ') + props.join(', ');
this.params = { operator: operator };
this.assert(missingProperties.length === 0);
// check if values in object matched expected
var valueCheckNames = Object.keys(values);
if(valueCheckNames.length) {
var wrongValues = [];
props = [];
// now check values, as there we have all properties
valueCheckNames.forEach(function(name) {
var value = values[name];
if(!eql(obj[name], value)) {
wrongValues.push(i(name) + ' of ' + i(value) + ' (got ' + i(obj[name]) + ')');
} else {
props.push(i(name) + ' of ' + i(value));
}
});
if(wrongValues.length > 0) {
props = wrongValues;
}
operator = (props.length === 1 ?
'to have property ' : 'to have properties ') + props.join(', ');
this.params = { operator: operator };
this.assert(wrongValues.length === 0);
}
});
Assertion.add('length', function(n, description) {
this.have.property('length', n, description);
});
Assertion.alias('length', 'lengthOf');
var hasOwnProperty = Object.prototype.hasOwnProperty;
Assertion.add('ownProperty', function(name, description) {
this.params = { operator: 'to have own property ' + i(name), message: description };
this.assert(hasOwnProperty.call(this.obj, name));
this.obj = this.obj[name];
});
Assertion.alias('hasOwnProperty', 'ownProperty');
Assertion.add('empty', function() {
this.params = { operator: 'to be empty' };
if(util.isString(this.obj) || Array.isArray(this.obj) || util.isArguments(this.obj)) {
this.have.property('length', 0);
} else {
var obj = Object(this.obj); // wrap to reference for booleans and numbers
for(var prop in obj) {
this.have.not.ownProperty(prop);
}
}
}, true);
Assertion.add('keys', function(keys) {
if(arguments.length > 1) keys = aSlice.call(arguments);
else if(arguments.length === 1 && util.isString(keys)) keys = [ keys ];
else if(arguments.length === 0) keys = [];
var obj = Object(this.obj);
// first check if some keys are missing
var missingKeys = [];
keys.forEach(function(key) {
if(!hasOwnProperty.call(this.obj, key))
missingKeys.push(i(key));
}, this);
// second check for extra keys
var extraKeys = [];
Object.keys(obj).forEach(function(key) {
if(keys.indexOf(key) < 0) {
extraKeys.push(i(key));
}
});
var verb = keys.length === 0 ? 'to be empty' :
'to have ' + (keys.length === 1 ? 'key ' : 'keys ');
this.params = { operator: verb + keys.map(i).join(', ')};
if(missingKeys.length > 0)
this.params.operator += '\n\tmissing keys: ' + missingKeys.join(', ');
if(extraKeys.length > 0)
this.params.operator += '\n\textra keys: ' + extraKeys.join(', ');
this.assert(missingKeys.length === 0 && extraKeys.length === 0);
});
Assertion.alias("keys", "key");
Assertion.add('containEql', function(other) {
this.params = { operator: 'to contain ' + i(other) };
var obj = this.obj;
if(Array.isArray(obj)) {
this.assert(obj.some(function(item) {
return eql(item, other);
}));
} else if(util.isString(obj)) {
// expect obj to be string
this.assert(obj.indexOf(String(other)) >= 0);
} else if(util.isObject(obj)) {
// object contains object case
util.forOwn(other, function(value, key) {
obj[key].should.eql(value);
});
} else {
//other uncovered cases
this.assert(false);
}
});
Assertion.add('containDeep', function(other) {
this.params = { operator: 'to contain ' + i(other) };
var obj = this.obj;
if(Array.isArray(obj)) {
if(Array.isArray(other)) {
var otherIdx = 0;
obj.forEach(function(item) {
try {
should(item).not.be.null.and.containDeep(other[otherIdx]);
otherIdx++;
} catch(e) {
if(e instanceof should.AssertionError) {
return;
}
throw e;
}
});
this.assert(otherIdx == other.length);
//search array contain other as sub sequence
} else {
this.assert(false);
}
} else if(util.isString(obj)) {// expect other to be string
this.assert(obj.indexOf(String(other)) >= 0);
} else if(util.isObject(obj)) {// object contains object case
if(util.isObject(other)) {
util.forOwn(other, function(value, key) {
should(obj[key]).not.be.null.and.containDeep(value);
});
} else {//one of the properties contain value
this.assert(false);
}
} else {
this.eql(other);
}
});
};
},{"../eql":2,"../util":16}],13:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
Assertion.add('startWith', function(str, description) {
this.params = { operator: 'to start with ' + should.format(str), message: description };
this.assert(0 === this.obj.indexOf(str));
});
Assertion.add('endWith', function(str, description) {
this.params = { operator: 'to end with ' + should.format(str), message: description };
this.assert(this.obj.indexOf(str, this.obj.length - str.length) >= 0);
});
};
},{}],14:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var util = require('../util');
module.exports = function(should, Assertion) {
Assertion.add('Number', function() {
this.params = { operator: 'to be a number' };
this.assert(util.isNumber(this.obj));
}, true);
Assertion.add('arguments', function() {
this.params = { operator: 'to be arguments' };
this.assert(util.isArguments(this.obj));
}, true);
Assertion.add('type', function(type, description) {
this.params = { operator: 'to have type ' + type, message: description };
(typeof this.obj).should.be.exactly(type, description);
});
Assertion.add('instanceof', function(constructor, description) {
this.params = { operator: 'to be an instance of ' + constructor.name, message: description };
this.assert(Object(this.obj) instanceof constructor);
});
Assertion.add('Function', function() {
this.params = { operator: 'to be a function' };
this.assert(util.isFunction(this.obj));
}, true);
Assertion.add('Object', function() {
this.params = { operator: 'to be an object' };
this.assert(util.isObject(this.obj));
}, true);
Assertion.add('String', function() {
this.params = { operator: 'to be a string' };
this.assert(util.isString(this.obj));
}, true);
Assertion.add('Array', function() {
this.params = { operator: 'to be an array' };
this.assert(Array.isArray(this.obj));
}, true);
Assertion.add('Boolean', function() {
this.params = { operator: 'to be a boolean' };
this.assert(util.isBoolean(this.obj));
}, true);
Assertion.add('Error', function() {
this.params = { operator: 'to be an error' };
this.assert(util.isError(this.obj));
}, true);
Assertion.add('null', function() {
this.params = { operator: 'to be null' };
this.assert(this.obj === null);
}, true);
Assertion.alias('instanceof', 'instanceOf');
};
},{"../util":16}],15:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
var util = require('./util')
, AssertionError = util.AssertionError
, inspect = util.inspect;
/**
* Our function should
* @param obj
* @returns {Assertion}
*/
var should = function(obj) {
return new Assertion(util.isWrapperType(obj) ? obj.valueOf(): obj);
};
/**
* Initialize a new `Assertion` with the given _obj_.
*
* @param {*} obj
* @api private
*/
var Assertion = should.Assertion = function Assertion(obj) {
this.obj = obj;
};
/**
Way to extend Assertion function. It uses some logic
to define only positive assertions and itself rule with negative assertion.
All actions happen in subcontext and this method take care about negation.
Potentially we can add some more modifiers that does not depends from state of assertion.
*/
Assertion.add = function(name, f, isGetter) {
var prop = {};
prop[isGetter ? 'get' : 'value'] = function() {
var context = new Assertion(this.obj);
context.copy = context.copyIfMissing;
try {
f.apply(context, arguments);
} catch(e) {
//copy data from sub context to this
this.copy(context);
//check for fail
if(e instanceof should.AssertionError) {
//negative fail
if(this.negate) {
this.obj = context.obj;
this.negate = false;
return this;
}
this.assert(false);
}
// throw if it is another exception
throw e;
}
//copy data from sub context to this
this.copy(context);
if(this.negate) {
this.assert(false);
}
this.obj = context.obj;
this.negate = false;
return this;
};
Object.defineProperty(Assertion.prototype, name, prop);
};
Assertion.alias = function(from, to) {
Assertion.prototype[to] = Assertion.prototype[from]
};
should.AssertionError = AssertionError;
var i = should.format = function i(value) {
if(util.isDate(value) && typeof value.inspect !== 'function') return value.toISOString(); //show millis in dates
return inspect(value, { depth: null });
};
should.use = function(f) {
f(this, Assertion);
return this;
};
/**
* Expose should to external world.
*/
exports = module.exports = should;
/**
* Expose api via `Object#should`.
*
* @api public
*/
Object.defineProperty(Object.prototype, 'should', {
set: function(){},
get: function(){
return should(this);
},
configurable: true
});
Assertion.prototype = {
constructor: Assertion,
assert: function(expr) {
if(expr) return;
var params = this.params;
var msg = params.message, generatedMessage = false;
if(!msg) {
msg = this.getMessage();
generatedMessage = true;
}
var err = new AssertionError({
message: msg
, actual: this.obj
, expected: params.expected
, stackStartFunction: this.assert
});
err.showDiff = params.showDiff;
err.operator = params.operator;
err.generatedMessage = generatedMessage;
throw err;
},
getMessage: function() {
return 'expected ' + i(this.obj) + (this.negate ? ' not ': ' ') +
this.params.operator + ('expected' in this.params ? ' ' + i(this.params.expected) : '');
},
copy: function(other) {
this.params = other.params;
},
copyIfMissing: function(other) {
if(!this.params) this.params = other.params;
},
/**
* Negation modifier.
*
* @api public
*/
get not() {
this.negate = !this.negate;
return this;
}
};
},{"./util":16}],16:[function(require,module,exports){
/*!
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
/**
* Check if given obj just a primitive type wrapper
* @param {Object} obj
* @returns {boolean}
* @api private
*/
exports.isWrapperType = function(obj) {
return isNumber(obj) || isString(obj) || isBoolean(obj);
};
/**
* Merge object b with object a.
*
* var a = { foo: 'bar' }
* , b = { bar: 'baz' };
*
* utils.merge(a, b);
* // => { foo: 'bar', bar: 'baz' }
*
* @param {Object} a
* @param {Object} b
* @return {Object}
* @api private
*/
exports.merge = function(a, b){
if (a && b) {
for (var key in b) {
a[key] = b[key];
}
}
return a;
};
function isNumber(arg) {
return typeof arg === 'number' || arg instanceof Number;
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string' || arg instanceof String;
}
function isBoolean(arg) {
return typeof arg === 'boolean' || arg instanceof Boolean;
}
exports.isBoolean = isBoolean;
exports.isString = isString;
function isBuffer(arg) {
return typeof Buffer !== 'undefined' && arg instanceof Buffer;
}
exports.isBuffer = isBuffer;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isArguments(object) {
return objectToString(object) === '[object Arguments]';
}
exports.isArguments = isArguments;
exports.isFunction = function(arg) {
return typeof arg === 'function' || arg instanceof Function;
};
function isError(e) {
return isObject(e) && objectToString(e) === '[object Error]';
}
exports.isError = isError;
exports.inspect = require('util').inspect;
exports.AssertionError = require('assert').AssertionError;
var hasOwnProperty = Object.prototype.hasOwnProperty;
exports.forOwn = function(obj, f, context) {
for(var prop in obj) {
if(hasOwnProperty.call(obj, prop)) {
f.call(context, obj[prop], prop);
}
}
};
},{"assert":17,"util":20}],17:[function(require,module,exports){
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// 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 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.
// when used in node, this will actually load the util module we depend on
// versus loading the builtin util module as happens otherwise
// this is a bug in node module loading as far as I am concerned
var util = require('util/');
var pSlice = Array.prototype.slice;
var hasOwn = Object.prototype.hasOwnProperty;
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
}
else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = stackStartFunction.name;
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (util.isUndefined(value)) {
return '' + value;
}
if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) {
return value.toString();
}
if (util.isFunction(value) || util.isRegExp(value)) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (util.isString(s)) {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try {
var ka = objectKeys(a),
kb = objectKeys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (util.isString(expected)) {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [true].concat(pSlice.call(arguments)));
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
_throws.apply(this, [false].concat(pSlice.call(arguments)));
};
assert.ifError = function(err) { if (err) {throw err;}};
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
},{"util/":20}],18:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],19:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],20:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
},{"./support/isBuffer":19,"inherits":18}]},{},[1])
(1)
}); | InnovatingTeams/InnovatingTeams.github.io | vendor/should/should.js | JavaScript | mit | 65,566 |
"use strict";function emptyFunction(){}exports.__esModule=!0,exports.default=void 0;var BackHandler={exitApp:emptyFunction,addEventListener:function(){return{remove:emptyFunction}},removeEventListener:emptyFunction},_default=BackHandler;exports.default=BackHandler,module.exports=exports.default; | cdnjs/cdnjs | ajax/libs/react-native-web/0.16.1/cjs/exports/BackHandler/index.min.js | JavaScript | mit | 296 |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/ipc/sem.c
* Copyright (C) 1992 Krishna Balasubramanian
* Copyright (C) 1995 Eric Schenk, Bruno Haible
*
* /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <[email protected]>
*
* SMP-threaded, sysctl's added
* (c) 1999 Manfred Spraul <[email protected]>
* Enforced range limit on SEM_UNDO
* (c) 2001 Red Hat Inc
* Lockless wakeup
* (c) 2003 Manfred Spraul <[email protected]>
* (c) 2016 Davidlohr Bueso <[email protected]>
* Further wakeup optimizations, documentation
* (c) 2010 Manfred Spraul <[email protected]>
*
* support for audit of ipc object properties and permission changes
* Dustin Kirkland <[email protected]>
*
* namespaces support
* OpenVZ, SWsoft Inc.
* Pavel Emelianov <[email protected]>
*
* Implementation notes: (May 2010)
* This file implements System V semaphores.
*
* User space visible behavior:
* - FIFO ordering for semop() operations (just FIFO, not starvation
* protection)
* - multiple semaphore operations that alter the same semaphore in
* one semop() are handled.
* - sem_ctime (time of last semctl()) is updated in the IPC_SET, SETVAL and
* SETALL calls.
* - two Linux specific semctl() commands: SEM_STAT, SEM_INFO.
* - undo adjustments at process exit are limited to 0..SEMVMX.
* - namespace are supported.
* - SEMMSL, SEMMNS, SEMOPM and SEMMNI can be configured at runtine by writing
* to /proc/sys/kernel/sem.
* - statistics about the usage are reported in /proc/sysvipc/sem.
*
* Internals:
* - scalability:
* - all global variables are read-mostly.
* - semop() calls and semctl(RMID) are synchronized by RCU.
* - most operations do write operations (actually: spin_lock calls) to
* the per-semaphore array structure.
* Thus: Perfect SMP scaling between independent semaphore arrays.
* If multiple semaphores in one array are used, then cache line
* trashing on the semaphore array spinlock will limit the scaling.
* - semncnt and semzcnt are calculated on demand in count_semcnt()
* - the task that performs a successful semop() scans the list of all
* sleeping tasks and completes any pending operations that can be fulfilled.
* Semaphores are actively given to waiting tasks (necessary for FIFO).
* (see update_queue())
* - To improve the scalability, the actual wake-up calls are performed after
* dropping all locks. (see wake_up_sem_queue_prepare())
* - All work is done by the waker, the woken up task does not have to do
* anything - not even acquiring a lock or dropping a refcount.
* - A woken up task may not even touch the semaphore array anymore, it may
* have been destroyed already by a semctl(RMID).
* - UNDO values are stored in an array (one per process and per
* semaphore array, lazily allocated). For backwards compatibility, multiple
* modes for the UNDO variables are supported (per process, per thread)
* (see copy_semundo, CLONE_SYSVSEM)
* - There are two lists of the pending operations: a per-array list
* and per-semaphore list (stored in the array). This allows to achieve FIFO
* ordering without always scanning all pending operations.
* The worst-case behavior is nevertheless O(N^2) for N wakeups.
*/
#include <linux/compat.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/time.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/seq_file.h>
#include <linux/rwsem.h>
#include <linux/nsproxy.h>
#include <linux/ipc_namespace.h>
#include <linux/sched/wake_q.h>
#include <linux/nospec.h>
#include <linux/rhashtable.h>
#include <linux/uaccess.h>
#include "util.h"
/* One semaphore structure for each semaphore in the system. */
struct sem {
int semval; /* current value */
/*
* PID of the process that last modified the semaphore. For
* Linux, specifically these are:
* - semop
* - semctl, via SETVAL and SETALL.
* - at task exit when performing undo adjustments (see exit_sem).
*/
struct pid *sempid;
spinlock_t lock; /* spinlock for fine-grained semtimedop */
struct list_head pending_alter; /* pending single-sop operations */
/* that alter the semaphore */
struct list_head pending_const; /* pending single-sop operations */
/* that do not alter the semaphore*/
time64_t sem_otime; /* candidate for sem_otime */
} ____cacheline_aligned_in_smp;
/* One sem_array data structure for each set of semaphores in the system. */
struct sem_array {
struct kern_ipc_perm sem_perm; /* permissions .. see ipc.h */
time64_t sem_ctime; /* create/last semctl() time */
struct list_head pending_alter; /* pending operations */
/* that alter the array */
struct list_head pending_const; /* pending complex operations */
/* that do not alter semvals */
struct list_head list_id; /* undo requests on this array */
int sem_nsems; /* no. of semaphores in array */
int complex_count; /* pending complex operations */
unsigned int use_global_lock;/* >0: global lock required */
struct sem sems[];
} __randomize_layout;
/* One queue for each sleeping process in the system. */
struct sem_queue {
struct list_head list; /* queue of pending operations */
struct task_struct *sleeper; /* this process */
struct sem_undo *undo; /* undo structure */
struct pid *pid; /* process id of requesting process */
int status; /* completion status of operation */
struct sembuf *sops; /* array of pending operations */
struct sembuf *blocking; /* the operation that blocked */
int nsops; /* number of operations */
bool alter; /* does *sops alter the array? */
bool dupsop; /* sops on more than one sem_num */
};
/* Each task has a list of undo requests. They are executed automatically
* when the process exits.
*/
struct sem_undo {
struct list_head list_proc; /* per-process list: *
* all undos from one process
* rcu protected */
struct rcu_head rcu; /* rcu struct for sem_undo */
struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
struct list_head list_id; /* per semaphore array list:
* all undos for one array */
int semid; /* semaphore set identifier */
short *semadj; /* array of adjustments */
/* one per semaphore */
};
/* sem_undo_list controls shared access to the list of sem_undo structures
* that may be shared among all a CLONE_SYSVSEM task group.
*/
struct sem_undo_list {
refcount_t refcnt;
spinlock_t lock;
struct list_head list_proc;
};
#define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
static int newary(struct ipc_namespace *, struct ipc_params *);
static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
#ifdef CONFIG_PROC_FS
static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
#endif
#define SEMMSL_FAST 256 /* 512 bytes on stack */
#define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
/*
* Switching from the mode suitable for simple ops
* to the mode for complex ops is costly. Therefore:
* use some hysteresis
*/
#define USE_GLOBAL_LOCK_HYSTERESIS 10
/*
* Locking:
* a) global sem_lock() for read/write
* sem_undo.id_next,
* sem_array.complex_count,
* sem_array.pending{_alter,_const},
* sem_array.sem_undo
*
* b) global or semaphore sem_lock() for read/write:
* sem_array.sems[i].pending_{const,alter}:
*
* c) special:
* sem_undo_list.list_proc:
* * undo_list->lock for write
* * rcu for read
* use_global_lock:
* * global sem_lock() for write
* * either local or global sem_lock() for read.
*
* Memory ordering:
* Most ordering is enforced by using spin_lock() and spin_unlock().
*
* Exceptions:
* 1) use_global_lock: (SEM_BARRIER_1)
* Setting it from non-zero to 0 is a RELEASE, this is ensured by
* using smp_store_release(): Immediately after setting it to 0,
* a simple op can start.
* Testing if it is non-zero is an ACQUIRE, this is ensured by using
* smp_load_acquire().
* Setting it from 0 to non-zero must be ordered with regards to
* this smp_load_acquire(), this is guaranteed because the smp_load_acquire()
* is inside a spin_lock() and after a write from 0 to non-zero a
* spin_lock()+spin_unlock() is done.
*
* 2) queue.status: (SEM_BARRIER_2)
* Initialization is done while holding sem_lock(), so no further barrier is
* required.
* Setting it to a result code is a RELEASE, this is ensured by both a
* smp_store_release() (for case a) and while holding sem_lock()
* (for case b).
* The AQUIRE when reading the result code without holding sem_lock() is
* achieved by using READ_ONCE() + smp_acquire__after_ctrl_dep().
* (case a above).
* Reading the result code while holding sem_lock() needs no further barriers,
* the locks inside sem_lock() enforce ordering (case b above)
*
* 3) current->state:
* current->state is set to TASK_INTERRUPTIBLE while holding sem_lock().
* The wakeup is handled using the wake_q infrastructure. wake_q wakeups may
* happen immediately after calling wake_q_add. As wake_q_add_safe() is called
* when holding sem_lock(), no further barriers are required.
*
* See also ipc/mqueue.c for more details on the covered races.
*/
#define sc_semmsl sem_ctls[0]
#define sc_semmns sem_ctls[1]
#define sc_semopm sem_ctls[2]
#define sc_semmni sem_ctls[3]
void sem_init_ns(struct ipc_namespace *ns)
{
ns->sc_semmsl = SEMMSL;
ns->sc_semmns = SEMMNS;
ns->sc_semopm = SEMOPM;
ns->sc_semmni = SEMMNI;
ns->used_sems = 0;
ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
}
#ifdef CONFIG_IPC_NS
void sem_exit_ns(struct ipc_namespace *ns)
{
free_ipcs(ns, &sem_ids(ns), freeary);
idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
rhashtable_destroy(&ns->ids[IPC_SEM_IDS].key_ht);
}
#endif
void __init sem_init(void)
{
sem_init_ns(&init_ipc_ns);
ipc_init_proc_interface("sysvipc/sem",
" key semid perms nsems uid gid cuid cgid otime ctime\n",
IPC_SEM_IDS, sysvipc_sem_proc_show);
}
/**
* unmerge_queues - unmerge queues, if possible.
* @sma: semaphore array
*
* The function unmerges the wait queues if complex_count is 0.
* It must be called prior to dropping the global semaphore array lock.
*/
static void unmerge_queues(struct sem_array *sma)
{
struct sem_queue *q, *tq;
/* complex operations still around? */
if (sma->complex_count)
return;
/*
* We will switch back to simple mode.
* Move all pending operation back into the per-semaphore
* queues.
*/
list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
struct sem *curr;
curr = &sma->sems[q->sops[0].sem_num];
list_add_tail(&q->list, &curr->pending_alter);
}
INIT_LIST_HEAD(&sma->pending_alter);
}
/**
* merge_queues - merge single semop queues into global queue
* @sma: semaphore array
*
* This function merges all per-semaphore queues into the global queue.
* It is necessary to achieve FIFO ordering for the pending single-sop
* operations when a multi-semop operation must sleep.
* Only the alter operations must be moved, the const operations can stay.
*/
static void merge_queues(struct sem_array *sma)
{
int i;
for (i = 0; i < sma->sem_nsems; i++) {
struct sem *sem = &sma->sems[i];
list_splice_init(&sem->pending_alter, &sma->pending_alter);
}
}
static void sem_rcu_free(struct rcu_head *head)
{
struct kern_ipc_perm *p = container_of(head, struct kern_ipc_perm, rcu);
struct sem_array *sma = container_of(p, struct sem_array, sem_perm);
security_sem_free(&sma->sem_perm);
kvfree(sma);
}
/*
* Enter the mode suitable for non-simple operations:
* Caller must own sem_perm.lock.
*/
static void complexmode_enter(struct sem_array *sma)
{
int i;
struct sem *sem;
if (sma->use_global_lock > 0) {
/*
* We are already in global lock mode.
* Nothing to do, just reset the
* counter until we return to simple mode.
*/
sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
return;
}
sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
for (i = 0; i < sma->sem_nsems; i++) {
sem = &sma->sems[i];
spin_lock(&sem->lock);
spin_unlock(&sem->lock);
}
}
/*
* Try to leave the mode that disallows simple operations:
* Caller must own sem_perm.lock.
*/
static void complexmode_tryleave(struct sem_array *sma)
{
if (sma->complex_count) {
/* Complex ops are sleeping.
* We must stay in complex mode
*/
return;
}
if (sma->use_global_lock == 1) {
/* See SEM_BARRIER_1 for purpose/pairing */
smp_store_release(&sma->use_global_lock, 0);
} else {
sma->use_global_lock--;
}
}
#define SEM_GLOBAL_LOCK (-1)
/*
* If the request contains only one semaphore operation, and there are
* no complex transactions pending, lock only the semaphore involved.
* Otherwise, lock the entire semaphore array, since we either have
* multiple semaphores in our own semops, or we need to look at
* semaphores from other pending complex operations.
*/
static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
int nsops)
{
struct sem *sem;
int idx;
if (nsops != 1) {
/* Complex operation - acquire a full lock */
ipc_lock_object(&sma->sem_perm);
/* Prevent parallel simple ops */
complexmode_enter(sma);
return SEM_GLOBAL_LOCK;
}
/*
* Only one semaphore affected - try to optimize locking.
* Optimized locking is possible if no complex operation
* is either enqueued or processed right now.
*
* Both facts are tracked by use_global_mode.
*/
idx = array_index_nospec(sops->sem_num, sma->sem_nsems);
sem = &sma->sems[idx];
/*
* Initial check for use_global_lock. Just an optimization,
* no locking, no memory barrier.
*/
if (!sma->use_global_lock) {
/*
* It appears that no complex operation is around.
* Acquire the per-semaphore lock.
*/
spin_lock(&sem->lock);
/* see SEM_BARRIER_1 for purpose/pairing */
if (!smp_load_acquire(&sma->use_global_lock)) {
/* fast path successful! */
return sops->sem_num;
}
spin_unlock(&sem->lock);
}
/* slow path: acquire the full lock */
ipc_lock_object(&sma->sem_perm);
if (sma->use_global_lock == 0) {
/*
* The use_global_lock mode ended while we waited for
* sma->sem_perm.lock. Thus we must switch to locking
* with sem->lock.
* Unlike in the fast path, there is no need to recheck
* sma->use_global_lock after we have acquired sem->lock:
* We own sma->sem_perm.lock, thus use_global_lock cannot
* change.
*/
spin_lock(&sem->lock);
ipc_unlock_object(&sma->sem_perm);
return sops->sem_num;
} else {
/*
* Not a false alarm, thus continue to use the global lock
* mode. No need for complexmode_enter(), this was done by
* the caller that has set use_global_mode to non-zero.
*/
return SEM_GLOBAL_LOCK;
}
}
static inline void sem_unlock(struct sem_array *sma, int locknum)
{
if (locknum == SEM_GLOBAL_LOCK) {
unmerge_queues(sma);
complexmode_tryleave(sma);
ipc_unlock_object(&sma->sem_perm);
} else {
struct sem *sem = &sma->sems[locknum];
spin_unlock(&sem->lock);
}
}
/*
* sem_lock_(check_) routines are called in the paths where the rwsem
* is not held.
*
* The caller holds the RCU read lock.
*/
static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&sem_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct sem_array, sem_perm);
}
static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct sem_array, sem_perm);
}
static inline void sem_lock_and_putref(struct sem_array *sma)
{
sem_lock(sma, NULL, -1);
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
}
static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
{
ipc_rmid(&sem_ids(ns), &s->sem_perm);
}
static struct sem_array *sem_alloc(size_t nsems)
{
struct sem_array *sma;
if (nsems > (INT_MAX - sizeof(*sma)) / sizeof(sma->sems[0]))
return NULL;
sma = kvzalloc(struct_size(sma, sems, nsems), GFP_KERNEL);
if (unlikely(!sma))
return NULL;
return sma;
}
/**
* newary - Create a new semaphore set
* @ns: namespace
* @params: ptr to the structure that contains key, semflg and nsems
*
* Called with sem_ids.rwsem held (as a writer)
*/
static int newary(struct ipc_namespace *ns, struct ipc_params *params)
{
int retval;
struct sem_array *sma;
key_t key = params->key;
int nsems = params->u.nsems;
int semflg = params->flg;
int i;
if (!nsems)
return -EINVAL;
if (ns->used_sems + nsems > ns->sc_semmns)
return -ENOSPC;
sma = sem_alloc(nsems);
if (!sma)
return -ENOMEM;
sma->sem_perm.mode = (semflg & S_IRWXUGO);
sma->sem_perm.key = key;
sma->sem_perm.security = NULL;
retval = security_sem_alloc(&sma->sem_perm);
if (retval) {
kvfree(sma);
return retval;
}
for (i = 0; i < nsems; i++) {
INIT_LIST_HEAD(&sma->sems[i].pending_alter);
INIT_LIST_HEAD(&sma->sems[i].pending_const);
spin_lock_init(&sma->sems[i].lock);
}
sma->complex_count = 0;
sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
INIT_LIST_HEAD(&sma->pending_alter);
INIT_LIST_HEAD(&sma->pending_const);
INIT_LIST_HEAD(&sma->list_id);
sma->sem_nsems = nsems;
sma->sem_ctime = ktime_get_real_seconds();
/* ipc_addid() locks sma upon success. */
retval = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
if (retval < 0) {
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
return retval;
}
ns->used_sems += nsems;
sem_unlock(sma, -1);
rcu_read_unlock();
return sma->sem_perm.id;
}
/*
* Called with sem_ids.rwsem and ipcp locked.
*/
static int sem_more_checks(struct kern_ipc_perm *ipcp, struct ipc_params *params)
{
struct sem_array *sma;
sma = container_of(ipcp, struct sem_array, sem_perm);
if (params->u.nsems > sma->sem_nsems)
return -EINVAL;
return 0;
}
long ksys_semget(key_t key, int nsems, int semflg)
{
struct ipc_namespace *ns;
static const struct ipc_ops sem_ops = {
.getnew = newary,
.associate = security_sem_associate,
.more_checks = sem_more_checks,
};
struct ipc_params sem_params;
ns = current->nsproxy->ipc_ns;
if (nsems < 0 || nsems > ns->sc_semmsl)
return -EINVAL;
sem_params.key = key;
sem_params.flg = semflg;
sem_params.u.nsems = nsems;
return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
}
SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
{
return ksys_semget(key, nsems, semflg);
}
/**
* perform_atomic_semop[_slow] - Attempt to perform semaphore
* operations on a given array.
* @sma: semaphore array
* @q: struct sem_queue that describes the operation
*
* Caller blocking are as follows, based the value
* indicated by the semaphore operation (sem_op):
*
* (1) >0 never blocks.
* (2) 0 (wait-for-zero operation): semval is non-zero.
* (3) <0 attempting to decrement semval to a value smaller than zero.
*
* Returns 0 if the operation was possible.
* Returns 1 if the operation is impossible, the caller must sleep.
* Returns <0 for error codes.
*/
static int perform_atomic_semop_slow(struct sem_array *sma, struct sem_queue *q)
{
int result, sem_op, nsops;
struct pid *pid;
struct sembuf *sop;
struct sem *curr;
struct sembuf *sops;
struct sem_undo *un;
sops = q->sops;
nsops = q->nsops;
un = q->undo;
for (sop = sops; sop < sops + nsops; sop++) {
int idx = array_index_nospec(sop->sem_num, sma->sem_nsems);
curr = &sma->sems[idx];
sem_op = sop->sem_op;
result = curr->semval;
if (!sem_op && result)
goto would_block;
result += sem_op;
if (result < 0)
goto would_block;
if (result > SEMVMX)
goto out_of_range;
if (sop->sem_flg & SEM_UNDO) {
int undo = un->semadj[sop->sem_num] - sem_op;
/* Exceeding the undo range is an error. */
if (undo < (-SEMAEM - 1) || undo > SEMAEM)
goto out_of_range;
un->semadj[sop->sem_num] = undo;
}
curr->semval = result;
}
sop--;
pid = q->pid;
while (sop >= sops) {
ipc_update_pid(&sma->sems[sop->sem_num].sempid, pid);
sop--;
}
return 0;
out_of_range:
result = -ERANGE;
goto undo;
would_block:
q->blocking = sop;
if (sop->sem_flg & IPC_NOWAIT)
result = -EAGAIN;
else
result = 1;
undo:
sop--;
while (sop >= sops) {
sem_op = sop->sem_op;
sma->sems[sop->sem_num].semval -= sem_op;
if (sop->sem_flg & SEM_UNDO)
un->semadj[sop->sem_num] += sem_op;
sop--;
}
return result;
}
static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
{
int result, sem_op, nsops;
struct sembuf *sop;
struct sem *curr;
struct sembuf *sops;
struct sem_undo *un;
sops = q->sops;
nsops = q->nsops;
un = q->undo;
if (unlikely(q->dupsop))
return perform_atomic_semop_slow(sma, q);
/*
* We scan the semaphore set twice, first to ensure that the entire
* operation can succeed, therefore avoiding any pointless writes
* to shared memory and having to undo such changes in order to block
* until the operations can go through.
*/
for (sop = sops; sop < sops + nsops; sop++) {
int idx = array_index_nospec(sop->sem_num, sma->sem_nsems);
curr = &sma->sems[idx];
sem_op = sop->sem_op;
result = curr->semval;
if (!sem_op && result)
goto would_block; /* wait-for-zero */
result += sem_op;
if (result < 0)
goto would_block;
if (result > SEMVMX)
return -ERANGE;
if (sop->sem_flg & SEM_UNDO) {
int undo = un->semadj[sop->sem_num] - sem_op;
/* Exceeding the undo range is an error. */
if (undo < (-SEMAEM - 1) || undo > SEMAEM)
return -ERANGE;
}
}
for (sop = sops; sop < sops + nsops; sop++) {
curr = &sma->sems[sop->sem_num];
sem_op = sop->sem_op;
result = curr->semval;
if (sop->sem_flg & SEM_UNDO) {
int undo = un->semadj[sop->sem_num] - sem_op;
un->semadj[sop->sem_num] = undo;
}
curr->semval += sem_op;
ipc_update_pid(&curr->sempid, q->pid);
}
return 0;
would_block:
q->blocking = sop;
return sop->sem_flg & IPC_NOWAIT ? -EAGAIN : 1;
}
static inline void wake_up_sem_queue_prepare(struct sem_queue *q, int error,
struct wake_q_head *wake_q)
{
get_task_struct(q->sleeper);
/* see SEM_BARRIER_2 for purpuse/pairing */
smp_store_release(&q->status, error);
wake_q_add_safe(wake_q, q->sleeper);
}
static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
{
list_del(&q->list);
if (q->nsops > 1)
sma->complex_count--;
}
/** check_restart(sma, q)
* @sma: semaphore array
* @q: the operation that just completed
*
* update_queue is O(N^2) when it restarts scanning the whole queue of
* waiting operations. Therefore this function checks if the restart is
* really necessary. It is called after a previously waiting operation
* modified the array.
* Note that wait-for-zero operations are handled without restart.
*/
static inline int check_restart(struct sem_array *sma, struct sem_queue *q)
{
/* pending complex alter operations are too difficult to analyse */
if (!list_empty(&sma->pending_alter))
return 1;
/* we were a sleeping complex operation. Too difficult */
if (q->nsops > 1)
return 1;
/* It is impossible that someone waits for the new value:
* - complex operations always restart.
* - wait-for-zero are handled seperately.
* - q is a previously sleeping simple operation that
* altered the array. It must be a decrement, because
* simple increments never sleep.
* - If there are older (higher priority) decrements
* in the queue, then they have observed the original
* semval value and couldn't proceed. The operation
* decremented to value - thus they won't proceed either.
*/
return 0;
}
/**
* wake_const_ops - wake up non-alter tasks
* @sma: semaphore array.
* @semnum: semaphore that was modified.
* @wake_q: lockless wake-queue head.
*
* wake_const_ops must be called after a semaphore in a semaphore array
* was set to 0. If complex const operations are pending, wake_const_ops must
* be called with semnum = -1, as well as with the number of each modified
* semaphore.
* The tasks that must be woken up are added to @wake_q. The return code
* is stored in q->pid.
* The function returns 1 if at least one operation was completed successfully.
*/
static int wake_const_ops(struct sem_array *sma, int semnum,
struct wake_q_head *wake_q)
{
struct sem_queue *q, *tmp;
struct list_head *pending_list;
int semop_completed = 0;
if (semnum == -1)
pending_list = &sma->pending_const;
else
pending_list = &sma->sems[semnum].pending_const;
list_for_each_entry_safe(q, tmp, pending_list, list) {
int error = perform_atomic_semop(sma, q);
if (error > 0)
continue;
/* operation completed, remove from queue & wakeup */
unlink_queue(sma, q);
wake_up_sem_queue_prepare(q, error, wake_q);
if (error == 0)
semop_completed = 1;
}
return semop_completed;
}
/**
* do_smart_wakeup_zero - wakeup all wait for zero tasks
* @sma: semaphore array
* @sops: operations that were performed
* @nsops: number of operations
* @wake_q: lockless wake-queue head
*
* Checks all required queue for wait-for-zero operations, based
* on the actual changes that were performed on the semaphore array.
* The function returns 1 if at least one operation was completed successfully.
*/
static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
int nsops, struct wake_q_head *wake_q)
{
int i;
int semop_completed = 0;
int got_zero = 0;
/* first: the per-semaphore queues, if known */
if (sops) {
for (i = 0; i < nsops; i++) {
int num = sops[i].sem_num;
if (sma->sems[num].semval == 0) {
got_zero = 1;
semop_completed |= wake_const_ops(sma, num, wake_q);
}
}
} else {
/*
* No sops means modified semaphores not known.
* Assume all were changed.
*/
for (i = 0; i < sma->sem_nsems; i++) {
if (sma->sems[i].semval == 0) {
got_zero = 1;
semop_completed |= wake_const_ops(sma, i, wake_q);
}
}
}
/*
* If one of the modified semaphores got 0,
* then check the global queue, too.
*/
if (got_zero)
semop_completed |= wake_const_ops(sma, -1, wake_q);
return semop_completed;
}
/**
* update_queue - look for tasks that can be completed.
* @sma: semaphore array.
* @semnum: semaphore that was modified.
* @wake_q: lockless wake-queue head.
*
* update_queue must be called after a semaphore in a semaphore array
* was modified. If multiple semaphores were modified, update_queue must
* be called with semnum = -1, as well as with the number of each modified
* semaphore.
* The tasks that must be woken up are added to @wake_q. The return code
* is stored in q->pid.
* The function internally checks if const operations can now succeed.
*
* The function return 1 if at least one semop was completed successfully.
*/
static int update_queue(struct sem_array *sma, int semnum, struct wake_q_head *wake_q)
{
struct sem_queue *q, *tmp;
struct list_head *pending_list;
int semop_completed = 0;
if (semnum == -1)
pending_list = &sma->pending_alter;
else
pending_list = &sma->sems[semnum].pending_alter;
again:
list_for_each_entry_safe(q, tmp, pending_list, list) {
int error, restart;
/* If we are scanning the single sop, per-semaphore list of
* one semaphore and that semaphore is 0, then it is not
* necessary to scan further: simple increments
* that affect only one entry succeed immediately and cannot
* be in the per semaphore pending queue, and decrements
* cannot be successful if the value is already 0.
*/
if (semnum != -1 && sma->sems[semnum].semval == 0)
break;
error = perform_atomic_semop(sma, q);
/* Does q->sleeper still need to sleep? */
if (error > 0)
continue;
unlink_queue(sma, q);
if (error) {
restart = 0;
} else {
semop_completed = 1;
do_smart_wakeup_zero(sma, q->sops, q->nsops, wake_q);
restart = check_restart(sma, q);
}
wake_up_sem_queue_prepare(q, error, wake_q);
if (restart)
goto again;
}
return semop_completed;
}
/**
* set_semotime - set sem_otime
* @sma: semaphore array
* @sops: operations that modified the array, may be NULL
*
* sem_otime is replicated to avoid cache line trashing.
* This function sets one instance to the current time.
*/
static void set_semotime(struct sem_array *sma, struct sembuf *sops)
{
if (sops == NULL) {
sma->sems[0].sem_otime = ktime_get_real_seconds();
} else {
sma->sems[sops[0].sem_num].sem_otime =
ktime_get_real_seconds();
}
}
/**
* do_smart_update - optimized update_queue
* @sma: semaphore array
* @sops: operations that were performed
* @nsops: number of operations
* @otime: force setting otime
* @wake_q: lockless wake-queue head
*
* do_smart_update() does the required calls to update_queue and wakeup_zero,
* based on the actual changes that were performed on the semaphore array.
* Note that the function does not do the actual wake-up: the caller is
* responsible for calling wake_up_q().
* It is safe to perform this call after dropping all locks.
*/
static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
int otime, struct wake_q_head *wake_q)
{
int i;
otime |= do_smart_wakeup_zero(sma, sops, nsops, wake_q);
if (!list_empty(&sma->pending_alter)) {
/* semaphore array uses the global queue - just process it. */
otime |= update_queue(sma, -1, wake_q);
} else {
if (!sops) {
/*
* No sops, thus the modified semaphores are not
* known. Check all.
*/
for (i = 0; i < sma->sem_nsems; i++)
otime |= update_queue(sma, i, wake_q);
} else {
/*
* Check the semaphores that were increased:
* - No complex ops, thus all sleeping ops are
* decrease.
* - if we decreased the value, then any sleeping
* semaphore ops wont be able to run: If the
* previous value was too small, then the new
* value will be too small, too.
*/
for (i = 0; i < nsops; i++) {
if (sops[i].sem_op > 0) {
otime |= update_queue(sma,
sops[i].sem_num, wake_q);
}
}
}
}
if (otime)
set_semotime(sma, sops);
}
/*
* check_qop: Test if a queued operation sleeps on the semaphore semnum
*/
static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
bool count_zero)
{
struct sembuf *sop = q->blocking;
/*
* Linux always (since 0.99.10) reported a task as sleeping on all
* semaphores. This violates SUS, therefore it was changed to the
* standard compliant behavior.
* Give the administrators a chance to notice that an application
* might misbehave because it relies on the Linux behavior.
*/
pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
"The task %s (%d) triggered the difference, watch for misbehavior.\n",
current->comm, task_pid_nr(current));
if (sop->sem_num != semnum)
return 0;
if (count_zero && sop->sem_op == 0)
return 1;
if (!count_zero && sop->sem_op < 0)
return 1;
return 0;
}
/* The following counts are associated to each semaphore:
* semncnt number of tasks waiting on semval being nonzero
* semzcnt number of tasks waiting on semval being zero
*
* Per definition, a task waits only on the semaphore of the first semop
* that cannot proceed, even if additional operation would block, too.
*/
static int count_semcnt(struct sem_array *sma, ushort semnum,
bool count_zero)
{
struct list_head *l;
struct sem_queue *q;
int semcnt;
semcnt = 0;
/* First: check the simple operations. They are easy to evaluate */
if (count_zero)
l = &sma->sems[semnum].pending_const;
else
l = &sma->sems[semnum].pending_alter;
list_for_each_entry(q, l, list) {
/* all task on a per-semaphore list sleep on exactly
* that semaphore
*/
semcnt++;
}
/* Then: check the complex operations. */
list_for_each_entry(q, &sma->pending_alter, list) {
semcnt += check_qop(sma, semnum, q, count_zero);
}
if (count_zero) {
list_for_each_entry(q, &sma->pending_const, list) {
semcnt += check_qop(sma, semnum, q, count_zero);
}
}
return semcnt;
}
/* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
* as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
* remains locked on exit.
*/
static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
{
struct sem_undo *un, *tu;
struct sem_queue *q, *tq;
struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
int i;
DEFINE_WAKE_Q(wake_q);
/* Free the existing undo structures for this semaphore set. */
ipc_assert_locked_object(&sma->sem_perm);
list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
list_del(&un->list_id);
spin_lock(&un->ulp->lock);
un->semid = -1;
list_del_rcu(&un->list_proc);
spin_unlock(&un->ulp->lock);
kfree_rcu(un, rcu);
}
/* Wake up all pending processes and let them fail with EIDRM. */
list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
unlink_queue(sma, q);
wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
}
list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
unlink_queue(sma, q);
wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
}
for (i = 0; i < sma->sem_nsems; i++) {
struct sem *sem = &sma->sems[i];
list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
unlink_queue(sma, q);
wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
}
list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
unlink_queue(sma, q);
wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
}
ipc_update_pid(&sem->sempid, NULL);
}
/* Remove the semaphore set from the IDR */
sem_rmid(ns, sma);
sem_unlock(sma, -1);
rcu_read_unlock();
wake_up_q(&wake_q);
ns->used_sems -= sma->sem_nsems;
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
}
static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
{
switch (version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct semid_ds out;
memset(&out, 0, sizeof(out));
ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
out.sem_otime = in->sem_otime;
out.sem_ctime = in->sem_ctime;
out.sem_nsems = in->sem_nsems;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
static time64_t get_semotime(struct sem_array *sma)
{
int i;
time64_t res;
res = sma->sems[0].sem_otime;
for (i = 1; i < sma->sem_nsems; i++) {
time64_t to = sma->sems[i].sem_otime;
if (to > res)
res = to;
}
return res;
}
static int semctl_stat(struct ipc_namespace *ns, int semid,
int cmd, struct semid64_ds *semid64)
{
struct sem_array *sma;
time64_t semotime;
int err;
memset(semid64, 0, sizeof(*semid64));
rcu_read_lock();
if (cmd == SEM_STAT || cmd == SEM_STAT_ANY) {
sma = sem_obtain_object(ns, semid);
if (IS_ERR(sma)) {
err = PTR_ERR(sma);
goto out_unlock;
}
} else { /* IPC_STAT */
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
err = PTR_ERR(sma);
goto out_unlock;
}
}
/* see comment for SHM_STAT_ANY */
if (cmd == SEM_STAT_ANY)
audit_ipc_obj(&sma->sem_perm);
else {
err = -EACCES;
if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
goto out_unlock;
}
err = security_sem_semctl(&sma->sem_perm, cmd);
if (err)
goto out_unlock;
ipc_lock_object(&sma->sem_perm);
if (!ipc_valid_object(&sma->sem_perm)) {
ipc_unlock_object(&sma->sem_perm);
err = -EIDRM;
goto out_unlock;
}
kernel_to_ipc64_perm(&sma->sem_perm, &semid64->sem_perm);
semotime = get_semotime(sma);
semid64->sem_otime = semotime;
semid64->sem_ctime = sma->sem_ctime;
#ifndef CONFIG_64BIT
semid64->sem_otime_high = semotime >> 32;
semid64->sem_ctime_high = sma->sem_ctime >> 32;
#endif
semid64->sem_nsems = sma->sem_nsems;
if (cmd == IPC_STAT) {
/*
* As defined in SUS:
* Return 0 on success
*/
err = 0;
} else {
/*
* SEM_STAT and SEM_STAT_ANY (both Linux specific)
* Return the full id, including the sequence number
*/
err = sma->sem_perm.id;
}
ipc_unlock_object(&sma->sem_perm);
out_unlock:
rcu_read_unlock();
return err;
}
static int semctl_info(struct ipc_namespace *ns, int semid,
int cmd, void __user *p)
{
struct seminfo seminfo;
int max_idx;
int err;
err = security_sem_semctl(NULL, cmd);
if (err)
return err;
memset(&seminfo, 0, sizeof(seminfo));
seminfo.semmni = ns->sc_semmni;
seminfo.semmns = ns->sc_semmns;
seminfo.semmsl = ns->sc_semmsl;
seminfo.semopm = ns->sc_semopm;
seminfo.semvmx = SEMVMX;
seminfo.semmnu = SEMMNU;
seminfo.semmap = SEMMAP;
seminfo.semume = SEMUME;
down_read(&sem_ids(ns).rwsem);
if (cmd == SEM_INFO) {
seminfo.semusz = sem_ids(ns).in_use;
seminfo.semaem = ns->used_sems;
} else {
seminfo.semusz = SEMUSZ;
seminfo.semaem = SEMAEM;
}
max_idx = ipc_get_maxidx(&sem_ids(ns));
up_read(&sem_ids(ns).rwsem);
if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
return -EFAULT;
return (max_idx < 0) ? 0 : max_idx;
}
static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
int val)
{
struct sem_undo *un;
struct sem_array *sma;
struct sem *curr;
int err;
DEFINE_WAKE_Q(wake_q);
if (val > SEMVMX || val < 0)
return -ERANGE;
rcu_read_lock();
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
return PTR_ERR(sma);
}
if (semnum < 0 || semnum >= sma->sem_nsems) {
rcu_read_unlock();
return -EINVAL;
}
if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
rcu_read_unlock();
return -EACCES;
}
err = security_sem_semctl(&sma->sem_perm, SETVAL);
if (err) {
rcu_read_unlock();
return -EACCES;
}
sem_lock(sma, NULL, -1);
if (!ipc_valid_object(&sma->sem_perm)) {
sem_unlock(sma, -1);
rcu_read_unlock();
return -EIDRM;
}
semnum = array_index_nospec(semnum, sma->sem_nsems);
curr = &sma->sems[semnum];
ipc_assert_locked_object(&sma->sem_perm);
list_for_each_entry(un, &sma->list_id, list_id)
un->semadj[semnum] = 0;
curr->semval = val;
ipc_update_pid(&curr->sempid, task_tgid(current));
sma->sem_ctime = ktime_get_real_seconds();
/* maybe some queued-up processes were waiting for this */
do_smart_update(sma, NULL, 0, 0, &wake_q);
sem_unlock(sma, -1);
rcu_read_unlock();
wake_up_q(&wake_q);
return 0;
}
static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
int cmd, void __user *p)
{
struct sem_array *sma;
struct sem *curr;
int err, nsems;
ushort fast_sem_io[SEMMSL_FAST];
ushort *sem_io = fast_sem_io;
DEFINE_WAKE_Q(wake_q);
rcu_read_lock();
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
return PTR_ERR(sma);
}
nsems = sma->sem_nsems;
err = -EACCES;
if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
goto out_rcu_wakeup;
err = security_sem_semctl(&sma->sem_perm, cmd);
if (err)
goto out_rcu_wakeup;
err = -EACCES;
switch (cmd) {
case GETALL:
{
ushort __user *array = p;
int i;
sem_lock(sma, NULL, -1);
if (!ipc_valid_object(&sma->sem_perm)) {
err = -EIDRM;
goto out_unlock;
}
if (nsems > SEMMSL_FAST) {
if (!ipc_rcu_getref(&sma->sem_perm)) {
err = -EIDRM;
goto out_unlock;
}
sem_unlock(sma, -1);
rcu_read_unlock();
sem_io = kvmalloc_array(nsems, sizeof(ushort),
GFP_KERNEL);
if (sem_io == NULL) {
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
return -ENOMEM;
}
rcu_read_lock();
sem_lock_and_putref(sma);
if (!ipc_valid_object(&sma->sem_perm)) {
err = -EIDRM;
goto out_unlock;
}
}
for (i = 0; i < sma->sem_nsems; i++)
sem_io[i] = sma->sems[i].semval;
sem_unlock(sma, -1);
rcu_read_unlock();
err = 0;
if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
err = -EFAULT;
goto out_free;
}
case SETALL:
{
int i;
struct sem_undo *un;
if (!ipc_rcu_getref(&sma->sem_perm)) {
err = -EIDRM;
goto out_rcu_wakeup;
}
rcu_read_unlock();
if (nsems > SEMMSL_FAST) {
sem_io = kvmalloc_array(nsems, sizeof(ushort),
GFP_KERNEL);
if (sem_io == NULL) {
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
return -ENOMEM;
}
}
if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
err = -EFAULT;
goto out_free;
}
for (i = 0; i < nsems; i++) {
if (sem_io[i] > SEMVMX) {
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
err = -ERANGE;
goto out_free;
}
}
rcu_read_lock();
sem_lock_and_putref(sma);
if (!ipc_valid_object(&sma->sem_perm)) {
err = -EIDRM;
goto out_unlock;
}
for (i = 0; i < nsems; i++) {
sma->sems[i].semval = sem_io[i];
ipc_update_pid(&sma->sems[i].sempid, task_tgid(current));
}
ipc_assert_locked_object(&sma->sem_perm);
list_for_each_entry(un, &sma->list_id, list_id) {
for (i = 0; i < nsems; i++)
un->semadj[i] = 0;
}
sma->sem_ctime = ktime_get_real_seconds();
/* maybe some queued-up processes were waiting for this */
do_smart_update(sma, NULL, 0, 0, &wake_q);
err = 0;
goto out_unlock;
}
/* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
}
err = -EINVAL;
if (semnum < 0 || semnum >= nsems)
goto out_rcu_wakeup;
sem_lock(sma, NULL, -1);
if (!ipc_valid_object(&sma->sem_perm)) {
err = -EIDRM;
goto out_unlock;
}
semnum = array_index_nospec(semnum, nsems);
curr = &sma->sems[semnum];
switch (cmd) {
case GETVAL:
err = curr->semval;
goto out_unlock;
case GETPID:
err = pid_vnr(curr->sempid);
goto out_unlock;
case GETNCNT:
err = count_semcnt(sma, semnum, 0);
goto out_unlock;
case GETZCNT:
err = count_semcnt(sma, semnum, 1);
goto out_unlock;
}
out_unlock:
sem_unlock(sma, -1);
out_rcu_wakeup:
rcu_read_unlock();
wake_up_q(&wake_q);
out_free:
if (sem_io != fast_sem_io)
kvfree(sem_io);
return err;
}
static inline unsigned long
copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
{
switch (version) {
case IPC_64:
if (copy_from_user(out, buf, sizeof(*out)))
return -EFAULT;
return 0;
case IPC_OLD:
{
struct semid_ds tbuf_old;
if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
return -EFAULT;
out->sem_perm.uid = tbuf_old.sem_perm.uid;
out->sem_perm.gid = tbuf_old.sem_perm.gid;
out->sem_perm.mode = tbuf_old.sem_perm.mode;
return 0;
}
default:
return -EINVAL;
}
}
/*
* This function handles some semctl commands which require the rwsem
* to be held in write mode.
* NOTE: no locks must be held, the rwsem is taken inside this function.
*/
static int semctl_down(struct ipc_namespace *ns, int semid,
int cmd, struct semid64_ds *semid64)
{
struct sem_array *sma;
int err;
struct kern_ipc_perm *ipcp;
down_write(&sem_ids(ns).rwsem);
rcu_read_lock();
ipcp = ipcctl_obtain_check(ns, &sem_ids(ns), semid, cmd,
&semid64->sem_perm, 0);
if (IS_ERR(ipcp)) {
err = PTR_ERR(ipcp);
goto out_unlock1;
}
sma = container_of(ipcp, struct sem_array, sem_perm);
err = security_sem_semctl(&sma->sem_perm, cmd);
if (err)
goto out_unlock1;
switch (cmd) {
case IPC_RMID:
sem_lock(sma, NULL, -1);
/* freeary unlocks the ipc object and rcu */
freeary(ns, ipcp);
goto out_up;
case IPC_SET:
sem_lock(sma, NULL, -1);
err = ipc_update_perm(&semid64->sem_perm, ipcp);
if (err)
goto out_unlock0;
sma->sem_ctime = ktime_get_real_seconds();
break;
default:
err = -EINVAL;
goto out_unlock1;
}
out_unlock0:
sem_unlock(sma, -1);
out_unlock1:
rcu_read_unlock();
out_up:
up_write(&sem_ids(ns).rwsem);
return err;
}
static long ksys_semctl(int semid, int semnum, int cmd, unsigned long arg, int version)
{
struct ipc_namespace *ns;
void __user *p = (void __user *)arg;
struct semid64_ds semid64;
int err;
if (semid < 0)
return -EINVAL;
ns = current->nsproxy->ipc_ns;
switch (cmd) {
case IPC_INFO:
case SEM_INFO:
return semctl_info(ns, semid, cmd, p);
case IPC_STAT:
case SEM_STAT:
case SEM_STAT_ANY:
err = semctl_stat(ns, semid, cmd, &semid64);
if (err < 0)
return err;
if (copy_semid_to_user(p, &semid64, version))
err = -EFAULT;
return err;
case GETALL:
case GETVAL:
case GETPID:
case GETNCNT:
case GETZCNT:
case SETALL:
return semctl_main(ns, semid, semnum, cmd, p);
case SETVAL: {
int val;
#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
/* big-endian 64bit */
val = arg >> 32;
#else
/* 32bit or little-endian 64bit */
val = arg;
#endif
return semctl_setval(ns, semid, semnum, val);
}
case IPC_SET:
if (copy_semid_from_user(&semid64, p, version))
return -EFAULT;
fallthrough;
case IPC_RMID:
return semctl_down(ns, semid, cmd, &semid64);
default:
return -EINVAL;
}
}
SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
{
return ksys_semctl(semid, semnum, cmd, arg, IPC_64);
}
#ifdef CONFIG_ARCH_WANT_IPC_PARSE_VERSION
long ksys_old_semctl(int semid, int semnum, int cmd, unsigned long arg)
{
int version = ipc_parse_version(&cmd);
return ksys_semctl(semid, semnum, cmd, arg, version);
}
SYSCALL_DEFINE4(old_semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
{
return ksys_old_semctl(semid, semnum, cmd, arg);
}
#endif
#ifdef CONFIG_COMPAT
struct compat_semid_ds {
struct compat_ipc_perm sem_perm;
old_time32_t sem_otime;
old_time32_t sem_ctime;
compat_uptr_t sem_base;
compat_uptr_t sem_pending;
compat_uptr_t sem_pending_last;
compat_uptr_t undo;
unsigned short sem_nsems;
};
static int copy_compat_semid_from_user(struct semid64_ds *out, void __user *buf,
int version)
{
memset(out, 0, sizeof(*out));
if (version == IPC_64) {
struct compat_semid64_ds __user *p = buf;
return get_compat_ipc64_perm(&out->sem_perm, &p->sem_perm);
} else {
struct compat_semid_ds __user *p = buf;
return get_compat_ipc_perm(&out->sem_perm, &p->sem_perm);
}
}
static int copy_compat_semid_to_user(void __user *buf, struct semid64_ds *in,
int version)
{
if (version == IPC_64) {
struct compat_semid64_ds v;
memset(&v, 0, sizeof(v));
to_compat_ipc64_perm(&v.sem_perm, &in->sem_perm);
v.sem_otime = lower_32_bits(in->sem_otime);
v.sem_otime_high = upper_32_bits(in->sem_otime);
v.sem_ctime = lower_32_bits(in->sem_ctime);
v.sem_ctime_high = upper_32_bits(in->sem_ctime);
v.sem_nsems = in->sem_nsems;
return copy_to_user(buf, &v, sizeof(v));
} else {
struct compat_semid_ds v;
memset(&v, 0, sizeof(v));
to_compat_ipc_perm(&v.sem_perm, &in->sem_perm);
v.sem_otime = in->sem_otime;
v.sem_ctime = in->sem_ctime;
v.sem_nsems = in->sem_nsems;
return copy_to_user(buf, &v, sizeof(v));
}
}
static long compat_ksys_semctl(int semid, int semnum, int cmd, int arg, int version)
{
void __user *p = compat_ptr(arg);
struct ipc_namespace *ns;
struct semid64_ds semid64;
int err;
ns = current->nsproxy->ipc_ns;
if (semid < 0)
return -EINVAL;
switch (cmd & (~IPC_64)) {
case IPC_INFO:
case SEM_INFO:
return semctl_info(ns, semid, cmd, p);
case IPC_STAT:
case SEM_STAT:
case SEM_STAT_ANY:
err = semctl_stat(ns, semid, cmd, &semid64);
if (err < 0)
return err;
if (copy_compat_semid_to_user(p, &semid64, version))
err = -EFAULT;
return err;
case GETVAL:
case GETPID:
case GETNCNT:
case GETZCNT:
case GETALL:
case SETALL:
return semctl_main(ns, semid, semnum, cmd, p);
case SETVAL:
return semctl_setval(ns, semid, semnum, arg);
case IPC_SET:
if (copy_compat_semid_from_user(&semid64, p, version))
return -EFAULT;
fallthrough;
case IPC_RMID:
return semctl_down(ns, semid, cmd, &semid64);
default:
return -EINVAL;
}
}
COMPAT_SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, int, arg)
{
return compat_ksys_semctl(semid, semnum, cmd, arg, IPC_64);
}
#ifdef CONFIG_ARCH_WANT_COMPAT_IPC_PARSE_VERSION
long compat_ksys_old_semctl(int semid, int semnum, int cmd, int arg)
{
int version = compat_ipc_parse_version(&cmd);
return compat_ksys_semctl(semid, semnum, cmd, arg, version);
}
COMPAT_SYSCALL_DEFINE4(old_semctl, int, semid, int, semnum, int, cmd, int, arg)
{
return compat_ksys_old_semctl(semid, semnum, cmd, arg);
}
#endif
#endif
/* If the task doesn't already have a undo_list, then allocate one
* here. We guarantee there is only one thread using this undo list,
* and current is THE ONE
*
* If this allocation and assignment succeeds, but later
* portions of this code fail, there is no need to free the sem_undo_list.
* Just let it stay associated with the task, and it'll be freed later
* at exit time.
*
* This can block, so callers must hold no locks.
*/
static inline int get_undo_list(struct sem_undo_list **undo_listp)
{
struct sem_undo_list *undo_list;
undo_list = current->sysvsem.undo_list;
if (!undo_list) {
undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
if (undo_list == NULL)
return -ENOMEM;
spin_lock_init(&undo_list->lock);
refcount_set(&undo_list->refcnt, 1);
INIT_LIST_HEAD(&undo_list->list_proc);
current->sysvsem.undo_list = undo_list;
}
*undo_listp = undo_list;
return 0;
}
static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
{
struct sem_undo *un;
list_for_each_entry_rcu(un, &ulp->list_proc, list_proc,
spin_is_locked(&ulp->lock)) {
if (un->semid == semid)
return un;
}
return NULL;
}
static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
{
struct sem_undo *un;
assert_spin_locked(&ulp->lock);
un = __lookup_undo(ulp, semid);
if (un) {
list_del_rcu(&un->list_proc);
list_add_rcu(&un->list_proc, &ulp->list_proc);
}
return un;
}
/**
* find_alloc_undo - lookup (and if not present create) undo array
* @ns: namespace
* @semid: semaphore array id
*
* The function looks up (and if not present creates) the undo structure.
* The size of the undo structure depends on the size of the semaphore
* array, thus the alloc path is not that straightforward.
* Lifetime-rules: sem_undo is rcu-protected, on success, the function
* performs a rcu_read_lock().
*/
static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
{
struct sem_array *sma;
struct sem_undo_list *ulp;
struct sem_undo *un, *new;
int nsems, error;
error = get_undo_list(&ulp);
if (error)
return ERR_PTR(error);
rcu_read_lock();
spin_lock(&ulp->lock);
un = lookup_undo(ulp, semid);
spin_unlock(&ulp->lock);
if (likely(un != NULL))
goto out;
/* no undo structure around - allocate one. */
/* step 1: figure out the size of the semaphore array */
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
return ERR_CAST(sma);
}
nsems = sma->sem_nsems;
if (!ipc_rcu_getref(&sma->sem_perm)) {
rcu_read_unlock();
un = ERR_PTR(-EIDRM);
goto out;
}
rcu_read_unlock();
/* step 2: allocate new undo structure */
new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
if (!new) {
ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
return ERR_PTR(-ENOMEM);
}
/* step 3: Acquire the lock on semaphore array */
rcu_read_lock();
sem_lock_and_putref(sma);
if (!ipc_valid_object(&sma->sem_perm)) {
sem_unlock(sma, -1);
rcu_read_unlock();
kfree(new);
un = ERR_PTR(-EIDRM);
goto out;
}
spin_lock(&ulp->lock);
/*
* step 4: check for races: did someone else allocate the undo struct?
*/
un = lookup_undo(ulp, semid);
if (un) {
kfree(new);
goto success;
}
/* step 5: initialize & link new undo structure */
new->semadj = (short *) &new[1];
new->ulp = ulp;
new->semid = semid;
assert_spin_locked(&ulp->lock);
list_add_rcu(&new->list_proc, &ulp->list_proc);
ipc_assert_locked_object(&sma->sem_perm);
list_add(&new->list_id, &sma->list_id);
un = new;
success:
spin_unlock(&ulp->lock);
sem_unlock(sma, -1);
out:
return un;
}
static long do_semtimedop(int semid, struct sembuf __user *tsops,
unsigned nsops, const struct timespec64 *timeout)
{
int error = -EINVAL;
struct sem_array *sma;
struct sembuf fast_sops[SEMOPM_FAST];
struct sembuf *sops = fast_sops, *sop;
struct sem_undo *un;
int max, locknum;
bool undos = false, alter = false, dupsop = false;
struct sem_queue queue;
unsigned long dup = 0, jiffies_left = 0;
struct ipc_namespace *ns;
ns = current->nsproxy->ipc_ns;
if (nsops < 1 || semid < 0)
return -EINVAL;
if (nsops > ns->sc_semopm)
return -E2BIG;
if (nsops > SEMOPM_FAST) {
sops = kvmalloc_array(nsops, sizeof(*sops), GFP_KERNEL);
if (sops == NULL)
return -ENOMEM;
}
if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
error = -EFAULT;
goto out_free;
}
if (timeout) {
if (timeout->tv_sec < 0 || timeout->tv_nsec < 0 ||
timeout->tv_nsec >= 1000000000L) {
error = -EINVAL;
goto out_free;
}
jiffies_left = timespec64_to_jiffies(timeout);
}
max = 0;
for (sop = sops; sop < sops + nsops; sop++) {
unsigned long mask = 1ULL << ((sop->sem_num) % BITS_PER_LONG);
if (sop->sem_num >= max)
max = sop->sem_num;
if (sop->sem_flg & SEM_UNDO)
undos = true;
if (dup & mask) {
/*
* There was a previous alter access that appears
* to have accessed the same semaphore, thus use
* the dupsop logic. "appears", because the detection
* can only check % BITS_PER_LONG.
*/
dupsop = true;
}
if (sop->sem_op != 0) {
alter = true;
dup |= mask;
}
}
if (undos) {
/* On success, find_alloc_undo takes the rcu_read_lock */
un = find_alloc_undo(ns, semid);
if (IS_ERR(un)) {
error = PTR_ERR(un);
goto out_free;
}
} else {
un = NULL;
rcu_read_lock();
}
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
error = PTR_ERR(sma);
goto out_free;
}
error = -EFBIG;
if (max >= sma->sem_nsems) {
rcu_read_unlock();
goto out_free;
}
error = -EACCES;
if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
rcu_read_unlock();
goto out_free;
}
error = security_sem_semop(&sma->sem_perm, sops, nsops, alter);
if (error) {
rcu_read_unlock();
goto out_free;
}
error = -EIDRM;
locknum = sem_lock(sma, sops, nsops);
/*
* We eventually might perform the following check in a lockless
* fashion, considering ipc_valid_object() locking constraints.
* If nsops == 1 and there is no contention for sem_perm.lock, then
* only a per-semaphore lock is held and it's OK to proceed with the
* check below. More details on the fine grained locking scheme
* entangled here and why it's RMID race safe on comments at sem_lock()
*/
if (!ipc_valid_object(&sma->sem_perm))
goto out_unlock_free;
/*
* semid identifiers are not unique - find_alloc_undo may have
* allocated an undo structure, it was invalidated by an RMID
* and now a new array with received the same id. Check and fail.
* This case can be detected checking un->semid. The existence of
* "un" itself is guaranteed by rcu.
*/
if (un && un->semid == -1)
goto out_unlock_free;
queue.sops = sops;
queue.nsops = nsops;
queue.undo = un;
queue.pid = task_tgid(current);
queue.alter = alter;
queue.dupsop = dupsop;
error = perform_atomic_semop(sma, &queue);
if (error == 0) { /* non-blocking succesfull path */
DEFINE_WAKE_Q(wake_q);
/*
* If the operation was successful, then do
* the required updates.
*/
if (alter)
do_smart_update(sma, sops, nsops, 1, &wake_q);
else
set_semotime(sma, sops);
sem_unlock(sma, locknum);
rcu_read_unlock();
wake_up_q(&wake_q);
goto out_free;
}
if (error < 0) /* non-blocking error path */
goto out_unlock_free;
/*
* We need to sleep on this operation, so we put the current
* task into the pending queue and go to sleep.
*/
if (nsops == 1) {
struct sem *curr;
int idx = array_index_nospec(sops->sem_num, sma->sem_nsems);
curr = &sma->sems[idx];
if (alter) {
if (sma->complex_count) {
list_add_tail(&queue.list,
&sma->pending_alter);
} else {
list_add_tail(&queue.list,
&curr->pending_alter);
}
} else {
list_add_tail(&queue.list, &curr->pending_const);
}
} else {
if (!sma->complex_count)
merge_queues(sma);
if (alter)
list_add_tail(&queue.list, &sma->pending_alter);
else
list_add_tail(&queue.list, &sma->pending_const);
sma->complex_count++;
}
do {
/* memory ordering ensured by the lock in sem_lock() */
WRITE_ONCE(queue.status, -EINTR);
queue.sleeper = current;
/* memory ordering is ensured by the lock in sem_lock() */
__set_current_state(TASK_INTERRUPTIBLE);
sem_unlock(sma, locknum);
rcu_read_unlock();
if (timeout)
jiffies_left = schedule_timeout(jiffies_left);
else
schedule();
/*
* fastpath: the semop has completed, either successfully or
* not, from the syscall pov, is quite irrelevant to us at this
* point; we're done.
*
* We _do_ care, nonetheless, about being awoken by a signal or
* spuriously. The queue.status is checked again in the
* slowpath (aka after taking sem_lock), such that we can detect
* scenarios where we were awakened externally, during the
* window between wake_q_add() and wake_up_q().
*/
error = READ_ONCE(queue.status);
if (error != -EINTR) {
/* see SEM_BARRIER_2 for purpose/pairing */
smp_acquire__after_ctrl_dep();
goto out_free;
}
rcu_read_lock();
locknum = sem_lock(sma, sops, nsops);
if (!ipc_valid_object(&sma->sem_perm))
goto out_unlock_free;
/*
* No necessity for any barrier: We are protect by sem_lock()
*/
error = READ_ONCE(queue.status);
/*
* If queue.status != -EINTR we are woken up by another process.
* Leave without unlink_queue(), but with sem_unlock().
*/
if (error != -EINTR)
goto out_unlock_free;
/*
* If an interrupt occurred we have to clean up the queue.
*/
if (timeout && jiffies_left == 0)
error = -EAGAIN;
} while (error == -EINTR && !signal_pending(current)); /* spurious */
unlink_queue(sma, &queue);
out_unlock_free:
sem_unlock(sma, locknum);
rcu_read_unlock();
out_free:
if (sops != fast_sops)
kvfree(sops);
return error;
}
long ksys_semtimedop(int semid, struct sembuf __user *tsops,
unsigned int nsops, const struct __kernel_timespec __user *timeout)
{
if (timeout) {
struct timespec64 ts;
if (get_timespec64(&ts, timeout))
return -EFAULT;
return do_semtimedop(semid, tsops, nsops, &ts);
}
return do_semtimedop(semid, tsops, nsops, NULL);
}
SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
unsigned int, nsops, const struct __kernel_timespec __user *, timeout)
{
return ksys_semtimedop(semid, tsops, nsops, timeout);
}
#ifdef CONFIG_COMPAT_32BIT_TIME
long compat_ksys_semtimedop(int semid, struct sembuf __user *tsems,
unsigned int nsops,
const struct old_timespec32 __user *timeout)
{
if (timeout) {
struct timespec64 ts;
if (get_old_timespec32(&ts, timeout))
return -EFAULT;
return do_semtimedop(semid, tsems, nsops, &ts);
}
return do_semtimedop(semid, tsems, nsops, NULL);
}
SYSCALL_DEFINE4(semtimedop_time32, int, semid, struct sembuf __user *, tsems,
unsigned int, nsops,
const struct old_timespec32 __user *, timeout)
{
return compat_ksys_semtimedop(semid, tsems, nsops, timeout);
}
#endif
SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
unsigned, nsops)
{
return do_semtimedop(semid, tsops, nsops, NULL);
}
/* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
* parent and child tasks.
*/
int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
{
struct sem_undo_list *undo_list;
int error;
if (clone_flags & CLONE_SYSVSEM) {
error = get_undo_list(&undo_list);
if (error)
return error;
refcount_inc(&undo_list->refcnt);
tsk->sysvsem.undo_list = undo_list;
} else
tsk->sysvsem.undo_list = NULL;
return 0;
}
/*
* add semadj values to semaphores, free undo structures.
* undo structures are not freed when semaphore arrays are destroyed
* so some of them may be out of date.
* IMPLEMENTATION NOTE: There is some confusion over whether the
* set of adjustments that needs to be done should be done in an atomic
* manner or not. That is, if we are attempting to decrement the semval
* should we queue up and wait until we can do so legally?
* The original implementation attempted to do this (queue and wait).
* The current implementation does not do so. The POSIX standard
* and SVID should be consulted to determine what behavior is mandated.
*/
void exit_sem(struct task_struct *tsk)
{
struct sem_undo_list *ulp;
ulp = tsk->sysvsem.undo_list;
if (!ulp)
return;
tsk->sysvsem.undo_list = NULL;
if (!refcount_dec_and_test(&ulp->refcnt))
return;
for (;;) {
struct sem_array *sma;
struct sem_undo *un;
int semid, i;
DEFINE_WAKE_Q(wake_q);
cond_resched();
rcu_read_lock();
un = list_entry_rcu(ulp->list_proc.next,
struct sem_undo, list_proc);
if (&un->list_proc == &ulp->list_proc) {
/*
* We must wait for freeary() before freeing this ulp,
* in case we raced with last sem_undo. There is a small
* possibility where we exit while freeary() didn't
* finish unlocking sem_undo_list.
*/
spin_lock(&ulp->lock);
spin_unlock(&ulp->lock);
rcu_read_unlock();
break;
}
spin_lock(&ulp->lock);
semid = un->semid;
spin_unlock(&ulp->lock);
/* exit_sem raced with IPC_RMID, nothing to do */
if (semid == -1) {
rcu_read_unlock();
continue;
}
sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, semid);
/* exit_sem raced with IPC_RMID, nothing to do */
if (IS_ERR(sma)) {
rcu_read_unlock();
continue;
}
sem_lock(sma, NULL, -1);
/* exit_sem raced with IPC_RMID, nothing to do */
if (!ipc_valid_object(&sma->sem_perm)) {
sem_unlock(sma, -1);
rcu_read_unlock();
continue;
}
un = __lookup_undo(ulp, semid);
if (un == NULL) {
/* exit_sem raced with IPC_RMID+semget() that created
* exactly the same semid. Nothing to do.
*/
sem_unlock(sma, -1);
rcu_read_unlock();
continue;
}
/* remove un from the linked lists */
ipc_assert_locked_object(&sma->sem_perm);
list_del(&un->list_id);
spin_lock(&ulp->lock);
list_del_rcu(&un->list_proc);
spin_unlock(&ulp->lock);
/* perform adjustments registered in un */
for (i = 0; i < sma->sem_nsems; i++) {
struct sem *semaphore = &sma->sems[i];
if (un->semadj[i]) {
semaphore->semval += un->semadj[i];
/*
* Range checks of the new semaphore value,
* not defined by sus:
* - Some unices ignore the undo entirely
* (e.g. HP UX 11i 11.22, Tru64 V5.1)
* - some cap the value (e.g. FreeBSD caps
* at 0, but doesn't enforce SEMVMX)
*
* Linux caps the semaphore value, both at 0
* and at SEMVMX.
*
* Manfred <[email protected]>
*/
if (semaphore->semval < 0)
semaphore->semval = 0;
if (semaphore->semval > SEMVMX)
semaphore->semval = SEMVMX;
ipc_update_pid(&semaphore->sempid, task_tgid(current));
}
}
/* maybe some queued-up processes were waiting for this */
do_smart_update(sma, NULL, 0, 1, &wake_q);
sem_unlock(sma, -1);
rcu_read_unlock();
wake_up_q(&wake_q);
kfree_rcu(un, rcu);
}
kfree(ulp);
}
#ifdef CONFIG_PROC_FS
static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
{
struct user_namespace *user_ns = seq_user_ns(s);
struct kern_ipc_perm *ipcp = it;
struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
time64_t sem_otime;
/*
* The proc interface isn't aware of sem_lock(), it calls
* ipc_lock_object() directly (in sysvipc_find_ipc).
* In order to stay compatible with sem_lock(), we must
* enter / leave complex_mode.
*/
complexmode_enter(sma);
sem_otime = get_semotime(sma);
seq_printf(s,
"%10d %10d %4o %10u %5u %5u %5u %5u %10llu %10llu\n",
sma->sem_perm.key,
sma->sem_perm.id,
sma->sem_perm.mode,
sma->sem_nsems,
from_kuid_munged(user_ns, sma->sem_perm.uid),
from_kgid_munged(user_ns, sma->sem_perm.gid),
from_kuid_munged(user_ns, sma->sem_perm.cuid),
from_kgid_munged(user_ns, sma->sem_perm.cgid),
sem_otime,
sma->sem_ctime);
complexmode_tryleave(sma);
return 0;
}
#endif
| GuillaumeSeren/linux | ipc/sem.c | C | gpl-2.0 | 64,175 |
/*
* 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.
*/
#include <limits>
#include <cstdlib>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TSocket.h>
namespace apache {
namespace thrift {
namespace transport {
using namespace std;
THttpClient::THttpClient(boost::shared_ptr<TTransport> transport,
std::string host,
std::string path)
: THttpTransport(transport), host_(host), path_(path) {
}
THttpClient::THttpClient(string host, int port, string path)
: THttpTransport(boost::shared_ptr<TTransport>(new TSocket(host, port))),
host_(host),
path_(path) {
}
THttpClient::~THttpClient() {
}
void THttpClient::parseHeader(char* header) {
char* colon = strchr(header, ':');
if (colon == NULL) {
return;
}
char* value = colon + 1;
if (boost::istarts_with(header, "Transfer-Encoding")) {
if (boost::iends_with(value, "chunked")) {
chunked_ = true;
}
} else if (boost::istarts_with(header, "Content-Length")) {
chunked_ = false;
contentLength_ = atoi(value);
}
}
bool THttpClient::parseStatusLine(char* status) {
char* http = status;
char* code = strchr(http, ' ');
if (code == NULL) {
throw TTransportException(string("Bad Status: ") + status);
}
*code = '\0';
while (*(code++) == ' ') {
};
char* msg = strchr(code, ' ');
if (msg == NULL) {
throw TTransportException(string("Bad Status: ") + status);
}
*msg = '\0';
if (strcmp(code, "200") == 0) {
// HTTP 200 = OK, we got the response
return true;
} else if (strcmp(code, "100") == 0) {
// HTTP 100 = continue, just keep reading
return false;
} else {
throw TTransportException(string("Bad Status: ") + status);
}
}
void THttpClient::flush() {
// Fetch the contents of the write buffer
uint8_t* buf;
uint32_t len;
writeBuffer_.getBuffer(&buf, &len);
// Construct the HTTP header
std::ostringstream h;
h << "POST " << path_ << " HTTP/1.1" << CRLF << "Host: " << host_ << CRLF
<< "Content-Type: application/x-thrift" << CRLF << "Content-Length: " << len << CRLF
<< "Accept: application/x-thrift" << CRLF << "User-Agent: Thrift/" << VERSION
<< " (C++/THttpClient)" << CRLF << CRLF;
string header = h.str();
if (header.size() > (std::numeric_limits<uint32_t>::max)())
throw TTransportException("Header too big");
// Write the header, then the data, then flush
transport_->write((const uint8_t*)header.c_str(), static_cast<uint32_t>(header.size()));
transport_->write(buf, len);
transport_->flush();
// Reset the buffer and header variables
writeBuffer_.resetBuffer();
readHeaders_ = true;
}
}
}
} // apache::thrift::transport
| jcgruenhage/dendrite | vendor/src/github.com/apache/thrift/lib/cpp/src/thrift/transport/THttpClient.cpp | C++ | apache-2.0 | 3,519 |
<?php
namespace Drupal\migrate\Plugin\migrate\destination;
use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\DependencyTrait;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides Configuration Management destination plugin.
*
* Persist data to the config system.
*
* When a property is NULL, the default is used unless the configuration option
* 'store null' is set to TRUE.
*
* @MigrateDestination(
* id = "config"
* )
*/
class Config extends DestinationBase implements ContainerFactoryPluginInterface, DependentPluginInterface {
use DependencyTrait;
/**
* The config object.
*
* @var \Drupal\Core\Config\Config
*/
protected $config;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $language_manager;
/**
* Constructs a Config destination object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\migrate\Plugin\MigrationInterface $migration
* The migration entity.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, ConfigFactoryInterface $config_factory, LanguageManagerInterface $language_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
$this->config = $config_factory->getEditable($configuration['config_name']);
$this->language_manager = $language_manager;
if ($this->isTranslationDestination()) {
$this->supportsRollback = TRUE;
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$migration,
$container->get('config.factory'),
$container->get('language_manager')
);
}
/**
* {@inheritdoc}
*/
public function import(Row $row, array $old_destination_id_values = []) {
if ($this->isTranslationDestination()) {
$this->config = $this->language_manager->getLanguageConfigOverride($row->getDestinationProperty('langcode'), $this->config->getName());
}
foreach ($row->getRawDestination() as $key => $value) {
if (isset($value) || !empty($this->configuration['store null'])) {
$this->config->set(str_replace(Row::PROPERTY_SEPARATOR, '.', $key), $value);
}
}
$this->config->save();
$ids[] = $this->config->getName();
if ($this->isTranslationDestination()) {
$ids[] = $row->getDestinationProperty('langcode');
}
return $ids;
}
/**
* {@inheritdoc}
*/
public function fields(MigrationInterface $migration = NULL) {
// @todo Dynamically fetch fields using Config Schema API.
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['config_name']['type'] = 'string';
if ($this->isTranslationDestination()) {
$ids['langcode']['type'] = 'string';
}
return $ids;
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$provider = explode('.', $this->config->getName(), 2)[0];
$this->addDependency('module', $provider);
return $this->dependencies;
}
/**
* Get whether this destination is for translations.
*
* @return bool
* Whether this destination is for translations.
*/
protected function isTranslationDestination() {
return !empty($this->configuration['translations']);
}
/**
* {@inheritdoc}
*/
public function rollback(array $destination_identifier) {
if ($this->isTranslationDestination()) {
$language = $destination_identifier['langcode'];
$config = $this->language_manager->getLanguageConfigOverride($language, $this->config->getName());
$config->delete();
}
}
}
| sukottokun/jenkins-002-001 | web/core/modules/migrate/src/Plugin/migrate/destination/Config.php | PHP | mit | 4,540 |
/**
* Copyright (c) 2010-2015, 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.homematic.internal.converter.state;
import org.openhab.binding.homematic.internal.model.HmValueItem;
import org.openhab.core.library.types.OnOffType;
/**
* Converts between openHAB OnOffType and Homematic values.
*
* @author Gerhard Riegler
* @since 1.5.0
*/
public class OnOffTypeConverter extends AbstractEnumTypeConverter<OnOffType> {
/**
* {@inheritDoc}
*/
@Override
protected OnOffType getFalseType() {
return OnOffType.OFF;
}
/**
* {@inheritDoc}
*/
@Override
protected OnOffType getTrueType() {
return OnOffType.ON;
}
/**
* If the item is a sensor or a state from some devices, then OnOff must be
* inverted.
*/
@Override
protected boolean isInvert(HmValueItem hmValueItem) {
return isName(hmValueItem, "SENSOR") || isStateInvertDevice(hmValueItem);
}
}
| Greblys/openhab | bundles/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/converter/state/OnOffTypeConverter.java | Java | epl-1.0 | 1,140 |
/**
* Copyright (c) 2010-2015, 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.homematic.test.state;
import junit.framework.Assert;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.junit.Test;
import org.openhab.binding.homematic.internal.converter.state.DecimalTypeConverter;
import org.openhab.binding.homematic.internal.converter.state.OnOffTypeConverter;
import org.openhab.binding.homematic.internal.converter.state.OpenClosedTypeConverter;
import org.openhab.binding.homematic.internal.converter.state.PercentTypeConverter;
import org.openhab.binding.homematic.internal.converter.state.StringTypeConverter;
import org.openhab.binding.homematic.internal.model.HmChannel;
import org.openhab.binding.homematic.internal.model.HmDatapoint;
import org.openhab.binding.homematic.internal.model.HmDevice;
import org.openhab.binding.homematic.internal.model.HmVariable;
import org.openhab.binding.homematic.internal.model.adapter.TypeGuessAdapter;
import org.openhab.binding.homematic.internal.model.adapter.ValueListAdapter;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.IncreaseDecreaseType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PercentType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.library.types.UpDownType;
/**
* Testcases for the converter framework of the Homematic binding.
*
* @author Gerhard Riegler
* @since 1.5.0
*/
public class ConverterTest {
private HmDatapoint getRollerShutterDatapoint(String name, Object value) throws Exception {
return getDatapoint(name, value, 0.0d, 1.0d, "HM-LC-Bl1-FM");
}
private HmDatapoint getDatapoint(String name, Object value) throws Exception {
return getDatapoint(name, value, 0, 0);
}
private HmDatapoint getDatapoint(String name, Object value, Number min, Number max) throws Exception {
return getDatapoint(name, value, min, max, null);
}
private HmDatapoint getDatapoint(String name, Object value, Number min, Number max, String deviceType)
throws Exception {
return getDatapoint(name, value, min, max, "1", deviceType);
}
private HmDatapoint getDatapoint(String name, Object value, Number min, Number max, String channelNumber,
String deviceType) throws Exception {
HmDatapoint dp = new HmDatapoint();
FieldUtils.writeField(dp, "name", name, true);
FieldUtils.writeField(dp, "minValue", min, true);
FieldUtils.writeField(dp, "maxValue", max, true);
Object convertedValue = new TypeGuessAdapter().unmarshal(value == null ? null : value.toString());
if (convertedValue instanceof Boolean) {
FieldUtils.writeField(dp, "valueType", 2, true);
} else if (convertedValue instanceof Integer) {
FieldUtils.writeField(dp, "valueType", 8, true);
} else if (convertedValue instanceof Double) {
FieldUtils.writeField(dp, "valueType", 4, true);
} else {
FieldUtils.writeField(dp, "valueType", -1, true);
}
dp.setValue(convertedValue);
HmChannel channel = new HmChannel();
FieldUtils.writeField(dp, "channel", channel, true);
FieldUtils.writeField(channel, "number", channelNumber, true);
HmDevice device = new HmDevice();
FieldUtils.writeField(device, "type", StringUtils.defaultString(deviceType, ""), true);
FieldUtils.writeField(channel, "device", device, true);
return dp;
}
private HmVariable getValueListVariable(Object value, String valueList) throws Exception {
HmVariable var = new HmVariable();
FieldUtils.writeField(var, "name", "Var", true);
FieldUtils.writeField(var, "valueType", 16, true);
FieldUtils.writeField(var, "subType", 29, true);
Object convertedValueList = new ValueListAdapter().unmarshal(valueList == null ? null : valueList.toString());
FieldUtils.writeField(var, "valueList", convertedValueList, true);
var.setValue(value);
return var;
}
@Test
public void testOnOffTypeConverterFromBinding() throws Exception {
OnOffTypeConverter converter = new OnOffTypeConverter();
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("PRESS_SHORT", true)));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("PRESS_SHORT", false)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("SENSOR", false)));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("SENSOR", true)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("LEVEL", true)));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("LEVEL", false)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("LEVEL", 1.0)));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("LEVEL", 0.0)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("LEVEL", 1)));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("LEVEL", 0)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("STATE", true)));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("STATE", false)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "HM-Sec-SC-2")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "HM-Sec-SC-2")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "15", "BC-SC-Rd-WM")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "15", "BC-SC-Rd-WM")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "15", "BC-SC-Rd-WM-2")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "15", "BC-SC-Rd-WM-2")));
Assert.assertEquals(OnOffType.ON,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "HM-SCI-3-FM")));
Assert.assertEquals(OnOffType.OFF,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "HM-SCI-3-FM")));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getDatapoint("LEVEL", "on")));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getDatapoint("LEVEL", "off")));
Assert.assertEquals(OnOffType.OFF, converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 1.0)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.1)));
Assert.assertEquals(OnOffType.ON, converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.9)));
}
@Test
public void testOnOffTypeConverterToBinding() throws Exception {
OnOffTypeConverter converter = new OnOffTypeConverter();
Assert.assertEquals(true, converter.convertToBinding(OnOffType.ON, getDatapoint("PRESS_SHORT", true)));
Assert.assertEquals(false, converter.convertToBinding(OnOffType.OFF, getDatapoint("PRESS_SHORT", false)));
Assert.assertEquals("ON", converter.convertToBinding(OnOffType.ON, getDatapoint("LEVEL", "")));
Assert.assertEquals("OFF", converter.convertToBinding(OnOffType.OFF, getDatapoint("LEVEL", "")));
Assert.assertEquals(1, converter.convertToBinding(OnOffType.ON, getDatapoint("LEVEL", 1, 0, 1)));
Assert.assertEquals(0, converter.convertToBinding(OnOffType.OFF, getDatapoint("LEVEL", 0)));
Assert.assertEquals(5, converter.convertToBinding(OnOffType.ON, getDatapoint("LEVEL", 5, 0, 5)));
Assert.assertEquals(0, converter.convertToBinding(OnOffType.OFF, getDatapoint("LEVEL", 0)));
Assert.assertEquals(0, converter.convertToBinding(OnOffType.OFF, getDatapoint("LEVEL", 1, 0, 5)));
Assert.assertEquals(0, converter.convertToBinding(OnOffType.OFF, getDatapoint("LEVEL", 4, 0, 5)));
Assert.assertEquals(true, converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true)));
Assert.assertEquals(false, converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false)));
Assert.assertEquals(false, converter.convertToBinding(OnOffType.ON, getDatapoint("SENSOR", true)));
Assert.assertEquals(true, converter.convertToBinding(OnOffType.OFF, getDatapoint("SENSOR", false)));
Assert.assertEquals(true, converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true)));
Assert.assertEquals(false, converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false)));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "HM-Sec-SC-2")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false, 0, 0, "HM-Sec-SC-2")));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(false, converter.convertToBinding(OnOffType.OFF,
getDatapoint("STATE", false, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(true, converter.convertToBinding(OnOffType.OFF,
getDatapoint("STATE", false, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "BC-SC-Rd-WM")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false, 0, 0, "BC-SC-Rd-WM")));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "BC-SC-Rd-WM-2")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false, 0, 0, "BC-SC-Rd-WM-2")));
Assert.assertEquals(false,
converter.convertToBinding(OnOffType.ON, getDatapoint("STATE", true, 0, 0, "HM-SCI-3-FM")));
Assert.assertEquals(true,
converter.convertToBinding(OnOffType.OFF, getDatapoint("STATE", false, 0, 0, "HM-SCI-3-FM")));
Assert.assertEquals(1.0, converter.convertToBinding(OnOffType.ON, getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(0.0, converter.convertToBinding(OnOffType.OFF, getRollerShutterDatapoint("LEVEL", 0.0)));
}
@Test
public void testOpenClosedTypeConverterFromBinding() throws Exception {
OpenClosedTypeConverter converter = new OpenClosedTypeConverter();
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("PRESS_SHORT", true)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("PRESS_SHORT", false)));
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("SENSOR", false)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("SENSOR", true)));
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("STATE", true)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("STATE", false)));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "HM-Sec-SC-2")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "HM-Sec-SC-2")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "15", "BC-SC-Rd-WM")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "15", "BC-SC-Rd-WM")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "15", "BC-SC-Rd-WM-2")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "15", "BC-SC-Rd-WM-2")));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getDatapoint("STATE", false, 0, 0, "15", "HM-SCI-3-FM")));
Assert.assertEquals(OpenClosedType.OPEN,
converter.convertFromBinding(getDatapoint("STATE", true, 0, 0, "15", "HM-SCI-3-FM")));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("STATE", false)));
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("STATE", true)));
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("LEVEL", true)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("LEVEL", false)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("LEVEL", 1.0)));
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("LEVEL", 0.0)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("LEVEL", 1)));
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("LEVEL", 0)));
Assert.assertEquals(OpenClosedType.CLOSED, converter.convertFromBinding(getDatapoint("LEVEL", "closed")));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getDatapoint("LEVEL", "open")));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 1.0)));
Assert.assertEquals(OpenClosedType.CLOSED,
converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.1)));
Assert.assertEquals(OpenClosedType.OPEN, converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.9)));
}
@Test
public void testOpenClosedTypeConverterToBinding() throws Exception {
OpenClosedTypeConverter converter = new OpenClosedTypeConverter();
Assert.assertEquals(true, converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("PRESS_SHORT", true)));
Assert.assertEquals(false, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("PRESS_SHORT", false)));
Assert.assertEquals("CLOSED", converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("LEVEL", "")));
Assert.assertEquals("OPEN", converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("LEVEL", "")));
Assert.assertEquals(1, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("LEVEL", 1, 0, 1)));
Assert.assertEquals(0, converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("LEVEL", 0)));
Assert.assertEquals(5, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("LEVEL", 5, 0, 5)));
Assert.assertEquals(0, converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("LEVEL", 0)));
Assert.assertEquals(5, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("LEVEL", 1, 0, 5)));
Assert.assertEquals(5, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("LEVEL", 4, 0, 5)));
Assert.assertEquals(false, converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("SENSOR", true)));
Assert.assertEquals(true, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("SENSOR", false)));
Assert.assertEquals(false,
converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(true,
converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(false,
converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true, 0, 0, "HM-Sec-SC-2")));
Assert.assertEquals(true,
converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false, 0, 0, "HM-Sec-SC")));
Assert.assertEquals(false,
converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(true,
converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false, 0, 0, "ZEL STG RM FFK")));
Assert.assertEquals(false,
converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(true,
converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false, 0, 0, "HM-Sec-TiS")));
Assert.assertEquals(
true,
converter.convertToBinding(OpenClosedType.CLOSED,
getDatapoint("STATE", true, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(
false,
converter.convertToBinding(OpenClosedType.OPEN,
getDatapoint("STATE", false, 0, 0, "14", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(
false,
converter.convertToBinding(OpenClosedType.CLOSED,
getDatapoint("STATE", true, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(
true,
converter.convertToBinding(OpenClosedType.OPEN,
getDatapoint("STATE", false, 0, 0, "15", "HMW-IO-12-Sw14-DR")));
Assert.assertEquals(false,
converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true, 0, 0, "BC-SC-Rd-WM")));
Assert.assertEquals(true,
converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false, 0, 0, "BC-SC-Rd-WM")));
Assert.assertEquals(false,
converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true, 0, 0, "BC-SC-Rd-WM-2")));
Assert.assertEquals(true,
converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false, 0, 0, "BC-SC-Rd-WM-2")));
Assert.assertEquals(false,
converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true, 0, 0, "HM-SCI-3-FM")));
Assert.assertEquals(true,
converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false, 0, 0, "HM-SCI-3-FM")));
Assert.assertEquals(true, converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("STATE", true)));
Assert.assertEquals(false, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("STATE", false)));
Assert.assertEquals(false, converter.convertToBinding(OpenClosedType.CLOSED, getDatapoint("SENSOR", false)));
Assert.assertEquals(true, converter.convertToBinding(OpenClosedType.OPEN, getDatapoint("SENSOR", true)));
Assert.assertEquals(1.0,
converter.convertToBinding(OpenClosedType.OPEN, getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(0.0,
converter.convertToBinding(OpenClosedType.CLOSED, getRollerShutterDatapoint("LEVEL", 0.0)));
}
@Test
public void testDecimalTypeConverterFromBinding() throws Exception {
DecimalTypeConverter converter = new DecimalTypeConverter();
Assert.assertEquals(new DecimalType(1), converter.convertFromBinding(getDatapoint("PRESS_SHORT", 1)));
Assert.assertEquals(new DecimalType(0), converter.convertFromBinding(getDatapoint("PRESS_SHORT", 0)));
Assert.assertEquals(new DecimalType(1), converter.convertFromBinding(getDatapoint("PRESS_SHORT", true, 0, 1)));
Assert.assertEquals(new DecimalType(5), converter.convertFromBinding(getDatapoint("PRESS_SHORT", true, 0, 5)));
Assert.assertEquals(new DecimalType(5.4).doubleValue(),
converter.convertFromBinding(getDatapoint("PRESS_SHORT", true, 0.0, 5.4)).doubleValue());
Assert.assertEquals(new DecimalType(0), converter.convertFromBinding(getDatapoint("PRESS_SHORT", false, 0, 1)));
Assert.assertEquals(new DecimalType(1), converter.convertFromBinding(getDatapoint("SENSOR", 1)));
Assert.assertEquals(new DecimalType(0), converter.convertFromBinding(getDatapoint("SENSOR", 0)));
Assert.assertEquals(new DecimalType(1.0).doubleValue(), converter
.convertFromBinding(getDatapoint("LEVEL", 1.0)).doubleValue());
Assert.assertEquals(new DecimalType(3.4).doubleValue(), converter
.convertFromBinding(getDatapoint("LEVEL", 3.4)).doubleValue());
Assert.assertEquals(new DecimalType(9876.678957).doubleValue(),
converter.convertFromBinding(getDatapoint("LEVEL", 9876.6789568)).doubleValue());
Assert.assertEquals(new DecimalType(5.3).doubleValue(),
converter.convertFromBinding(getDatapoint("LEVEL", "true", 0.0, 5.3)).doubleValue());
Assert.assertEquals(new DecimalType(0.0).doubleValue(),
converter.convertFromBinding(getDatapoint("LEVEL", "false", 0.0, 5.3)).doubleValue());
Assert.assertEquals(new DecimalType(1.0).doubleValue(), converter
.convertFromBinding(getDatapoint("LEVEL", "1")).doubleValue());
Assert.assertEquals(new DecimalType(1.0).doubleValue(),
converter.convertFromBinding(getDatapoint("LEVEL", "1.0")).doubleValue());
Assert.assertEquals(new DecimalType(9876.678957).doubleValue(),
converter.convertFromBinding(getDatapoint("LEVEL", "9876.6789568")).doubleValue());
Assert.assertEquals(new DecimalType(1.0).doubleValue(),
converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 1.0)).doubleValue());
Assert.assertEquals(new DecimalType(0.0).doubleValue(), converter
.convertFromBinding(getDatapoint("LEVEL", 0.0)).doubleValue());
}
@Test
public void testDecimalTypeConverterToBinding() throws Exception {
DecimalTypeConverter converter = new DecimalTypeConverter();
Assert.assertEquals(true,
converter.convertToBinding(new DecimalType(1), getDatapoint("PRESS_SHORT", true, 0, 1)));
Assert.assertEquals(false,
converter.convertToBinding(new DecimalType(0), getDatapoint("PRESS_SHORT", true, 0, 1)));
Assert.assertEquals(true, converter.convertToBinding(new DecimalType(5), getDatapoint("LEVEL", true, 0, 5)));
Assert.assertEquals(false, converter.convertToBinding(new DecimalType(4), getDatapoint("LEVEL", true, 0, 5)));
Assert.assertEquals(false, converter.convertToBinding(new DecimalType(0), getDatapoint("LEVEL", true, 0, 1)));
Assert.assertEquals(true, converter.convertToBinding(new DecimalType(1), getDatapoint("LEVEL", "true", 0, 1)));
Assert.assertEquals(false, converter.convertToBinding(new DecimalType(0), getDatapoint("LEVEL", "false", 0, 1)));
Assert.assertEquals(1, converter.convertToBinding(new DecimalType(1), getDatapoint("LEVEL", 0)));
Assert.assertEquals(1.0, converter.convertToBinding(new DecimalType(1), getDatapoint("LEVEL", 0.0)));
Assert.assertEquals(9876.678957,
converter.convertToBinding(new DecimalType(9876.6789568), getDatapoint("LEVEL", 0.0)));
Assert.assertEquals("1.0", converter.convertToBinding(new DecimalType(1), getDatapoint("LEVEL", "text")));
Assert.assertEquals(0.5,
converter.convertToBinding(new DecimalType(0.5), getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(0.4,
converter.convertToBinding(new DecimalType(0.4), getRollerShutterDatapoint("LEVEL", 0.0)));
}
@Test
public void testPercentTypeConverterFromBinding() throws Exception {
PercentTypeConverter converter = new PercentTypeConverter();
Assert.assertEquals(new PercentType(100), converter.convertFromBinding(getDatapoint("PRESS_SHORT", 1, 0, 1)));
Assert.assertEquals(new PercentType(0), converter.convertFromBinding(getDatapoint("PRESS_SHORT", 0, 0, 1)));
Assert.assertEquals(new PercentType(100), converter.convertFromBinding(getDatapoint("PRESS_SHORT", true, 0, 1)));
Assert.assertEquals(new PercentType(100), converter.convertFromBinding(getDatapoint("PRESS_SHORT", true, 0, 5)));
Assert.assertEquals(new PercentType(100),
converter.convertFromBinding(getDatapoint("PRESS_SHORT", true, 0.0, 5.4)));
Assert.assertEquals(new PercentType(0), converter.convertFromBinding(getDatapoint("PRESS_SHORT", false, 0, 1)));
Assert.assertEquals(new PercentType(100), converter.convertFromBinding(getDatapoint("SENSOR", 1, 0, 1)));
Assert.assertEquals(new PercentType(0), converter.convertFromBinding(getDatapoint("SENSOR", 0, 0, 1)));
Assert.assertEquals(new PercentType(100), converter.convertFromBinding(getDatapoint("LEVEL", 1.0, 0.0, 1.0)));
Assert.assertEquals(new PercentType(100), converter.convertFromBinding(getDatapoint("LEVEL", 3.4, 0.0, 3.4)));
Assert.assertEquals(new PercentType(40), converter.convertFromBinding(getDatapoint("LEVEL", 0.4, 0.0, 1.0)));
Assert.assertEquals(new PercentType(80), converter.convertFromBinding(getDatapoint("LEVEL", 0.8, 0.0, 1.0)));
Assert.assertEquals(new PercentType(60), converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.4)));
Assert.assertEquals(new PercentType(20), converter.convertFromBinding(getRollerShutterDatapoint("LEVEL", 0.8)));
Assert.assertEquals(new PercentType(20), converter.convertFromBinding(getDatapoint("LEVEL", 50, 0, 250)));
Assert.assertEquals(new PercentType(20), converter.convertFromBinding(getDatapoint("LEVEL", 50.0, 0.0, 250.0)));
Assert.assertEquals(new PercentType(20), converter.convertFromBinding(getDatapoint("LEVEL", "50", 0, 250)));
Assert.assertEquals(new PercentType(20),
converter.convertFromBinding(getDatapoint("LEVEL", "50.0", 0.0, 250.0)));
}
@Test
public void testPercentTypeConverterToBinding() throws Exception {
PercentTypeConverter converter = new PercentTypeConverter();
Assert.assertEquals(true,
converter.convertToBinding(new PercentType(100), getDatapoint("PRESS_SHORT", true, 0, 1)));
Assert.assertEquals(false,
converter.convertToBinding(new PercentType(0), getDatapoint("PRESS_SHORT", false, 0, 1)));
Assert.assertEquals(1, converter.convertToBinding(new PercentType(100), getDatapoint("SENSOR", 1, 0, 1)));
Assert.assertEquals(0, converter.convertToBinding(new PercentType(0), getDatapoint("SENSOR", 0, 0, 1)));
Assert.assertEquals(0.5, converter.convertToBinding(new PercentType(50), getDatapoint("LEVEL", 0.0, 0, 1)));
Assert.assertEquals(0.2, converter.convertToBinding(new PercentType(20), getDatapoint("LEVEL", 0.0, 0, 1)));
Assert.assertEquals(50, converter.convertToBinding(new PercentType(20), getDatapoint("LEVEL", 0, 0, 250)));
Assert.assertEquals(50, converter.convertToBinding(new PercentType(20), getDatapoint("LEVEL", 0, 0, 250)));
Assert.assertEquals("50.0",
converter.convertToBinding(new PercentType(20), getDatapoint("LEVEL", "text", 0, 250)));
Assert.assertEquals("50.0",
converter.convertToBinding(new PercentType(20), getDatapoint("LEVEL", "text", 0, 250)));
Assert.assertEquals(0.0,
converter.convertToBinding(new PercentType(100), getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(1.0,
converter.convertToBinding(new PercentType(0), getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(0.2,
converter.convertToBinding(new PercentType(80), getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(0.0,
converter.convertToBinding(IncreaseDecreaseType.INCREASE, getRollerShutterDatapoint("LEVEL", 0.1)));
Assert.assertEquals(0.3,
converter.convertToBinding(IncreaseDecreaseType.DECREASE, getRollerShutterDatapoint("LEVEL", 0.2)));
Assert.assertEquals(20,
converter.convertToBinding(IncreaseDecreaseType.INCREASE, getDatapoint("LEVEL", 10, 0, 100)));
Assert.assertEquals(40,
converter.convertToBinding(IncreaseDecreaseType.DECREASE, getDatapoint("LEVEL", 50, 0, 100)));
Assert.assertEquals(100,
converter.convertToBinding(IncreaseDecreaseType.INCREASE, getDatapoint("LEVEL", 100, 0, 100)));
Assert.assertEquals(0,
converter.convertToBinding(IncreaseDecreaseType.DECREASE, getDatapoint("LEVEL", 0, 0, 100)));
Assert.assertEquals(100, converter.convertToBinding(OnOffType.ON, getDatapoint("LEVEL", 10, 0, 100)));
Assert.assertEquals(90, converter.convertToBinding(OnOffType.ON, getDatapoint("LEVEL", 10, 0, 90)));
Assert.assertEquals(0, converter.convertToBinding(OnOffType.OFF, getDatapoint("LEVEL", 10, 0, 90)));
Assert.assertEquals(0.0, converter.convertToBinding(OnOffType.ON, getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(1.0, converter.convertToBinding(OnOffType.OFF, getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(100, converter.convertToBinding(UpDownType.UP, getDatapoint("LEVEL", 10, 0, 100)));
Assert.assertEquals(90, converter.convertToBinding(UpDownType.UP, getDatapoint("LEVEL", 10, 0, 90)));
Assert.assertEquals(0, converter.convertToBinding(UpDownType.DOWN, getDatapoint("LEVEL", 10, 0, 90)));
Assert.assertEquals(0.0, converter.convertToBinding(UpDownType.DOWN, getRollerShutterDatapoint("LEVEL", 0.0)));
Assert.assertEquals(1.0, converter.convertToBinding(UpDownType.UP, getRollerShutterDatapoint("LEVEL", 0.0)));
}
@Test
public void testValueListByString() throws Exception {
StringTypeConverter converter = new StringTypeConverter();
Assert.assertEquals(new StringType("0"),
converter.convertFromBinding(getValueListVariable("0", "0;10;20;30;40;50")));
Assert.assertEquals(new StringType("10"),
converter.convertFromBinding(getValueListVariable("1", "0;10;20;30;40;50")));
Assert.assertEquals(new StringType("50"),
converter.convertFromBinding(getValueListVariable("5", "0;10;20;30;40;50")));
Assert.assertEquals(new StringType("6"),
converter.convertFromBinding(getValueListVariable("6", "0;10;20;30;40;50")));
Assert.assertEquals(new StringType("10"),
converter.convertFromBinding(getValueListVariable(1, "0;10;20;30;40;50")));
Assert.assertEquals(new StringType("6"),
converter.convertFromBinding(getValueListVariable(6, "0;10;20;30;40;50")));
Assert.assertEquals(new StringType("two"), converter.convertFromBinding(getValueListVariable(1, "one;two")));
Assert.assertEquals(new StringType("one"), converter.convertFromBinding(getValueListVariable(false, "one;two")));
Assert.assertEquals(new StringType("two"), converter.convertFromBinding(getValueListVariable(true, "one;two")));
Assert.assertEquals("0",
converter.convertToBinding(new StringType("0"), getValueListVariable("", "0;10;20;30;40;50")));
Assert.assertEquals("1",
converter.convertToBinding(new StringType("10"), getValueListVariable("", "0;10;20;30;40;50")));
Assert.assertEquals("5",
converter.convertToBinding(new StringType("50"), getValueListVariable("", "0;10;20;30;40;50")));
Assert.assertEquals("2",
converter.convertToBinding(new StringType("three"), getValueListVariable("", "one;two;three")));
Assert.assertEquals("2",
converter.convertToBinding(new StringType("three"), getValueListVariable("1", "one;two;three")));
Assert.assertEquals(2,
converter.convertToBinding(new StringType("three"), getValueListVariable(1, "one;two;three")));
Assert.assertEquals(false,
converter.convertToBinding(new StringType("one"), getValueListVariable(false, "one;two")));
Assert.assertEquals(true,
converter.convertToBinding(new StringType("two"), getValueListVariable(true, "one;two")));
}
@Test
public void testValueListByNumber() throws Exception {
DecimalTypeConverter converter = new DecimalTypeConverter();
Assert.assertEquals(new DecimalType(0),
converter.convertFromBinding(getValueListVariable(0, "0;10;20;30;40;50")));
Assert.assertEquals(new DecimalType(1),
converter.convertFromBinding(getValueListVariable(1, "0;10;20;30;40;50")));
Assert.assertEquals(new DecimalType(5),
converter.convertFromBinding(getValueListVariable(5, "0;10;20;30;40;50")));
Assert.assertEquals(new DecimalType(6),
converter.convertFromBinding(getValueListVariable(6, "0;10;20;30;40;50")));
Assert.assertEquals(new DecimalType(1), converter.convertFromBinding(getValueListVariable(1, "one;two;three")));
Assert.assertEquals(new DecimalType(1),
converter.convertFromBinding(getValueListVariable("1", "one;two;three")));
Assert.assertEquals(new DecimalType(1),
converter.convertFromBinding(getValueListVariable(true, "one;two;three")));
Assert.assertEquals(new DecimalType(0),
converter.convertFromBinding(getValueListVariable(false, "one;two;three")));
Assert.assertEquals(0,
converter.convertToBinding(new DecimalType("0"), getValueListVariable(0, "0;10;20;30;40;50")));
Assert.assertEquals(10,
converter.convertToBinding(new DecimalType("10"), getValueListVariable(0, "0;10;20;30;40;50")));
Assert.assertEquals(50,
converter.convertToBinding(new DecimalType("50"), getValueListVariable(0, "0;10;20;30;40;50")));
Assert.assertEquals(60,
converter.convertToBinding(new DecimalType("60"), getValueListVariable(0, "0;10;20;30;40;50")));
Assert.assertEquals(60,
converter.convertToBinding(new DecimalType("60"), getValueListVariable(1, "0;10;20;30;40;50")));
Assert.assertEquals(1,
converter.convertToBinding(new DecimalType("1"), getValueListVariable(1, "one;two;three")));
Assert.assertEquals("1.0",
converter.convertToBinding(new DecimalType("1"), getValueListVariable("1", "one;two;three")));
Assert.assertEquals(true,
converter.convertToBinding(new DecimalType("1"), getValueListVariable(true, "one;two;three")));
Assert.assertEquals(false,
converter.convertToBinding(new DecimalType("0"), getValueListVariable(true, "one;two;three")));
}
}
| abrenk/openhab | bundles/binding/org.openhab.binding.homematic.test/src/test/java/org/openhab/binding/homematic/test/state/ConverterTest.java | Java | epl-1.0 | 36,481 |
/**
* Copyright (c) 2010-2015, 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.koubachi.internal;
import org.openhab.binding.koubachi.KoubachiBindingProvider;
import org.openhab.binding.koubachi.internal.api.KoubachiResourceType;
import org.openhab.core.binding.BindingConfig;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.DateTimeItem;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.model.item.binding.AbstractGenericBindingProvider;
import org.openhab.model.item.binding.BindingConfigParseException;
/**
* <p>This class can parse information from the generic binding format and
* provides Koubachi binding information from it. It registers as a
* {@link KoubachiBindingProvider} service as well.</p>
*
* <p>Here are some examples for valid binding configuration strings:
* <ul>
* <li><code>{ koubachi="device:00066680190e:virtualBatteryLevel" }</code></li>
* <li><code>{ koubachi="device:00066680190e:nextTransmission" } </code></li>
* <li><code>{ koubachi="plant:129892:vdmMistLevel" }</code><li>
* <li><code>{ koubachi="plant:129892:vdmWaterInstruction" }</code><li>
* </ul>
*
* @author Thomas.Eichstaedt-Engelen
* @since 1.2.0
*/
public class KoubachiGenericBindingProvider extends AbstractGenericBindingProvider implements KoubachiBindingProvider {
/**
* {@inheritDoc}
*/
public String getBindingType() {
return "koubachi";
}
/**
* @{inheritDoc}
*/
@Override
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException {
if (!(item instanceof NumberItem || item instanceof StringItem || item instanceof DateTimeItem
|| item instanceof SwitchItem)) {
throw new BindingConfigParseException("item '" + item.getName()
+ "' is of type '" + item.getClass().getSimpleName()
+ "', only Number-, String-, DateTime- and SwitchItems are allowed - please check your *.items configuration");
}
}
/**
* {@inheritDoc}
*/
@Override
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException {
super.processBindingConfiguration(context, item, bindingConfig);
String[] configParts = bindingConfig.split(":");
if (configParts.length < 3 || configParts.length > 4) {
throw new BindingConfigParseException("A Koubachi binding configuration for a property must consist of three or four parts - please verify your *.items file");
} else if (configParts[2].equals("action") && configParts.length != 4) {
throw new BindingConfigParseException("A Koubachi binding configuration for an action must consist of four parts - please verify your *.items file");
}
KoubachiBindingConfig config = new KoubachiBindingConfig();
config.resourceType = KoubachiResourceType.valueOf(configParts[0].toUpperCase());
config.resourceId = configParts[1];
if (configParts.length == 3) {
// this is a binding for a property
config.propertyName = configParts[2];
} else {
// this is a binding for a care action
config.actionType = configParts[3];
}
addBindingConfig(item, config);
}
/**
* {@inheritDoc}
*/
@Override
public KoubachiResourceType getResourceType(String itemName) {
KoubachiBindingConfig config = (KoubachiBindingConfig) bindingConfigs.get(itemName);
return config != null ? config.resourceType: null;
}
/**
* {@inheritDoc}
*/
@Override
public String getResourceId(String itemName) {
KoubachiBindingConfig config = (KoubachiBindingConfig) bindingConfigs.get(itemName);
return config != null ? config.resourceId: null;
}
/**
* {@inheritDoc}
*/
@Override
public String getPropertyName(String itemName) {
KoubachiBindingConfig config = (KoubachiBindingConfig) bindingConfigs.get(itemName);
return config != null ? config.propertyName: null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCareAction(String itemName) {
KoubachiBindingConfig config = (KoubachiBindingConfig) bindingConfigs.get(itemName);
return config != null ? config.actionType != null: false;
}
/**
* {@inheritDoc}
*/
@Override
public String getActionType(String itemName) {
KoubachiBindingConfig config = (KoubachiBindingConfig) bindingConfigs.get(itemName);
return config != null ? config.actionType: null;
}
/**
* @author Thomas.Eichstaedt-Engelen
* @since 1.2.0
*/
class KoubachiBindingConfig implements BindingConfig {
KoubachiResourceType resourceType;
String resourceId;
String propertyName;
String actionType;
@Override
public String toString() {
return "KoubachiBindingConfig [resourceType=" + resourceType
+ ", resourceId=" + resourceId + ", propertyName="
+ propertyName + ", actionType=" + actionType + "]";
}
}
}
| abrenk/openhab | bundles/binding/org.openhab.binding.koubachi/src/main/java/org/openhab/binding/koubachi/internal/KoubachiGenericBindingProvider.java | Java | epl-1.0 | 5,133 |
/**
* Module dependencies.
*/
var assert = require('assert')
, http = require('http');
var server = http.createServer(function(req, res){
if (req.method === 'GET') {
if (req.url === '/delay') {
setTimeout(function(){
res.writeHead(200, {});
res.end('delayed');
}, 200);
} else {
var body = JSON.stringify({ name: 'tj' });
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf8',
'Content-Length': body.length
});
res.end(body);
}
} else {
var body = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ body += chunk });
req.on('end', function(){
res.writeHead(200, {});
res.end(req.url + ' ' + body);
});
}
});
var delayedServer = http.createServer(function(req, res){
res.writeHead(200);
res.end('it worked');
});
var oldListen = delayedServer.listen;
delayedServer.listen = function(){
var args = arguments;
setTimeout(function(){
oldListen.apply(delayedServer, args);
}, 100);
};
var runningServer = http.createServer(function(req, res){
res.writeHead(200);
res.end('it worked');
});
runningServer.listen(5554);
module.exports = {
'test assert.response(req, res, fn)': function(beforeExit){
var calls = 0;
assert.response(server, {
url: '/',
method: 'GET'
},{
body: '{"name":"tj"}',
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf8'
}
}, function(res){
++calls;
assert.ok(res);
});
beforeExit(function(){
assert.equal(1, calls);
})
},
'test assert.response(req, fn)': function(beforeExit){
var calls = 0;
assert.response(server, {
url: '/foo'
}, function(res){
++calls;
assert.ok(res.body.indexOf('tj') >= 0, 'Test assert.response() callback');
});
beforeExit(function(){
assert.equal(1, calls);
});
},
'test assert.response() delay': function(beforeExit){
var calls = 0;
assert.response(server,
{ url: '/delay', timeout: 1500 },
{ body: 'delayed' },
function(){
++calls;
});
beforeExit(function(){
assert.equal(1, calls);
});
},
'test assert.response() regexp': function(beforeExit){
var calls = 0;
assert.response(server,
{ url: '/foo', method: 'POST', data: 'foobar' },
{ body: /^\/foo foo(bar)?/ },
function(){
++calls;
});
beforeExit(function(){
assert.equal(1, calls);
});
},
'test assert.response() regexp headers': function(beforeExit){
var calls = 0;
assert.response(server,
{ url: '/' },
{ body: '{"name":"tj"}', headers: { 'Content-Type': /^application\/json/ } },
function(){
++calls;
});
beforeExit(function(){
assert.equal(1, calls);
});
},
// [!] if this test doesn't pass, an uncaught ECONNREFUSED will display
'test assert.response() with deferred listen()': function(beforeExit){
var calls = 0;
assert.response(delayedServer,
{ url: '/' },
{ body: 'it worked' },
function(){
++calls;
});
beforeExit(function(){
assert.equal(1, calls);
});
},
'test assert.response() with already running server': function(beforeExit){
var calls = 0;
assert.response(runningServer,
{ url: '/' },
{ body: 'it worked' },
function(){
++calls;
});
beforeExit(function(){
assert.equal(1, calls);
});
}
};
| daslicht/TimberExperiments | wp-content/themes/mwt/node_modules/grunt-contrib-nodeunit/node_modules/nodeunit/deps/ejs/node_modules/expresso/test/http.test.js | JavaScript | gpl-2.0 | 3,593 |
/* arch/arm/mach-msm/proc_comm.h
*
* Copyright (c) 2007-2009,2011 The Linux Foundation. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef _ARCH_ARM_MACH_MSM_MSM_PROC_COMM_H_
#define _ARCH_ARM_MACH_MSM_MSM_PROC_COMM_H_
enum {
PCOM_CMD_IDLE = 0x0,
PCOM_CMD_DONE,
PCOM_RESET_APPS,
PCOM_RESET_CHIP,
PCOM_CONFIG_NAND_MPU,
PCOM_CONFIG_USB_CLKS,
PCOM_GET_POWER_ON_STATUS,
PCOM_GET_WAKE_UP_STATUS,
PCOM_GET_BATT_LEVEL,
PCOM_CHG_IS_CHARGING,
PCOM_POWER_DOWN,
PCOM_USB_PIN_CONFIG,
PCOM_USB_PIN_SEL,
PCOM_SET_RTC_ALARM,
PCOM_NV_READ,
PCOM_NV_WRITE,
PCOM_GET_UUID_HIGH,
PCOM_GET_UUID_LOW,
PCOM_GET_HW_ENTROPY,
PCOM_RPC_GPIO_TLMM_CONFIG_REMOTE,
PCOM_CLKCTL_RPC_ENABLE,
PCOM_CLKCTL_RPC_DISABLE,
PCOM_CLKCTL_RPC_RESET,
PCOM_CLKCTL_RPC_SET_FLAGS,
PCOM_CLKCTL_RPC_SET_RATE,
PCOM_CLKCTL_RPC_MIN_RATE,
PCOM_CLKCTL_RPC_MAX_RATE,
PCOM_CLKCTL_RPC_RATE,
PCOM_CLKCTL_RPC_PLL_REQUEST,
PCOM_CLKCTL_RPC_ENABLED,
PCOM_VREG_SWITCH,
PCOM_VREG_SET_LEVEL,
PCOM_GPIO_TLMM_CONFIG_GROUP,
PCOM_GPIO_TLMM_UNCONFIG_GROUP,
PCOM_NV_WRITE_BYTES_4_7,
PCOM_CONFIG_DISP,
PCOM_GET_FTM_BOOT_COUNT,
PCOM_RPC_GPIO_TLMM_CONFIG_EX,
PCOM_PM_MPP_CONFIG,
PCOM_GPIO_IN,
PCOM_GPIO_OUT,
PCOM_RESET_MODEM,
PCOM_RESET_CHIP_IMM,
PCOM_PM_VID_EN,
PCOM_VREG_PULLDOWN,
PCOM_GET_MODEM_VERSION,
PCOM_CLK_REGIME_SEC_RESET,
PCOM_CLK_REGIME_SEC_RESET_ASSERT,
PCOM_CLK_REGIME_SEC_RESET_DEASSERT,
PCOM_CLK_REGIME_SEC_PLL_REQUEST_WRP,
PCOM_CLK_REGIME_SEC_ENABLE,
PCOM_CLK_REGIME_SEC_DISABLE,
PCOM_CLK_REGIME_SEC_IS_ON,
PCOM_CLK_REGIME_SEC_SEL_CLK_INV,
PCOM_CLK_REGIME_SEC_SEL_CLK_SRC,
PCOM_CLK_REGIME_SEC_SEL_CLK_DIV,
PCOM_CLK_REGIME_SEC_ICODEC_CLK_ENABLE,
PCOM_CLK_REGIME_SEC_ICODEC_CLK_DISABLE,
PCOM_CLK_REGIME_SEC_SEL_SPEED,
PCOM_CLK_REGIME_SEC_CONFIG_GP_CLK_WRP,
PCOM_CLK_REGIME_SEC_CONFIG_MDH_CLK_WRP,
PCOM_CLK_REGIME_SEC_USB_XTAL_ON,
PCOM_CLK_REGIME_SEC_USB_XTAL_OFF,
PCOM_CLK_REGIME_SEC_SET_QDSP_DME_MODE,
PCOM_CLK_REGIME_SEC_SWITCH_ADSP_CLK,
PCOM_CLK_REGIME_SEC_GET_MAX_ADSP_CLK_KHZ,
PCOM_CLK_REGIME_SEC_GET_I2C_CLK_KHZ,
PCOM_CLK_REGIME_SEC_MSM_GET_CLK_FREQ_KHZ,
PCOM_CLK_REGIME_SEC_SEL_VFE_SRC,
PCOM_CLK_REGIME_SEC_MSM_SEL_CAMCLK,
PCOM_CLK_REGIME_SEC_MSM_SEL_LCDCLK,
PCOM_CLK_REGIME_SEC_VFE_RAIL_OFF,
PCOM_CLK_REGIME_SEC_VFE_RAIL_ON,
PCOM_CLK_REGIME_SEC_GRP_RAIL_OFF,
PCOM_CLK_REGIME_SEC_GRP_RAIL_ON,
PCOM_CLK_REGIME_SEC_VDC_RAIL_OFF,
PCOM_CLK_REGIME_SEC_VDC_RAIL_ON,
PCOM_CLK_REGIME_SEC_LCD_CTRL,
PCOM_CLK_REGIME_SEC_REGISTER_FOR_CPU_RESOURCE,
PCOM_CLK_REGIME_SEC_DEREGISTER_FOR_CPU_RESOURCE,
PCOM_CLK_REGIME_SEC_RESOURCE_REQUEST_WRP,
PCOM_CLK_REGIME_MSM_SEC_SEL_CLK_OWNER,
PCOM_CLK_REGIME_SEC_DEVMAN_REQUEST_WRP,
PCOM_GPIO_CONFIG,
PCOM_GPIO_CONFIGURE_GROUP,
PCOM_GPIO_TLMM_SET_PORT,
PCOM_GPIO_TLMM_CONFIG_EX,
PCOM_SET_FTM_BOOT_COUNT,
PCOM_RESERVED0,
PCOM_RESERVED1,
PCOM_CUSTOMER_CMD1,
PCOM_CUSTOMER_CMD2,
PCOM_CUSTOMER_CMD3,
PCOM_CLK_REGIME_ENTER_APPSBL_CHG_MODE,
PCOM_CLK_REGIME_EXIT_APPSBL_CHG_MODE,
PCOM_CLK_REGIME_SEC_RAIL_DISABLE,
PCOM_CLK_REGIME_SEC_RAIL_ENABLE,
PCOM_CLK_REGIME_SEC_RAIL_CONTROL,
PCOM_SET_SW_WATCHDOG_STATE,
PCOM_PM_MPP_CONFIG_DIGITAL_INPUT,
PCOM_PM_MPP_CONFIG_I_SINK,
PCOM_RESERVED_101,
PCOM_MSM_HSUSB_PHY_RESET,
PCOM_GET_BATT_MV_LEVEL,
PCOM_CHG_USB_IS_PC_CONNECTED,
PCOM_CHG_USB_IS_CHARGER_CONNECTED,
PCOM_CHG_USB_IS_DISCONNECTED,
PCOM_CHG_USB_IS_AVAILABLE,
PCOM_CLK_REGIME_SEC_MSM_SEL_FREQ,
PCOM_CLK_REGIME_SEC_SET_PCLK_AXI_POLICY,
PCOM_CLKCTL_RPC_RESET_ASSERT,
PCOM_CLKCTL_RPC_RESET_DEASSERT,
PCOM_CLKCTL_RPC_RAIL_ON,
PCOM_CLKCTL_RPC_RAIL_OFF,
PCOM_CLKCTL_RPC_RAIL_ENABLE,
PCOM_CLKCTL_RPC_RAIL_DISABLE,
PCOM_CLKCTL_RPC_RAIL_CONTROL,
PCOM_CLKCTL_RPC_MIN_MSMC1,
PCOM_CLKCTL_RPC_SRC_REQUEST,
PCOM_NPA_INIT,
PCOM_NPA_ISSUE_REQUIRED_REQUEST,
PCOM_CLKCTL_RPC_SET_EXT_CONFIG,
};
enum {
PCOM_OEM_FIRST_CMD = 0x10000000,
PCOM_OEM_TEST_CMD = PCOM_OEM_FIRST_CMD,
/* add OEM PROC COMM commands here */
PCOM_OEM_LAST = PCOM_OEM_TEST_CMD,
};
enum {
PCOM_INVALID_STATUS = 0x0,
PCOM_READY,
PCOM_CMD_RUNNING,
PCOM_CMD_SUCCESS,
PCOM_CMD_FAIL,
PCOM_CMD_FAIL_FALSE_RETURNED,
PCOM_CMD_FAIL_CMD_OUT_OF_BOUNDS_SERVER,
PCOM_CMD_FAIL_CMD_OUT_OF_BOUNDS_CLIENT,
PCOM_CMD_FAIL_CMD_UNREGISTERED,
PCOM_CMD_FAIL_CMD_LOCKED,
PCOM_CMD_FAIL_SERVER_NOT_YET_READY,
PCOM_CMD_FAIL_BAD_DESTINATION,
PCOM_CMD_FAIL_SERVER_RESET,
PCOM_CMD_FAIL_SMSM_NOT_INIT,
PCOM_CMD_FAIL_PROC_COMM_BUSY,
PCOM_CMD_FAIL_PROC_COMM_NOT_INIT,
};
#ifdef CONFIG_MSM_PROC_COMM
void msm_proc_comm_reset_modem_now(void);
int msm_proc_comm(unsigned cmd, unsigned *data1, unsigned *data2);
#else
static inline void msm_proc_comm_reset_modem_now(void) { }
static inline int msm_proc_comm(unsigned cmd, unsigned *data1, unsigned *data2)
{ return 0; }
#endif
#endif
| koxda/android_kernel_samsung_msm8660-common | arch/arm/mach-msm/proc_comm.h | C | gpl-2.0 | 5,158 |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_test_crc32.h
*
* Include file for SDL test framework.
*
* This code is a part of the SDL2_test library, not the main SDL library.
*/
/*
Implements CRC32 calculations (default output is Perl String::CRC32 compatible).
*/
#ifndef SDL_test_crc32_h_
#define SDL_test_crc32_h_
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* ------------ Definitions --------- */
/* Definition shared by all CRC routines */
#ifndef CrcUint32
#define CrcUint32 unsigned int
#endif
#ifndef CrcUint8
#define CrcUint8 unsigned char
#endif
#ifdef ORIGINAL_METHOD
#define CRC32_POLY 0x04c11db7 /* AUTODIN II, Ethernet, & FDDI */
#else
#define CRC32_POLY 0xEDB88320 /* Perl String::CRC32 compatible */
#endif
/**
* Data structure for CRC32 (checksum) computation
*/
typedef struct {
CrcUint32 crc32_table[256]; /* CRC table */
} SDLTest_Crc32Context;
/* ---------- Function Prototypes ------------- */
/**
* \brief Initialize the CRC context
*
* Note: The function initializes the crc table required for all crc calculations.
*
* \param crcContext pointer to context variable
*
* \returns 0 for OK, -1 on error
*
*/
int SDLTest_Crc32Init(SDLTest_Crc32Context * crcContext);
/**
* \brief calculate a crc32 from a data block
*
* \param crcContext pointer to context variable
* \param inBuf input buffer to checksum
* \param inLen length of input buffer
* \param crc32 pointer to Uint32 to store the final CRC into
*
* \returns 0 for OK, -1 on error
*
*/
int SDLTest_Crc32Calc(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUint32 inLen, CrcUint32 *crc32);
/* Same routine broken down into three steps */
int SDLTest_Crc32CalcStart(SDLTest_Crc32Context * crcContext, CrcUint32 *crc32);
int SDLTest_Crc32CalcEnd(SDLTest_Crc32Context * crcContext, CrcUint32 *crc32);
int SDLTest_Crc32CalcBuffer(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUint32 inLen, CrcUint32 *crc32);
/**
* \brief clean up CRC context
*
* \param crcContext pointer to context variable
*
* \returns 0 for OK, -1 on error
*
*/
int SDLTest_Crc32Done(SDLTest_Crc32Context * crcContext);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_test_crc32_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| z-10/digger | windows/externals/SDL2/include/SDL_test_crc32.h | C | gpl-2.0 | 3,385 |
/* include/linux/max1187x.h
*
* Copyright (c)2012 Maxim Integrated Products, Inc.
*
* Driver Version: 3.0.7
* Release Date: Feb 22, 2013
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef __MAX1187X_H
#define __MAX1187X_H
#define MAX1187X_NAME "max1187x"
#define MAX1187X_TOUCH MAX1187X_NAME "_touchscreen_0"
#define MAX1187X_KEY MAX1187X_NAME "_key_0"
#define MAX1187X_LOG_NAME "[TP] "
#define MAX_WORDS_COMMAND 9
#define MAX_WORDS_REPORT 245
#define MAX_WORDS_COMMAND_ALL (15 * MAX_WORDS_COMMAND)
#define MAX1187X_NUM_FW_MAPPINGS_MAX 5
#define MAX1187X_TOUCH_COUNT_MAX 10
#define MAX1187X_TOUCH_REPORT_RAW 0x0800
#define MAX1187X_TOUCH_REPORT_BASIC 0x0801
#define MAX1187X_TOUCH_REPORT_EXTENDED 0x0802
#define MAX_REPORT_READERS 5
#define DEBUG_STRING_LEN_MAX 60
#define MAX_FW_RETRIES 5
#define MAX1187X_PI 205887
#define MAX1187X_TOUCH_CONFIG_MAX 65
#define MAX1187X_CALIB_TABLE_MAX 74
#define MAX1187X_PRIVATE_CONFIG_MAX 34
#define MAX1187X_LOOKUP_TABLE_MAX 8
#define MAX1187X_IMAGE_FACTOR_MAX 460
#define MAX1187X_NO_BASELINE 0
#define MAX1187X_FIX_BASELINE 1
#define MAX1187X_AUTO_BASELINE 2
struct max1187x_touch_report_header {
u16 header;
u16 report_id;
u16 report_size;
u16 touch_count:4;
u16 touch_status:4;
u16 reserved0:5;
u16 cycles:1;
u16 reserved1:2;
u16 button0:1;
u16 button1:1;
u16 button2:1;
u16 button3:1;
u16 reserved2:12;
u16 framecounter;
};
struct max1187x_touch_report_basic {
u16 finger_id:4;
u16 reserved0:4;
u16 finger_status:4;
u16 reserved1:4;
u16 x:12;
u16 reserved2:4;
u16 y:12;
u16 reserved3:4;
u16 z;
};
struct max1187x_touch_report_extended {
u16 finger_id:4;
u16 reserved0:4;
u16 finger_status:4;
u16 reserved1:4;
u16 x:12;
u16 reserved2:4;
u16 y:12;
u16 reserved3:4;
u16 z;
s16 xspeed;
s16 yspeed;
s8 xpixel;
s8 ypixel;
u16 area;
u16 xmin;
u16 xmax;
u16 ymin;
u16 ymax;
};
struct max1187x_board_config {
u16 config_id;
u16 chip_id;
u8 major_ver;
u8 minor_ver;
u8 protocol_ver;
u16 vendor_pin;
u16 config_touch[MAX1187X_TOUCH_CONFIG_MAX];
u16 config_cal[MAX1187X_CALIB_TABLE_MAX];
u16 config_private[MAX1187X_PRIVATE_CONFIG_MAX];
u16 config_lin_x[MAX1187X_LOOKUP_TABLE_MAX];
u16 config_lin_y[MAX1187X_LOOKUP_TABLE_MAX];
u16 config_ifactor[MAX1187X_IMAGE_FACTOR_MAX];
};
struct max1187x_virtual_key {
int index;
int keycode;
int x_position;
int y_position;
};
struct max1187x_fw_mapping {
u32 chip_id;
char *filename;
u32 filesize;
u32 filecrc16;
u32 file_codesize;
};
struct max1187x_pdata {
struct max1187x_board_config *fw_config;
u32 gpio_tirq;
u32 gpio_reset;
u32 num_fw_mappings;
struct max1187x_fw_mapping fw_mapping[MAX1187X_NUM_FW_MAPPINGS_MAX];
u32 defaults_allow;
u32 default_config_id;
u32 default_chip_id;
u32 i2c_words;
#define MAX1187X_REVERSE_X 0x0001
#define MAX1187X_REVERSE_Y 0x0002
#define MAX1187X_SWAP_XY 0x0004
u32 coordinate_settings;
u32 panel_min_x;
u32 panel_max_x;
u32 panel_min_y;
u32 panel_max_y;
u32 lcd_x;
u32 lcd_y;
u32 num_rows;
u32 num_cols;
#define MAX1187X_PROTOCOL_A 0
#define MAX1187X_PROTOCOL_B 1
#define MAX1187X_PROTOCOL_CUSTOM1 2
u16 input_protocol;
#define MAX1187X_UPDATE_NONE 0
#define MAX1187X_UPDATE_BIN 1
#define MAX1187X_UPDATE_CONFIG 2
#define MAX1187X_UPDATE_BOTH 3
u8 update_feature;
u8 support_htc_event;
u16 tw_mask;
u32 button_code0;
u32 button_code1;
u32 button_code2;
u32 button_code3;
#define MAX1187X_REPORT_MODE_BASIC 1
#define MAX1187X_REPORT_MODE_EXTEND 2
u8 report_mode;
struct max1187x_virtual_key *button_data;
};
#endif
| AICP/kernel_htc_msm8960-old | include/linux/max1187x.h | C | gpl-2.0 | 4,416 |
package com.siyeh.igtest.abstraction;
public enum PublicMethodNotExposedInInterfaceEnum implements Interface {
a, b, c;
public void baz() {
}
}
| Lekanich/intellij-community | plugins/InspectionGadgets/test/com/siyeh/igtest/abstraction/PublicMethodNotExposedInInterfaceEnum.java | Java | apache-2.0 | 159 |
/*
Uniform v1.7.5
Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC
http://pixelmatrixdesign.com
Requires jQuery 1.4 or newer
Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this
Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/>
and his noSelect plugin. <http://github.com/mathiasbynens/noSelect-jQuery-Plugin>
Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin
License:
MIT License - http://www.opensource.org/licenses/mit-license.php
Enjoy!
*/
(function($) {
$.uniform = {
options: {
selectClass: 'selector',
radioClass: 'radio',
checkboxClass: 'checker',
fileClass: 'uploader',
filenameClass: 'filename',
fileBtnClass: 'action',
fileDefaultText: 'No file selected',
fileBtnText: 'Choose File',
checkedClass: 'checked',
focusClass: 'focus',
disabledClass: 'disabled',
buttonClass: 'button',
activeClass: 'active',
hoverClass: 'hover',
useID: true,
idPrefix: 'uniform',
resetSelector: false,
autoHide: true
},
elements: []
};
if($.browser.msie && $.browser.version < 7){
$.support.selectOpacity = false;
}else{
$.support.selectOpacity = true;
}
$.fn.uniform = function(options) {
options = $.extend($.uniform.options, options);
var el = this;
//code for specifying a reset button
if(options.resetSelector != false){
$(options.resetSelector).mouseup(function(){
function resetThis(){
$.uniform.update(el);
}
setTimeout(resetThis, 10);
});
}
function doInput(elem){
$el = $(elem);
$el.addClass($el.attr("type"));
storeElement(elem);
}
function doTextarea(elem){
$(elem).addClass("uniform");
storeElement(elem);
}
function doButton(elem){
var $el = $(elem);
var divTag = $("<div>"),
spanTag = $("<span>");
divTag.addClass(options.buttonClass);
if(options.useID && $el.attr("id") != "") divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
var btnText;
if($el.is("a") || $el.is("button")){
btnText = $el.text();
}else if($el.is(":submit") || $el.is(":reset") || $el.is("input[type=button]")){
btnText = $el.attr("value");
}
btnText = btnText == "" ? $el.is(":reset") ? "Reset" : "Submit" : btnText;
spanTag.html(btnText);
$el.css("opacity", 0);
$el.wrap(divTag);
$el.wrap(spanTag);
//redefine variables
divTag = $el.closest("div");
spanTag = $el.closest("span");
if($el.is(":disabled")) divTag.addClass(options.disabledClass);
divTag.bind({
"mouseenter.uniform": function(){
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function(){
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function(){
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(e){
if($(e.target).is("span") || $(e.target).is("div")){
if(elem[0].dispatchEvent){
var ev = document.createEvent('MouseEvents');
ev.initEvent( 'click', true, true );
elem[0].dispatchEvent(ev);
}else{
elem[0].click();
}
}
}
});
elem.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
}
});
$.uniform.noSelect(divTag);
storeElement(elem);
}
function doSelect(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.selectClass);
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
var selected = elem.find(":selected:first");
if(selected.length == 0){
selected = elem.find("option:first");
}
spanTag.html(selected.html());
elem.css('opacity', 0);
elem.wrap(divTag);
elem.before(spanTag);
//redefine variables
divTag = elem.parent("div");
spanTag = elem.siblings("span");
elem.bind({
"change.uniform": function() {
spanTag.text(elem.find(":selected").html());
divTag.removeClass(options.activeClass);
},
"focus.uniform": function() {
divTag.addClass(options.focusClass);
},
"blur.uniform": function() {
divTag.removeClass(options.focusClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"keyup.uniform": function(){
spanTag.text(elem.find(":selected").html());
}
});
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(spanTag);
storeElement(elem);
}
function doCheckbox(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.checkboxClass);
//assign the id of the element
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).attr("checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span.
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).attr("checked")){
//box is checked by default, check our box
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doRadio(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.radioClass);
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).attr("checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span
var classes = options.radioClass.split(" ")[0];
$("." + classes + " span." + options.checkedClass + ":has([name='" + $(elem).attr('name') + "'])").removeClass(options.checkedClass);
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchend.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform touchbegin.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform touchend.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).attr("checked")){
//box is checked by default, check span
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doFile(elem){
//sanitize input
var $el = $(elem);
var divTag = $('<div />'),
filenameTag = $('<span>'+options.fileDefaultText+'</span>'),
btnTag = $('<span>'+options.fileBtnText+'</span>');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.fileClass);
filenameTag.addClass(options.filenameClass);
btnTag.addClass(options.fileBtnClass);
if(options.useID && $el.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
}
//wrap with the proper elements
$el.wrap(divTag);
$el.after(btnTag);
$el.after(filenameTag);
//redefine variables
divTag = $el.closest("div");
filenameTag = $el.siblings("."+options.filenameClass);
btnTag = $el.siblings("."+options.fileBtnClass);
//set the size
if(!$el.attr("size")){
var divWidth = divTag.width();
//$el.css("width", divWidth);
$el.attr("size", divWidth/10);
}
//actions
var setFilename = function()
{
var filename = $el.val();
if (filename === '')
{
filename = options.fileDefaultText;
}
else
{
filename = filename.split(/[\/\\]+/);
filename = filename[(filename.length-1)];
}
filenameTag.text(filename);
};
// Account for input saved across refreshes
setFilename();
$el
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"mousedown.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
// IE7 doesn't fire onChange until blur or second fire.
if ($.browser.msie){
// IE considers browser chrome blocking I/O, so it
// suspends tiemouts until after the file has been selected.
$el.bind('click.uniform.ie7', function() {
setTimeout(setFilename, 0);
});
}else{
// All other browsers behave properly
$el.bind('change.uniform', setFilename);
}
//handle defaults
if($el.attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(filenameTag);
$.uniform.noSelect(btnTag);
storeElement(elem);
}
$.uniform.restore = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
$(elem).each(function(){
if($(this).is(":checkbox")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is("select")){
//remove sibling span
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is(":radio")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is(":file")){
//remove sibling spans
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is("button, :submit, :reset, a, input[type='button']")){
//unwrap from span and div
$(this).unwrap().unwrap();
}
//unbind events
$(this).unbind(".uniform");
//reset inline style
$(this).css("opacity", "1");
//remove item from list of uniformed elements
var index = $.inArray($(elem), $.uniform.elements);
$.uniform.elements.splice(index, 1);
});
};
function storeElement(elem){
//store this element in our global array
elem = $(elem).get();
if(elem.length > 1){
$.each(elem, function(i, val){
$.uniform.elements.push(val);
});
}else{
$.uniform.elements.push(elem);
}
}
//noSelect v1.0
$.uniform.noSelect = function(elem) {
function f() {
return false;
};
$(elem).each(function() {
this.onselectstart = this.ondragstart = f; // Webkit & IE
$(this)
.mousedown(f) // Webkit & Opera
.css({ MozUserSelect: 'none' }); // Firefox
});
};
$.uniform.update = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
//sanitize input
elem = $(elem);
elem.each(function(){
//do to each item in the selector
//function to reset all classes
var $e = $(this);
if($e.is("select")){
//element is a select
var spanTag = $e.siblings("span");
var divTag = $e.parent("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
//reset current selected text
spanTag.html($e.find(":selected").html());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":checkbox")){
//element is a checkbox
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":radio")){
//element is a radio
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":file")){
var divTag = $e.parent("div");
var filenameTag = $e.siblings(options.filenameClass);
btnTag = $e.siblings(options.fileBtnClass);
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
filenameTag.text($e.val());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":submit") || $e.is(":reset") || $e.is("button") || $e.is("a") || elem.is("input[type=button]")){
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}
});
};
return this.each(function() {
if($.support.selectOpacity){
var elem = $(this);
if(elem.is("select")){
//element is a select
if(elem.attr("multiple") != true){
//element is not a multi-select
if(elem.attr("size") == undefined || elem.attr("size") <= 1){
doSelect(elem);
}
}
}else if(elem.is(":checkbox")){
//element is a checkbox
doCheckbox(elem);
}else if(elem.is(":radio")){
//element is a radio
doRadio(elem);
}else if(elem.is(":file")){
//element is a file upload
doFile(elem);
}else if(elem.is(":text, :password, input[type='email']")){
doInput(elem);
}else if(elem.is("textarea")){
doTextarea(elem);
}else if(elem.is("a") || elem.is(":submit") || elem.is(":reset") || elem.is("button") || elem.is("input[type=button]")){
doButton(elem);
}
}
});
};
})(jQuery); | ptphp/PtTheme | webroot/static/theme/stilearn/js/uniform/jquery.uniform.js | JavaScript | bsd-3-clause | 19,587 |
module VagrantPlugins
module GuestLinux
module Cap
class RSync
def self.rsync_installed(machine)
machine.communicate.test("which rsync")
end
def self.rsync_command(machine)
"sudo rsync"
end
def self.rsync_pre(machine, opts)
machine.communicate.tap do |comm|
comm.sudo("mkdir -p '#{opts[:guestpath]}'")
end
end
def self.rsync_post(machine, opts)
if opts.key?(:chown) && !opts[:chown]
return
end
machine.communicate.sudo(
"find '#{opts[:guestpath]}' " +
"'!' -type l -a " +
"'(' ! -user #{opts[:owner]} -or ! -group #{opts[:group]} ')' -print0 | " +
"xargs -0 -r chown #{opts[:owner]}:#{opts[:group]}")
end
end
end
end
end
| sni/vagrant | plugins/guests/linux/cap/rsync.rb | Ruby | mit | 855 |
/*
* eXide - web-based XQuery IDE
*
* Copyright (C) 2011 Wolfgang Meier
*
* 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/>.
*/
define(function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require('../behaviour').Behaviour;
var CstyleBehaviour = require('./cstyle').CstyleBehaviour;
var XQueryBehaviour = function (parent) {
this.inherit(CstyleBehaviour, ["braces", "parens", "string_dquotes"]); // Get string behaviour
this.parent = parent;
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChars = line.substring(cursor.column, cursor.column + 2);
if (rightChars == '</') {
var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString();
var next_indent = this.$getIndent(session.doc.getLine(cursor.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
}
}
}
return false;
});
// Check for open tag if user enters / and auto-close it.
this.add("slash", "insertion", function (state, action, editor, session, text) {
if (text == "/") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (cursor.column > 0 && line.charAt(cursor.column - 1) == "<") {
line = line.substring(0, cursor.column) + "/" + line.substring(cursor.column);
var lines = session.doc.getAllLines();
lines[cursor.row] = line;
// call mode helper to close the tag if possible
parent.exec("closeTag", lines.join(session.doc.getNewLineCharacter()), cursor.row);
}
}
return false;
});
}
oop.inherits(XQueryBehaviour, Behaviour);
exports.XQueryBehaviour = XQueryBehaviour;
});
| nik3daz/chrome-app-samples | text-editor/lib/ace/mode/behaviour/xquery.js | JavaScript | apache-2.0 | 2,745 |
#define _GNU_SOURCE
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <signal.h>
#include "utils.h"
static void default_xprintf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fflush(stderr);
}
void (*xprintf)(const char *fmt, ...) = default_xprintf;
void barf(const char *fmt, ...)
{
char *str;
int bytes;
va_list arglist;
xprintf("FATAL: ");
va_start(arglist, fmt);
bytes = vasprintf(&str, fmt, arglist);
va_end(arglist);
if (bytes >= 0) {
xprintf("%s\n", str);
free(str);
}
exit(1);
}
void barf_perror(const char *fmt, ...)
{
char *str;
int bytes, err = errno;
va_list arglist;
xprintf("FATAL: ");
va_start(arglist, fmt);
bytes = vasprintf(&str, fmt, arglist);
va_end(arglist);
if (bytes >= 0) {
xprintf("%s: %s\n", str, strerror(err));
free(str);
}
exit(1);
}
| PennPanda/RT-Xen | tools/xenstore/utils.c | C | gpl-2.0 | 983 |
/*
* Copyright (c) 2012, Code Aurora Forum. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef WLAN_QCT_WLANBAP_API_EXT_H
#define WLAN_QCT_WLANBAP_API_EXT_H
/*===========================================================================
W L A N B T - A M P P A L L A Y E R
E X T E R N A L A P I
DESCRIPTION
This file contains the external APIs used by the wlan BT-AMP PAL layer
module.
Copyright (c) 2008 QUALCOMM Incorporated. All Rights Reserved.
Qualcomm Confidential and Proprietary
===========================================================================*/
/*===========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
$Header: /cygdrive/e/Builds/M7201JSDCAAPAD52240B/WM/platform/msm7200/Src/Drivers/SD/ClientDrivers/WLAN/QCT/CORE/BAP/src/bapApiExt.h,v 1.1 2008/11/21 20:29:13 jzmuda Exp jzmuda $ $DateTime: $ $Author: jzmuda $
when who what, where, why
-------- --- ----------------------------------------------------------
10/22/08 jez Created module.
===========================================================================*/
/*===========================================================================
INCLUDE FILES FOR MODULE
===========================================================================*/
/*----------------------------------------------------------------------------
* Include Files
* -------------------------------------------------------------------------*/
// Pick up all the BT-AMP internal definitions
// And underlying supporting types. (Including VOSS, CSR, and...)
#include "bapInternal.h"
/* Pick up the SIRIUS and HAL types */
// Already taken care of, above
//#include "sirApi.h"
//#include "halTypes.h"
/* Pick up the CCM API def'n */
#include "ccmApi.h"
/*----------------------------------------------------------------------------
* Preprocessor Definitions and Constants
* -------------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/*----------------------------------------------------------------------------
* Defines
* -------------------------------------------------------------------------*/
// Temporary
//#define BAP_DEBUG
// How do I get BAP context from voss context?
//#define VOS_GET_BAP_CB(ctx) vos_get_context( VOS_MODULE_ID_BAP, ctx)
// How do I get halHandle from voss context?
//#define VOS_GET_HAL_CB(ctx) vos_get_context( VOS_MODULE_ID_HAL, ctx)
/*----------------------------------------------------------------------------
* Typedefs
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* External declarations for global context
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Function prototypes
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Utility Function prototypes
* -------------------------------------------------------------------------*/
/*==========================================================================
FUNCTION WLANBAP_GetCurrentChannel
DESCRIPTION
Clear out all fields in the BAP context.
DEPENDENCIES
PARAMETERS
IN
pBtampCtx: pointer to the BAP control block
channel: current configured channel number.
activeFlag: flag indicating whether there is an active link.
RETURN VALUE
The result code associated with performing the operation
VOS_STATUS_E_FAULT: pointer to return channel is NULL ; access would cause a page
fault
VOS_STATUS_SUCCESS: Everything is good :)
SIDE EFFECTS
============================================================================*/
VOS_STATUS
WLANBAP_GetCurrentChannel
(
ptBtampContext pBtampCtx,
v_U32_t *channel, // return current channel here
v_U32_t *activeFlag // return active flag here
);
#ifdef __cplusplus
}
#endif
#endif /* #ifndef WLAN_QCT_WLANBAP_API_EXT_H */
| lindsaytheflint/stone | drivers/staging/prima_legacy_new/CORE/BAP/src/bapApiExt.h | C | gpl-2.0 | 5,325 |
/*!
* Chart.js
* http://chartjs.org/
* Version: 1.0.2
*
* Copyright 2015 Nick Downie
* Released under the MIT license
* https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
*/
(function(){
"use strict";
//Declare root variable - window in the browser, global on the server
var root = this,
previous = root.Chart;
//Occupy the global variable of Chart, and create a simple base class
var Chart = function(context){
var chart = this;
this.canvas = context.canvas;
this.ctx = context;
//Variables global to the chart
var computeDimension = function(element,dimension)
{
if (element['offset'+dimension])
{
return element['offset'+dimension];
}
else
{
return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
}
};
var width = this.width = computeDimension(context.canvas,'Width') || context.canvas.width;
var height = this.height = computeDimension(context.canvas,'Height') || context.canvas.height;
width = this.width = context.canvas.width;
height = this.height = context.canvas.height;
this.aspectRatio = this.width / this.height;
//High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
helpers.retinaScale(this);
return this;
};
//Globally expose the defaults to allow for user updating/changing
Chart.defaults = {
global: {
// Boolean - Whether to animate the chart
animation: true,
// Number - Number of animation steps
animationSteps: 60,
// String - Animation easing effect
animationEasing: "easeOutQuart",
// Boolean - If we should show the scale at all
showScale: true,
// Boolean - If we want to override with a hard coded scale
scaleOverride: false,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: null,
// Number - The value jump in the hard coded scale
scaleStepWidth: null,
// Number - The scale starting value
scaleStartValue: null,
// String - Colour of the scale line
scaleLineColor: "rgba(0,0,0,.1)",
// Number - Pixel width of the scale line
scaleLineWidth: 1,
// Boolean - Whether to show labels on the scale
scaleShowLabels: true,
// Interpolated JS string - can access value
scaleLabel: "<%=value%>",
// Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
scaleIntegersOnly: true,
// Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: false,
// String - Scale label font declaration for the scale label
scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Scale label font size in pixels
scaleFontSize: 12,
// String - Scale label font weight style
scaleFontStyle: "normal",
// String - Scale label font colour
scaleFontColor: "#666",
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: false,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
// Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
showTooltips: true,
// Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
customTooltips: false,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// String - Tooltip title template
tooltipTitleTemplate: "<%= label%>",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for single tooltips
multiTooltipTemplate: "<%= value %>",
// String - Colour behind the legend colour block
multiTooltipKeyBackground: '#fff',
// Array - A list of colors to use as the defaults
segmentColorDefault: ["#A6CEE3", "#1F78B4", "#B2DF8A", "#33A02C", "#FB9A99", "#E31A1C", "#FDBF6F", "#FF7F00", "#CAB2D6", "#6A3D9A", "#B4B482", "#B15928" ],
// Array - A list of highlight colors to use as the defaults
segmentHighlightColorDefaults: [ "#CEF6FF", "#47A0DC", "#DAFFB2", "#5BC854", "#FFC2C1", "#FF4244", "#FFE797", "#FFA728", "#F2DAFE", "#9265C2", "#DCDCAA", "#D98150" ],
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){}
}
};
//Create a dictionary of chart types, to allow for extension of existing types
Chart.types = {};
//Global Chart helpers object for utility methods and classes
var helpers = Chart.helpers = {};
//-- Basic js utility methods
var each = helpers.each = function(loopable,callback,self){
var additionalArgs = Array.prototype.slice.call(arguments, 3);
// Check to see if null or undefined firstly.
if (loopable){
if (loopable.length === +loopable.length){
var i;
for (i=0; i<loopable.length; i++){
callback.apply(self,[loopable[i], i].concat(additionalArgs));
}
}
else{
for (var item in loopable){
callback.apply(self,[loopable[item],item].concat(additionalArgs));
}
}
}
},
clone = helpers.clone = function(obj){
var objClone = {};
each(obj,function(value,key){
if (obj.hasOwnProperty(key)){
objClone[key] = value;
}
});
return objClone;
},
extend = helpers.extend = function(base){
each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
each(extensionObject,function(value,key){
if (extensionObject.hasOwnProperty(key)){
base[key] = value;
}
});
});
return base;
},
merge = helpers.merge = function(base,master){
//Merge properties in left object over to a shallow clone of object right.
var args = Array.prototype.slice.call(arguments,0);
args.unshift({});
return extend.apply(null, args);
},
indexOf = helpers.indexOf = function(arrayToSearch, item){
if (Array.prototype.indexOf) {
return arrayToSearch.indexOf(item);
}
else{
for (var i = 0; i < arrayToSearch.length; i++) {
if (arrayToSearch[i] === item) return i;
}
return -1;
}
},
where = helpers.where = function(collection, filterCallback){
var filtered = [];
helpers.each(collection, function(item){
if (filterCallback(item)){
filtered.push(item);
}
});
return filtered;
},
findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
// Default to start of the array
if (!startIndex){
startIndex = -1;
}
for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)){
return currentItem;
}
}
},
findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
// Default to end of the array
if (!startIndex){
startIndex = arrayToSearch.length;
}
for (var i = startIndex - 1; i >= 0; i--) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)){
return currentItem;
}
}
},
inherits = helpers.inherits = function(extensions){
//Basic javascript inheritance based on the model created in Backbone.js
var parent = this;
var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
var Surrogate = function(){ this.constructor = ChartElement;};
Surrogate.prototype = parent.prototype;
ChartElement.prototype = new Surrogate();
ChartElement.extend = inherits;
if (extensions) extend(ChartElement.prototype, extensions);
ChartElement.__super__ = parent.prototype;
return ChartElement;
},
noop = helpers.noop = function(){},
uid = helpers.uid = (function(){
var id=0;
return function(){
return "chart-" + id++;
};
})(),
warn = helpers.warn = function(str){
//Method for warning of errors
if (window.console && typeof window.console.warn === "function") console.warn(str);
},
amd = helpers.amd = (typeof define === 'function' && define.amd),
//-- Math methods
isNumber = helpers.isNumber = function(n){
return !isNaN(parseFloat(n)) && isFinite(n);
},
max = helpers.max = function(array){
return Math.max.apply( Math, array );
},
min = helpers.min = function(array){
return Math.min.apply( Math, array );
},
cap = helpers.cap = function(valueToCap,maxValue,minValue){
if(isNumber(maxValue)) {
if( valueToCap > maxValue ) {
return maxValue;
}
}
else if(isNumber(minValue)){
if ( valueToCap < minValue ){
return minValue;
}
}
return valueToCap;
},
getDecimalPlaces = helpers.getDecimalPlaces = function(num){
if (num%1!==0 && isNumber(num)){
var s = num.toString();
if(s.indexOf("e-") < 0){
// no exponent, e.g. 0.01
return s.split(".")[1].length;
}
else if(s.indexOf(".") < 0) {
// no decimal point, e.g. 1e-9
return parseInt(s.split("e-")[1]);
}
else {
// exponent and decimal point, e.g. 1.23e-9
var parts = s.split(".")[1].split("e-");
return parts[0].length + parseInt(parts[1]);
}
}
else {
return 0;
}
},
toRadians = helpers.radians = function(degrees){
return degrees * (Math.PI/180);
},
// Gets the angle from vertical upright to the point about a centre.
getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
var distanceFromXCenter = anglePoint.x - centrePoint.x,
distanceFromYCenter = anglePoint.y - centrePoint.y,
radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
//If the segment is in the top left quadrant, we need to add another rotation to the angle
if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
angle += Math.PI*2;
}
return {
angle: angle,
distance: radialDistanceFromCenter
};
},
aliasPixel = helpers.aliasPixel = function(pixelWidth){
return (pixelWidth % 2 === 0) ? 0 : 0.5;
},
splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
//Props to Rob Spencer at scaled innovation for his post on splining between points
//http://scaledinnovation.com/analytics/splines/aboutSplines.html
var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
fa=t*d01/(d01+d12),// scaling factor for triangle Ta
fb=t*d12/(d01+d12);
return {
inner : {
x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
},
outer : {
x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
}
};
},
calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
return Math.floor(Math.log(val) / Math.LN10);
},
calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
//Set a minimum step of two - a point at the top of the graph, and a point at the base
var minSteps = 2,
maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
skipFitting = (minSteps >= maxSteps);
// Filter out null values since these would min() to zero
var values = [];
each(valuesArray, function( v ){
v == null || values.push( v );
});
var minValue = min(values),
maxValue = max(values);
// We need some degree of separation here to calculate the scales if all the values are the same
// Adding/minusing 0.5 will give us a range of 1.
if (maxValue === minValue){
maxValue += 0.5;
// So we don't end up with a graph with a negative start value if we've said always start from zero
if (minValue >= 0.5 && !startFromZero){
minValue -= 0.5;
}
else{
// Make up a whole number above the values
maxValue += 0.5;
}
}
var valueRange = Math.abs(maxValue - minValue),
rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
graphRange = graphMax - graphMin,
stepValue = Math.pow(10, rangeOrderOfMagnitude),
numberOfSteps = Math.round(graphRange / stepValue);
//If we have more space on the graph we'll use it to give more definition to the data
while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
if(numberOfSteps > maxSteps){
stepValue *=2;
numberOfSteps = Math.round(graphRange/stepValue);
// Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
if (numberOfSteps % 1 !== 0){
skipFitting = true;
}
}
//We can fit in double the amount of scale points on the scale
else{
//If user has declared ints only, and the step value isn't a decimal
if (integersOnly && rangeOrderOfMagnitude >= 0){
//If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
if(stepValue/2 % 1 === 0){
stepValue /=2;
numberOfSteps = Math.round(graphRange/stepValue);
}
//If it would make it a float break out of the loop
else{
break;
}
}
//If the scale doesn't have to be an int, make the scale more granular anyway.
else{
stepValue /=2;
numberOfSteps = Math.round(graphRange/stepValue);
}
}
}
if (skipFitting){
numberOfSteps = minSteps;
stepValue = graphRange / numberOfSteps;
}
return {
steps : numberOfSteps,
stepValue : stepValue,
min : graphMin,
max : graphMin + (numberOfSteps * stepValue)
};
},
/* jshint ignore:start */
// Blows up jshint errors based on the new Function constructor
//Templating methods
//Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
template = helpers.template = function(templateString, valuesObject){
// If templateString is function rather than string-template - call the function for valuesObject
if(templateString instanceof Function){
return templateString(valuesObject);
}
var cache = {};
function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'") +
"');}return p.join('');"
);
// Provide some basic currying to the user
return data ? fn( data ) : fn;
}
return tmpl(templateString,valuesObject);
},
/* jshint ignore:end */
generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
var labelsArray = new Array(numberOfSteps);
if (templateString){
each(labelsArray,function(val,index){
labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
});
}
return labelsArray;
},
//--Animation methods
//Easing functions adapted from Robert Penner's easing equations
//http://www.robertpenner.com/easing/
easingEffects = helpers.easingEffects = {
linear: function (t) {
return t;
},
easeInQuad: function (t) {
return t * t;
},
easeOutQuad: function (t) {
return -1 * t * (t - 2);
},
easeInOutQuad: function (t) {
if ((t /= 1 / 2) < 1){
return 1 / 2 * t * t;
}
return -1 / 2 * ((--t) * (t - 2) - 1);
},
easeInCubic: function (t) {
return t * t * t;
},
easeOutCubic: function (t) {
return 1 * ((t = t / 1 - 1) * t * t + 1);
},
easeInOutCubic: function (t) {
if ((t /= 1 / 2) < 1){
return 1 / 2 * t * t * t;
}
return 1 / 2 * ((t -= 2) * t * t + 2);
},
easeInQuart: function (t) {
return t * t * t * t;
},
easeOutQuart: function (t) {
return -1 * ((t = t / 1 - 1) * t * t * t - 1);
},
easeInOutQuart: function (t) {
if ((t /= 1 / 2) < 1){
return 1 / 2 * t * t * t * t;
}
return -1 / 2 * ((t -= 2) * t * t * t - 2);
},
easeInQuint: function (t) {
return 1 * (t /= 1) * t * t * t * t;
},
easeOutQuint: function (t) {
return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
},
easeInOutQuint: function (t) {
if ((t /= 1 / 2) < 1){
return 1 / 2 * t * t * t * t * t;
}
return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
},
easeInSine: function (t) {
return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
},
easeOutSine: function (t) {
return 1 * Math.sin(t / 1 * (Math.PI / 2));
},
easeInOutSine: function (t) {
return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
},
easeInExpo: function (t) {
return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
},
easeOutExpo: function (t) {
return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
},
easeInOutExpo: function (t) {
if (t === 0){
return 0;
}
if (t === 1){
return 1;
}
if ((t /= 1 / 2) < 1){
return 1 / 2 * Math.pow(2, 10 * (t - 1));
}
return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
},
easeInCirc: function (t) {
if (t >= 1){
return t;
}
return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
},
easeOutCirc: function (t) {
return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
},
easeInOutCirc: function (t) {
if ((t /= 1 / 2) < 1){
return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
}
return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
easeInElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0){
return 0;
}
if ((t /= 1) == 1){
return 1;
}
if (!p){
p = 1 * 0.3;
}
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else{
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
},
easeOutElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0){
return 0;
}
if ((t /= 1) == 1){
return 1;
}
if (!p){
p = 1 * 0.3;
}
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else{
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
},
easeInOutElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0){
return 0;
}
if ((t /= 1 / 2) == 2){
return 1;
}
if (!p){
p = 1 * (0.3 * 1.5);
}
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else {
s = p / (2 * Math.PI) * Math.asin(1 / a);
}
if (t < 1){
return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));}
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
},
easeInBack: function (t) {
var s = 1.70158;
return 1 * (t /= 1) * t * ((s + 1) * t - s);
},
easeOutBack: function (t) {
var s = 1.70158;
return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
},
easeInOutBack: function (t) {
var s = 1.70158;
if ((t /= 1 / 2) < 1){
return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
}
return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
},
easeInBounce: function (t) {
return 1 - easingEffects.easeOutBounce(1 - t);
},
easeOutBounce: function (t) {
if ((t /= 1) < (1 / 2.75)) {
return 1 * (7.5625 * t * t);
} else if (t < (2 / 2.75)) {
return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
} else if (t < (2.5 / 2.75)) {
return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
} else {
return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
}
},
easeInOutBounce: function (t) {
if (t < 1 / 2){
return easingEffects.easeInBounce(t * 2) * 0.5;
}
return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
}
},
//Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimFrame = helpers.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
})(),
cancelAnimFrame = helpers.cancelAnimFrame = (function(){
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function(callback) {
return window.clearTimeout(callback, 1000 / 60);
};
})(),
animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
var currentStep = 0,
easingFunction = easingEffects[easingString] || easingEffects.linear;
var animationFrame = function(){
currentStep++;
var stepDecimal = currentStep/totalSteps;
var easeDecimal = easingFunction(stepDecimal);
callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
onProgress.call(chartInstance,easeDecimal,stepDecimal);
if (currentStep < totalSteps){
chartInstance.animationFrame = requestAnimFrame(animationFrame);
} else{
onComplete.apply(chartInstance);
}
};
requestAnimFrame(animationFrame);
},
//-- DOM methods
getRelativePosition = helpers.getRelativePosition = function(evt){
var mouseX, mouseY;
var e = evt.originalEvent || evt,
canvas = evt.currentTarget || evt.srcElement,
boundingRect = canvas.getBoundingClientRect();
if (e.touches){
mouseX = e.touches[0].clientX - boundingRect.left;
mouseY = e.touches[0].clientY - boundingRect.top;
}
else{
mouseX = e.clientX - boundingRect.left;
mouseY = e.clientY - boundingRect.top;
}
return {
x : mouseX,
y : mouseY
};
},
addEvent = helpers.addEvent = function(node,eventType,method){
if (node.addEventListener){
node.addEventListener(eventType,method);
} else if (node.attachEvent){
node.attachEvent("on"+eventType, method);
} else {
node["on"+eventType] = method;
}
},
removeEvent = helpers.removeEvent = function(node, eventType, handler){
if (node.removeEventListener){
node.removeEventListener(eventType, handler, false);
} else if (node.detachEvent){
node.detachEvent("on"+eventType,handler);
} else{
node["on" + eventType] = noop;
}
},
bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
// Create the events object if it's not already present
if (!chartInstance.events) chartInstance.events = {};
each(arrayOfEvents,function(eventName){
chartInstance.events[eventName] = function(){
handler.apply(chartInstance, arguments);
};
addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
});
},
unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
each(arrayOfEvents, function(handler,eventName){
removeEvent(chartInstance.chart.canvas, eventName, handler);
});
},
getMaximumWidth = helpers.getMaximumWidth = function(domNode){
var container = domNode.parentNode,
padding = parseInt(getStyle(container, 'padding-left')) + parseInt(getStyle(container, 'padding-right'));
// TODO = check cross browser stuff with this.
return container.clientWidth - padding;
},
getMaximumHeight = helpers.getMaximumHeight = function(domNode){
var container = domNode.parentNode,
padding = parseInt(getStyle(container, 'padding-bottom')) + parseInt(getStyle(container, 'padding-top'));
// TODO = check cross browser stuff with this.
return container.clientHeight - padding;
},
getStyle = helpers.getStyle = function (el, property) {
return el.currentStyle ?
el.currentStyle[property] :
document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
},
getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
retinaScale = helpers.retinaScale = function(chart){
var ctx = chart.ctx,
width = chart.canvas.width,
height = chart.canvas.height;
if (window.devicePixelRatio) {
ctx.canvas.style.width = width + "px";
ctx.canvas.style.height = height + "px";
ctx.canvas.height = height * window.devicePixelRatio;
ctx.canvas.width = width * window.devicePixelRatio;
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}
},
//-- Canvas methods
clear = helpers.clear = function(chart){
chart.ctx.clearRect(0,0,chart.width,chart.height);
},
fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
return fontStyle + " " + pixelSize+"px " + fontFamily;
},
longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
ctx.font = font;
var longest = 0;
each(arrayOfStrings,function(string){
var textWidth = ctx.measureText(string).width;
longest = (textWidth > longest) ? textWidth : longest;
});
return longest;
},
drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
};
//Store a reference to each instance - allowing us to globally resize chart instances on window resize.
//Destroy method on the chart will remove the instance of the chart from this reference.
Chart.instances = {};
Chart.Type = function(data,options,chart){
this.options = options;
this.chart = chart;
this.id = uid();
//Add the chart instance to the global namespace
Chart.instances[this.id] = this;
// Initialize is always called when a chart type is created
// By default it is a no op, but it should be extended
if (options.responsive){
this.resize();
}
this.initialize.call(this,data);
};
//Core methods that'll be a part of every chart type
extend(Chart.Type.prototype,{
initialize : function(){return this;},
clear : function(){
clear(this.chart);
return this;
},
stop : function(){
// Stops any current animation loop occuring
Chart.animationService.cancelAnimation(this);
return this;
},
resize : function(callback){
this.stop();
var canvas = this.chart.canvas,
newWidth = getMaximumWidth(this.chart.canvas),
newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
canvas.width = this.chart.width = newWidth;
canvas.height = this.chart.height = newHeight;
retinaScale(this.chart);
if (typeof callback === "function"){
callback.apply(this, Array.prototype.slice.call(arguments, 1));
}
return this;
},
reflow : noop,
render : function(reflow){
if (reflow){
this.reflow();
}
if (this.options.animation && !reflow){
var animation = new Chart.Animation();
animation.numSteps = this.options.animationSteps;
animation.easing = this.options.animationEasing;
// render function
animation.render = function(chartInstance, animationObject) {
var easingFunction = helpers.easingEffects[animationObject.easing];
var stepDecimal = animationObject.currentStep / animationObject.numSteps;
var easeDecimal = easingFunction(stepDecimal);
chartInstance.draw(easeDecimal, stepDecimal, animationObject.currentStep);
};
// user events
animation.onAnimationProgress = this.options.onAnimationProgress;
animation.onAnimationComplete = this.options.onAnimationComplete;
Chart.animationService.addAnimation(this, animation);
}
else{
this.draw();
this.options.onAnimationComplete.call(this);
}
return this;
},
generateLegend : function(){
return template(this.options.legendTemplate,this);
},
destroy : function(){
this.clear();
unbindEvents(this, this.events);
var canvas = this.chart.canvas;
// Reset canvas height/width attributes starts a fresh with the canvas context
canvas.width = this.chart.width;
canvas.height = this.chart.height;
// < IE9 doesn't support removeProperty
if (canvas.style.removeProperty) {
canvas.style.removeProperty('width');
canvas.style.removeProperty('height');
} else {
canvas.style.removeAttribute('width');
canvas.style.removeAttribute('height');
}
delete Chart.instances[this.id];
},
showTooltip : function(ChartElements, forceRedraw){
// Only redraw the chart if we've actually changed what we're hovering on.
if (typeof this.activeElements === 'undefined') this.activeElements = [];
var isChanged = (function(Elements){
var changed = false;
if (Elements.length !== this.activeElements.length){
changed = true;
return changed;
}
each(Elements, function(element, index){
if (element !== this.activeElements[index]){
changed = true;
}
}, this);
return changed;
}).call(this, ChartElements);
if (!isChanged && !forceRedraw){
return;
}
else{
this.activeElements = ChartElements;
}
this.draw();
if(this.options.customTooltips){
this.options.customTooltips(false);
}
if (ChartElements.length > 0){
// If we have multiple datasets, show a MultiTooltip for all of the data points at that index
if (this.datasets && this.datasets.length > 1) {
var dataArray,
dataIndex;
for (var i = this.datasets.length - 1; i >= 0; i--) {
dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
dataIndex = indexOf(dataArray, ChartElements[0]);
if (dataIndex !== -1){
break;
}
}
var tooltipLabels = [],
tooltipColors = [],
medianPosition = (function(index) {
// Get all the points at that particular index
var Elements = [],
dataCollection,
xPositions = [],
yPositions = [],
xMax,
yMax,
xMin,
yMin;
helpers.each(this.datasets, function(dataset){
dataCollection = dataset.points || dataset.bars || dataset.segments;
if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
Elements.push(dataCollection[dataIndex]);
}
});
helpers.each(Elements, function(element) {
xPositions.push(element.x);
yPositions.push(element.y);
//Include any colour information about the element
tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
tooltipColors.push({
fill: element._saved.fillColor || element.fillColor,
stroke: element._saved.strokeColor || element.strokeColor
});
}, this);
yMin = min(yPositions);
yMax = max(yPositions);
xMin = min(xPositions);
xMax = max(xPositions);
return {
x: (xMin > this.chart.width/2) ? xMin : xMax,
y: (yMin + yMax)/2
};
}).call(this, dataIndex);
new Chart.MultiTooltip({
x: medianPosition.x,
y: medianPosition.y,
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
xOffset: this.options.tooltipXOffset,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
titleTextColor: this.options.tooltipTitleFontColor,
titleFontFamily: this.options.tooltipTitleFontFamily,
titleFontStyle: this.options.tooltipTitleFontStyle,
titleFontSize: this.options.tooltipTitleFontSize,
cornerRadius: this.options.tooltipCornerRadius,
labels: tooltipLabels,
legendColors: tooltipColors,
legendColorBackground : this.options.multiTooltipKeyBackground,
title: template(this.options.tooltipTitleTemplate,ChartElements[0]),
chart: this.chart,
ctx: this.chart.ctx,
custom: this.options.customTooltips
}).draw();
} else {
each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: template(this.options.tooltipTemplate, Element),
chart: this.chart,
custom: this.options.customTooltips
}).draw();
}, this);
}
}
return this;
},
toBase64Image : function(){
return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
}
});
Chart.Type.extend = function(extensions){
var parent = this;
var ChartType = function(){
return parent.apply(this,arguments);
};
//Copy the prototype object of the this class
ChartType.prototype = clone(parent.prototype);
//Now overwrite some of the properties in the base class with the new extensions
extend(ChartType.prototype, extensions);
ChartType.extend = Chart.Type.extend;
if (extensions.name || parent.prototype.name){
var chartName = extensions.name || parent.prototype.name;
//Assign any potential default values of the new chart type
//If none are defined, we'll use a clone of the chart type this is being extended from.
//I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
//doesn't define some defaults of their own.
var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
Chart.types[chartName] = ChartType;
//Register this new chart type in the Chart prototype
Chart.prototype[chartName] = function(data,options){
var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
return new ChartType(data,config,this);
};
} else{
warn("Name not provided for this chart, so it hasn't been registered");
}
return parent;
};
Chart.Element = function(configuration){
extend(this,configuration);
this.initialize.apply(this,arguments);
this.save();
};
extend(Chart.Element.prototype,{
initialize : function(){},
restore : function(props){
if (!props){
extend(this,this._saved);
} else {
each(props,function(key){
this[key] = this._saved[key];
},this);
}
return this;
},
save : function(){
this._saved = clone(this);
delete this._saved._saved;
return this;
},
update : function(newProps){
each(newProps,function(value,key){
this._saved[key] = this[key];
this[key] = value;
},this);
return this;
},
transition : function(props,ease){
each(props,function(value,key){
this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
},this);
return this;
},
tooltipPosition : function(){
return {
x : this.x,
y : this.y
};
},
hasValue: function(){
return isNumber(this.value);
}
});
Chart.Element.extend = inherits;
Chart.Point = Chart.Element.extend({
display: true,
inRange: function(chartX,chartY){
var hitDetectionRange = this.hitDetectionRadius + this.radius;
return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
},
draw : function(){
if (this.display){
var ctx = this.ctx;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.closePath();
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.stroke();
}
//Quick debug for bezier curve splining
//Highlights control points and the line between them.
//Handy for dev - stripped in the min version.
// ctx.save();
// ctx.fillStyle = "black";
// ctx.strokeStyle = "black"
// ctx.beginPath();
// ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
// ctx.fill();
// ctx.beginPath();
// ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
// ctx.fill();
// ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
// ctx.lineTo(this.x, this.y);
// ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
// ctx.stroke();
// ctx.restore();
}
});
Chart.Arc = Chart.Element.extend({
inRange : function(chartX,chartY){
var pointRelativePosition = helpers.getAngleFromPoint(this, {
x: chartX,
y: chartY
});
// Normalize all angles to 0 - 2*PI (0 - 360°)
var pointRelativeAngle = pointRelativePosition.angle % (Math.PI * 2),
startAngle = (Math.PI * 2 + this.startAngle) % (Math.PI * 2),
endAngle = (Math.PI * 2 + this.endAngle) % (Math.PI * 2) || 360;
// Calculate wether the pointRelativeAngle is between the start and the end angle
var betweenAngles = (endAngle < startAngle) ?
pointRelativeAngle <= endAngle || pointRelativeAngle >= startAngle:
pointRelativeAngle >= startAngle && pointRelativeAngle <= endAngle;
//Check if within the range of the open/close angle
var withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
return (betweenAngles && withinRadius);
//Ensure within the outside of the arc centre, but inside arc outer
},
tooltipPosition : function(){
var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
return {
x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
};
},
draw : function(animationPercent){
var easingDecimal = animationPercent || 1;
var ctx = this.ctx;
ctx.beginPath();
ctx.arc(this.x, this.y, this.outerRadius < 0 ? 0 : this.outerRadius, this.startAngle, this.endAngle);
ctx.arc(this.x, this.y, this.innerRadius < 0 ? 0 : this.innerRadius, this.endAngle, this.startAngle, true);
ctx.closePath();
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.lineJoin = 'bevel';
if (this.showStroke){
ctx.stroke();
}
}
});
Chart.Rectangle = Chart.Element.extend({
draw : function(){
var ctx = this.ctx,
halfWidth = this.width/2,
leftX = this.x - halfWidth,
rightX = this.x + halfWidth,
top = this.base - (this.base - this.y),
halfStroke = this.strokeWidth / 2;
// Canvas doesn't allow us to stroke inside the width so we can
// adjust the sizes to fit if we're setting a stroke on the line
if (this.showStroke){
leftX += halfStroke;
rightX -= halfStroke;
top += halfStroke;
}
ctx.beginPath();
ctx.fillStyle = this.fillColor;
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
// It'd be nice to keep this class totally generic to any rectangle
// and simply specify which border to miss out.
ctx.moveTo(leftX, this.base);
ctx.lineTo(leftX, top);
ctx.lineTo(rightX, top);
ctx.lineTo(rightX, this.base);
ctx.fill();
if (this.showStroke){
ctx.stroke();
}
},
height : function(){
return this.base - this.y;
},
inRange : function(chartX,chartY){
return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
}
});
Chart.Animation = Chart.Element.extend({
currentStep: null, // the current animation step
numSteps: 60, // default number of steps
easing: "", // the easing to use for this animation
render: null, // render function used by the animation service
onAnimationProgress: null, // user specified callback to fire on each step of the animation
onAnimationComplete: null, // user specified callback to fire when the animation finishes
});
Chart.Tooltip = Chart.Element.extend({
draw : function(){
var ctx = this.chart.ctx;
ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
this.xAlign = "center";
this.yAlign = "above";
//Distance between the actual element.y position and the start of the tooltip caret
var caretPadding = this.caretPadding = 2;
var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
tooltipRectHeight = this.fontSize + 2*this.yPadding,
tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
if (this.x + tooltipWidth/2 >this.chart.width){
this.xAlign = "left";
} else if (this.x - tooltipWidth/2 < 0){
this.xAlign = "right";
}
if (this.y - tooltipHeight < 0){
this.yAlign = "below";
}
var tooltipX = this.x - tooltipWidth/2,
tooltipY = this.y - tooltipHeight;
ctx.fillStyle = this.fillColor;
// Custom Tooltips
if(this.custom){
this.custom(this);
}
else{
switch(this.yAlign)
{
case "above":
//Draw a caret above the x/y
ctx.beginPath();
ctx.moveTo(this.x,this.y - caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.closePath();
ctx.fill();
break;
case "below":
tooltipY = this.y + caretPadding + this.caretHeight;
//Draw a caret below the x/y
ctx.beginPath();
ctx.moveTo(this.x, this.y + caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.closePath();
ctx.fill();
break;
}
switch(this.xAlign)
{
case "left":
tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
break;
case "right":
tooltipX = this.x - (this.cornerRadius + this.caretHeight);
break;
}
drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
ctx.fill();
ctx.fillStyle = this.textColor;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
}
}
});
Chart.MultiTooltip = Chart.Element.extend({
initialize : function(){
this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
this.titleHeight = this.title ? this.titleFontSize * 1.5 : 0;
this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleHeight;
this.ctx.font = this.titleFont;
var titleWidth = this.ctx.measureText(this.title).width,
//Label has a legend square as well so account for this.
labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
longestTextWidth = max([labelWidth,titleWidth]);
this.width = longestTextWidth + (this.xPadding*2);
var halfHeight = this.height/2;
//Check to ensure the height will fit on the canvas
if (this.y - halfHeight < 0 ){
this.y = halfHeight;
} else if (this.y + halfHeight > this.chart.height){
this.y = this.chart.height - halfHeight;
}
//Decide whether to align left or right based on position on canvas
if (this.x > this.chart.width/2){
this.x -= this.xOffset + this.width;
} else {
this.x += this.xOffset;
}
},
getLineHeight : function(index){
var baseLineHeight = this.y - (this.height/2) + this.yPadding,
afterTitleIndex = index-1;
//If the index is zero, we're getting the title
if (index === 0){
return baseLineHeight + this.titleHeight / 3;
} else{
return baseLineHeight + ((this.fontSize * 1.5 * afterTitleIndex) + this.fontSize / 2) + this.titleHeight;
}
},
draw : function(){
// Custom Tooltips
if(this.custom){
this.custom(this);
}
else{
drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
var ctx = this.ctx;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.closePath();
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillStyle = this.titleTextColor;
ctx.font = this.titleFont;
ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
ctx.font = this.font;
helpers.each(this.labels,function(label,index){
ctx.fillStyle = this.textColor;
ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
//A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
//ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
//Instead we'll make a white filled block to put the legendColour palette over.
ctx.fillStyle = this.legendColorBackground;
ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
ctx.fillStyle = this.legendColors[index].fill;
ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
},this);
}
}
});
Chart.Scale = Chart.Element.extend({
initialize : function(){
this.fit();
},
buildYLabels : function(){
this.yLabels = [];
var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
for (var i=0; i<=this.steps; i++){
this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
}
this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) + 10 : 0;
},
addXLabel : function(label){
this.xLabels.push(label);
this.valuesCount++;
this.fit();
},
removeXLabel : function(){
this.xLabels.shift();
this.valuesCount--;
this.fit();
},
// Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
fit: function(){
// First we need the width of the yLabels, assuming the xLabels aren't rotated
// To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
this.startPoint = (this.display) ? this.fontSize : 0;
this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
// Apply padding settings to the start and end point.
this.startPoint += this.padding;
this.endPoint -= this.padding;
// Cache the starting endpoint, excluding the space for x labels
var cachedEndPoint = this.endPoint;
// Cache the starting height, so can determine if we need to recalculate the scale yAxis
var cachedHeight = this.endPoint - this.startPoint,
cachedYLabelWidth;
// Build the current yLabels so we have an idea of what size they'll be to start
/*
* This sets what is returned from calculateScaleRange as static properties of this class:
*
this.steps;
this.stepValue;
this.min;
this.max;
*
*/
this.calculateYRange(cachedHeight);
// With these properties set we can now build the array of yLabels
// and also the width of the largest yLabel
this.buildYLabels();
this.calculateXLabelRotation();
while((cachedHeight > this.endPoint - this.startPoint)){
cachedHeight = this.endPoint - this.startPoint;
cachedYLabelWidth = this.yLabelWidth;
this.calculateYRange(cachedHeight);
this.buildYLabels();
// Only go through the xLabel loop again if the yLabel width has changed
if (cachedYLabelWidth < this.yLabelWidth){
this.endPoint = cachedEndPoint;
this.calculateXLabelRotation();
}
}
},
calculateXLabelRotation : function(){
//Get the width of each grid by calculating the difference
//between x offsets between 0 and 1.
this.ctx.font = this.font;
var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
firstRotated,
lastRotated;
this.xScalePaddingRight = lastWidth/2 + 3;
this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth) ? firstWidth/2 : this.yLabelWidth;
this.xLabelRotation = 0;
if (this.display){
var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
cosRotation,
firstRotatedWidth;
this.xLabelWidth = originalLabelWidth;
//Allow 3 pixels x2 padding either side for label readability
var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
//Max label rotate should be 90 - also act as a loop counter
while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
cosRotation = Math.cos(toRadians(this.xLabelRotation));
firstRotated = cosRotation * firstWidth;
lastRotated = cosRotation * lastWidth;
// We're right aligning the text now.
if (firstRotated + this.fontSize / 2 > this.yLabelWidth){
this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
}
this.xScalePaddingRight = this.fontSize/2;
this.xLabelRotation++;
this.xLabelWidth = cosRotation * originalLabelWidth;
}
if (this.xLabelRotation > 0){
this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
}
}
else{
this.xLabelWidth = 0;
this.xScalePaddingRight = this.padding;
this.xScalePaddingLeft = this.padding;
}
},
// Needs to be overidden in each Chart type
// Otherwise we need to pass all the data into the scale class
calculateYRange: noop,
drawingArea: function(){
return this.startPoint - this.endPoint;
},
calculateY : function(value){
var scalingFactor = this.drawingArea() / (this.min - this.max);
return this.endPoint - (scalingFactor * (value - this.min));
},
calculateX : function(index){
var isRotated = (this.xLabelRotation > 0),
// innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
if (this.offsetGridLines){
valueOffset += (valueWidth/2);
}
return Math.round(valueOffset);
},
update : function(newProps){
helpers.extend(this, newProps);
this.fit();
},
draw : function(){
var ctx = this.ctx,
yLabelGap = (this.endPoint - this.startPoint) / this.steps,
xStart = Math.round(this.xScalePaddingLeft);
if (this.display){
ctx.fillStyle = this.textColor;
ctx.font = this.font;
each(this.yLabels,function(labelString,index){
var yLabelCenter = this.endPoint - (yLabelGap * index),
linePositionY = Math.round(yLabelCenter),
drawHorizontalLine = this.showHorizontalLines;
ctx.textAlign = "right";
ctx.textBaseline = "middle";
if (this.showLabels){
ctx.fillText(labelString,xStart - 10,yLabelCenter);
}
// This is X axis, so draw it
if (index === 0 && !drawHorizontalLine){
drawHorizontalLine = true;
}
if (drawHorizontalLine){
ctx.beginPath();
}
if (index > 0){
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
linePositionY += helpers.aliasPixel(ctx.lineWidth);
if(drawHorizontalLine){
ctx.moveTo(xStart, linePositionY);
ctx.lineTo(this.width, linePositionY);
ctx.stroke();
ctx.closePath();
}
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
ctx.beginPath();
ctx.moveTo(xStart - 5, linePositionY);
ctx.lineTo(xStart, linePositionY);
ctx.stroke();
ctx.closePath();
},this);
each(this.xLabels,function(label,index){
var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
// Check to see if line/bar here and decide where to place the line
linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
isRotated = (this.xLabelRotation > 0),
drawVerticalLine = this.showVerticalLines;
// This is Y axis, so draw it
if (index === 0 && !drawVerticalLine){
drawVerticalLine = true;
}
if (drawVerticalLine){
ctx.beginPath();
}
if (index > 0){
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
if (drawVerticalLine){
ctx.moveTo(linePos,this.endPoint);
ctx.lineTo(linePos,this.startPoint - 3);
ctx.stroke();
ctx.closePath();
}
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
// Small lines at the bottom of the base grid line
ctx.beginPath();
ctx.moveTo(linePos,this.endPoint);
ctx.lineTo(linePos,this.endPoint + 5);
ctx.stroke();
ctx.closePath();
ctx.save();
ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
ctx.rotate(toRadians(this.xLabelRotation)*-1);
ctx.font = this.font;
ctx.textAlign = (isRotated) ? "right" : "center";
ctx.textBaseline = (isRotated) ? "middle" : "top";
ctx.fillText(label, 0, 0);
ctx.restore();
},this);
}
}
});
Chart.RadialScale = Chart.Element.extend({
initialize: function(){
this.size = min([this.height, this.width]);
this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
},
calculateCenterOffset: function(value){
// Take into account half font size + the yPadding of the top value
var scalingFactor = this.drawingArea / (this.max - this.min);
return (value - this.min) * scalingFactor;
},
update : function(){
if (!this.lineArc){
this.setScaleSize();
} else {
this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
}
this.buildYLabels();
},
buildYLabels: function(){
this.yLabels = [];
var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
for (var i=0; i<=this.steps; i++){
this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
}
},
getCircumference : function(){
return ((Math.PI*2) / this.valuesCount);
},
setScaleSize: function(){
/*
* Right, this is really confusing and there is a lot of maths going on here
* The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
*
* Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
*
* Solution:
*
* We assume the radius of the polygon is half the size of the canvas at first
* at each index we check if the text overlaps.
*
* Where it does, we store that angle and that index.
*
* After finding the largest index and angle we calculate how much we need to remove
* from the shape radius to move the point inwards by that x.
*
* We average the left and right distances to get the maximum shape radius that can fit in the box
* along with labels.
*
* Once we have that, we can find the centre point for the chart, by taking the x text protrusion
* on each side, removing that from the size, halving it and adding the left x protrusion width.
*
* This will mean we have a shape fitted to the canvas, as large as it can be with the labels
* and position it in the most space efficient manner
*
* https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
*/
// Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
// Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
pointPosition,
i,
textWidth,
halfTextWidth,
furthestRight = this.width,
furthestRightIndex,
furthestRightAngle,
furthestLeft = 0,
furthestLeftIndex,
furthestLeftAngle,
xProtrusionLeft,
xProtrusionRight,
radiusReductionRight,
radiusReductionLeft,
maxWidthRadius;
this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
for (i=0;i<this.valuesCount;i++){
// 5px to space the text slightly out - similar to what we do in the draw function.
pointPosition = this.getPointPosition(i, largestPossibleRadius);
textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
if (i === 0 || i === this.valuesCount/2){
// If we're at index zero, or exactly the middle, we're at exactly the top/bottom
// of the radar chart, so text will be aligned centrally, so we'll half it and compare
// w/left and right text sizes
halfTextWidth = textWidth/2;
if (pointPosition.x + halfTextWidth > furthestRight) {
furthestRight = pointPosition.x + halfTextWidth;
furthestRightIndex = i;
}
if (pointPosition.x - halfTextWidth < furthestLeft) {
furthestLeft = pointPosition.x - halfTextWidth;
furthestLeftIndex = i;
}
}
else if (i < this.valuesCount/2) {
// Less than half the values means we'll left align the text
if (pointPosition.x + textWidth > furthestRight) {
furthestRight = pointPosition.x + textWidth;
furthestRightIndex = i;
}
}
else if (i > this.valuesCount/2){
// More than half the values means we'll right align the text
if (pointPosition.x - textWidth < furthestLeft) {
furthestLeft = pointPosition.x - textWidth;
furthestLeftIndex = i;
}
}
}
xProtrusionLeft = furthestLeft;
xProtrusionRight = Math.ceil(furthestRight - this.width);
furthestRightAngle = this.getIndexAngle(furthestRightIndex);
furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
// Ensure we actually need to reduce the size of the chart
radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
//this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
},
setCenterPoint: function(leftMovement, rightMovement){
var maxRight = this.width - rightMovement - this.drawingArea,
maxLeft = leftMovement + this.drawingArea;
this.xCenter = (maxLeft + maxRight)/2;
// Always vertically in the centre as the text height doesn't change
this.yCenter = (this.height/2);
},
getIndexAngle : function(index){
var angleMultiplier = (Math.PI * 2) / this.valuesCount;
// Start from the top instead of right, so remove a quarter of the circle
return index * angleMultiplier - (Math.PI/2);
},
getPointPosition : function(index, distanceFromCenter){
var thisAngle = this.getIndexAngle(index);
return {
x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
};
},
draw: function(){
if (this.display){
var ctx = this.ctx;
each(this.yLabels, function(label, index){
// Don't draw a centre value
if (index > 0){
var yCenterOffset = index * (this.drawingArea/this.steps),
yHeight = this.yCenter - yCenterOffset,
pointPosition;
// Draw circular lines around the scale
if (this.lineWidth > 0){
ctx.strokeStyle = this.lineColor;
ctx.lineWidth = this.lineWidth;
if(this.lineArc){
ctx.beginPath();
ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
ctx.closePath();
ctx.stroke();
} else{
ctx.beginPath();
for (var i=0;i<this.valuesCount;i++)
{
pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
if (i === 0){
ctx.moveTo(pointPosition.x, pointPosition.y);
} else {
ctx.lineTo(pointPosition.x, pointPosition.y);
}
}
ctx.closePath();
ctx.stroke();
}
}
if(this.showLabels){
ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
if (this.showLabelBackdrop){
var labelWidth = ctx.measureText(label).width;
ctx.fillStyle = this.backdropColor;
ctx.fillRect(
this.xCenter - labelWidth/2 - this.backdropPaddingX,
yHeight - this.fontSize/2 - this.backdropPaddingY,
labelWidth + this.backdropPaddingX*2,
this.fontSize + this.backdropPaddingY*2
);
}
ctx.textAlign = 'center';
ctx.textBaseline = "middle";
ctx.fillStyle = this.fontColor;
ctx.fillText(label, this.xCenter, yHeight);
}
}
}, this);
if (!this.lineArc){
ctx.lineWidth = this.angleLineWidth;
ctx.strokeStyle = this.angleLineColor;
for (var i = this.valuesCount - 1; i >= 0; i--) {
var centerOffset = null, outerPosition = null;
if (this.angleLineWidth > 0){
centerOffset = this.calculateCenterOffset(this.max);
outerPosition = this.getPointPosition(i, centerOffset);
ctx.beginPath();
ctx.moveTo(this.xCenter, this.yCenter);
ctx.lineTo(outerPosition.x, outerPosition.y);
ctx.stroke();
ctx.closePath();
}
if (this.backgroundColors && this.backgroundColors.length == this.valuesCount) {
if (centerOffset == null)
centerOffset = this.calculateCenterOffset(this.max);
if (outerPosition == null)
outerPosition = this.getPointPosition(i, centerOffset);
var previousOuterPosition = this.getPointPosition(i === 0 ? this.valuesCount - 1 : i - 1, centerOffset);
var nextOuterPosition = this.getPointPosition(i === this.valuesCount - 1 ? 0 : i + 1, centerOffset);
var previousOuterHalfway = { x: (previousOuterPosition.x + outerPosition.x) / 2, y: (previousOuterPosition.y + outerPosition.y) / 2 };
var nextOuterHalfway = { x: (outerPosition.x + nextOuterPosition.x) / 2, y: (outerPosition.y + nextOuterPosition.y) / 2 };
ctx.beginPath();
ctx.moveTo(this.xCenter, this.yCenter);
ctx.lineTo(previousOuterHalfway.x, previousOuterHalfway.y);
ctx.lineTo(outerPosition.x, outerPosition.y);
ctx.lineTo(nextOuterHalfway.x, nextOuterHalfway.y);
ctx.fillStyle = this.backgroundColors[i];
ctx.fill();
ctx.closePath();
}
// Extra 3px out for some label spacing
var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
ctx.fillStyle = this.pointLabelFontColor;
var labelsCount = this.labels.length,
halfLabelsCount = this.labels.length/2,
quarterLabelsCount = halfLabelsCount/2,
upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
if (i === 0){
ctx.textAlign = 'center';
} else if(i === halfLabelsCount){
ctx.textAlign = 'center';
} else if (i < halfLabelsCount){
ctx.textAlign = 'left';
} else {
ctx.textAlign = 'right';
}
// Set the correct text baseline based on outer positioning
if (exactQuarter){
ctx.textBaseline = 'middle';
} else if (upperHalf){
ctx.textBaseline = 'bottom';
} else {
ctx.textBaseline = 'top';
}
ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
}
}
}
}
});
Chart.animationService = {
frameDuration: 17,
animations: [],
dropFrames: 0,
addAnimation: function(chartInstance, animationObject) {
for (var index = 0; index < this.animations.length; ++ index){
if (this.animations[index].chartInstance === chartInstance){
// replacing an in progress animation
this.animations[index].animationObject = animationObject;
return;
}
}
this.animations.push({
chartInstance: chartInstance,
animationObject: animationObject
});
// If there are no animations queued, manually kickstart a digest, for lack of a better word
if (this.animations.length == 1) {
helpers.requestAnimFrame.call(window, this.digestWrapper);
}
},
// Cancel the animation for a given chart instance
cancelAnimation: function(chartInstance) {
var index = helpers.findNextWhere(this.animations, function(animationWrapper) {
return animationWrapper.chartInstance === chartInstance;
});
if (index)
{
this.animations.splice(index, 1);
}
},
// calls startDigest with the proper context
digestWrapper: function() {
Chart.animationService.startDigest.call(Chart.animationService);
},
startDigest: function() {
var startTime = Date.now();
var framesToDrop = 0;
if(this.dropFrames > 1){
framesToDrop = Math.floor(this.dropFrames);
this.dropFrames -= framesToDrop;
}
for (var i = 0; i < this.animations.length; i++) {
if (this.animations[i].animationObject.currentStep === null){
this.animations[i].animationObject.currentStep = 0;
}
this.animations[i].animationObject.currentStep += 1 + framesToDrop;
if(this.animations[i].animationObject.currentStep > this.animations[i].animationObject.numSteps){
this.animations[i].animationObject.currentStep = this.animations[i].animationObject.numSteps;
}
this.animations[i].animationObject.render(this.animations[i].chartInstance, this.animations[i].animationObject);
// Check if executed the last frame.
if (this.animations[i].animationObject.currentStep == this.animations[i].animationObject.numSteps){
// Call onAnimationComplete
this.animations[i].animationObject.onAnimationComplete.call(this.animations[i].chartInstance);
// Remove the animation.
this.animations.splice(i, 1);
// Keep the index in place to offset the splice
i--;
}
}
var endTime = Date.now();
var delay = endTime - startTime - this.frameDuration;
var frameDelay = delay / this.frameDuration;
if(frameDelay > 1){
this.dropFrames += frameDelay;
}
// Do we have more stuff to animate?
if (this.animations.length > 0){
helpers.requestAnimFrame.call(window, this.digestWrapper);
}
}
};
// Attach global event to resize each chart instance when the browser resizes
helpers.addEvent(window, "resize", (function(){
// Basic debounce of resize function so it doesn't hurt performance when resizing browser.
var timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(function(){
each(Chart.instances,function(instance){
// If the responsive flag is set in the chart instance config
// Cascade the resize event down to the chart.
if (instance.options.responsive){
instance.resize(instance.render, true);
}
});
}, 50);
};
})());
if (amd) {
define(function(){
return Chart;
});
} else if (typeof module === 'object' && module.exports) {
module.exports = Chart;
}
root.Chart = Chart;
Chart.noConflict = function(){
root.Chart = previous;
return Chart;
};
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
helpers = Chart.helpers;
var defaultConfig = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>"
};
Chart.Type.extend({
name: "Bar",
defaults : defaultConfig,
initialize: function(data){
//Expose options as a scope variable here so we can access it in the ScaleClass
var options = this.options;
this.ScaleClass = Chart.Scale.extend({
offsetGridLines : true,
calculateBarX : function(datasetCount, datasetIndex, barIndex){
//Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
var xWidth = this.calculateBaseWidth(),
xAbsolute = this.calculateX(barIndex) - (xWidth/2),
barWidth = this.calculateBarWidth(datasetCount);
return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
},
calculateBaseWidth : function(){
return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
},
calculateBarWidth : function(datasetCount){
//The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
return (baseWidth / datasetCount);
}
});
this.datasets = [];
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
this.eachBars(function(bar){
bar.restore(['fillColor', 'strokeColor']);
});
helpers.each(activeBars, function(activeBar){
activeBar.fillColor = activeBar.highlightFill;
activeBar.strokeColor = activeBar.highlightStroke;
});
this.showTooltip(activeBars);
});
}
//Declare the extension of the default point, to cater for the options passed in to the constructor
this.BarClass = Chart.Rectangle.extend({
strokeWidth : this.options.barStrokeWidth,
showStroke : this.options.barShowStroke,
ctx : this.chart.ctx
});
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset,datasetIndex){
var datasetObject = {
label : dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
bars : []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
fillColor : dataset.fillColor,
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
},this);
},this);
this.buildScale(data.labels);
this.BarClass.prototype.base = this.scale.endPoint;
this.eachBars(function(bar, index, datasetIndex){
helpers.extend(bar, {
width : this.scale.calculateBarWidth(this.datasets.length),
x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
y: this.scale.endPoint
});
bar.save();
}, this);
this.render();
},
update : function(){
this.scale.update();
// Reset any highlight colours before updating.
helpers.each(this.activeElements, function(activeElement){
activeElement.restore(['fillColor', 'strokeColor']);
});
this.eachBars(function(bar){
bar.save();
});
this.render();
},
eachBars : function(callback){
helpers.each(this.datasets,function(dataset, datasetIndex){
helpers.each(dataset.bars, callback, this, datasetIndex);
},this);
},
getBarsAtEvent : function(e){
var barsArray = [],
eventPosition = helpers.getRelativePosition(e),
datasetIterator = function(dataset){
barsArray.push(dataset.bars[barIndex]);
},
barIndex;
for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
helpers.each(this.datasets, datasetIterator);
return barsArray;
}
}
}
return barsArray;
},
buildScale : function(labels){
var self = this;
var dataTotal = function(){
var values = [];
self.eachBars(function(bar){
values.push(bar.value);
});
return values;
};
var scaleOptions = {
templateString : this.options.scaleLabel,
height : this.chart.height,
width : this.chart.width,
ctx : this.chart.ctx,
textColor : this.options.scaleFontColor,
fontSize : this.options.scaleFontSize,
fontStyle : this.options.scaleFontStyle,
fontFamily : this.options.scaleFontFamily,
valuesCount : labels.length,
beginAtZero : this.options.scaleBeginAtZero,
integersOnly : this.options.scaleIntegersOnly,
calculateYRange: function(currentHeight){
var updatedRanges = helpers.calculateScaleRange(
dataTotal(),
currentHeight,
this.fontSize,
this.beginAtZero,
this.integersOnly
);
helpers.extend(this, updatedRanges);
},
xLabels : labels,
font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
lineWidth : this.options.scaleLineWidth,
lineColor : this.options.scaleLineColor,
showHorizontalLines : this.options.scaleShowHorizontalLines,
showVerticalLines : this.options.scaleShowVerticalLines,
gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
showLabels : this.options.scaleShowLabels,
display : this.options.showScale
};
if (this.options.scaleOverride){
helpers.extend(scaleOptions, {
calculateYRange: helpers.noop,
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
});
}
this.scale = new this.ScaleClass(scaleOptions);
},
addData : function(valuesArray,label){
//Map the values array for each of the datasets
helpers.each(valuesArray,function(value,datasetIndex){
//Add a new point for each piece of data, passing any required data to draw.
this.datasets[datasetIndex].bars.push(new this.BarClass({
value : value,
label : label,
datasetLabel: this.datasets[datasetIndex].label,
x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
y: this.scale.endPoint,
width : this.scale.calculateBarWidth(this.datasets.length),
base : this.scale.endPoint,
strokeColor : this.datasets[datasetIndex].strokeColor,
fillColor : this.datasets[datasetIndex].fillColor
}));
},this);
this.scale.addXLabel(label);
//Then re-render the chart.
this.update();
},
removeData : function(){
this.scale.removeXLabel();
//Then re-render the chart.
helpers.each(this.datasets,function(dataset){
dataset.bars.shift();
},this);
this.update();
},
reflow : function(){
helpers.extend(this.BarClass.prototype,{
y: this.scale.endPoint,
base : this.scale.endPoint
});
var newScaleProps = helpers.extend({
height : this.chart.height,
width : this.chart.width
});
this.scale.update(newScaleProps);
},
draw : function(ease){
var easingDecimal = ease || 1;
this.clear();
var ctx = this.chart.ctx;
this.scale.draw(easingDecimal);
//Draw all the bars for each dataset
helpers.each(this.datasets,function(dataset,datasetIndex){
helpers.each(dataset.bars,function(bar,index){
if (bar.hasValue()){
bar.base = this.scale.endPoint;
//Transition then draw
bar.transition({
x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
y : this.scale.calculateY(bar.value),
width : this.scale.calculateBarWidth(this.datasets.length)
}, easingDecimal).draw();
}
},this);
},this);
}
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
//Cache a local reference to Chart.helpers
helpers = Chart.helpers;
var defaultConfig = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : true,
//String - The colour of each segment stroke
segmentStrokeColor : "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth : 2,
//The percentage of the chart that we cut out of the middle.
percentageInnerCutout : 50,
//Number - Amount of animation steps
animationSteps : 100,
//String - Animation easing effect
animationEasing : "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate : true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale : false,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>"
};
Chart.Type.extend({
//Passing in a name registers this chart in the Chart namespace
name: "Doughnut",
//Providing a defaults will also register the deafults in the chart namespace
defaults : defaultConfig,
//Initialize is fired when the chart is initialized - Data is passed in as a parameter
//Config is automatically merged by the core of Chart.js, and is available at this.options
initialize: function(data){
//Declare segments as a static property to prevent inheriting across the Chart type prototype
this.segments = [];
this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
this.SegmentArc = Chart.Arc.extend({
ctx : this.chart.ctx,
x : this.chart.width/2,
y : this.chart.height/2
});
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
helpers.each(this.segments,function(segment){
segment.restore(["fillColor"]);
});
helpers.each(activeSegments,function(activeSegment){
activeSegment.fillColor = activeSegment.highlightColor;
});
this.showTooltip(activeSegments);
});
}
this.calculateTotal(data);
helpers.each(data,function(datapoint, index){
if (!datapoint.color) {
datapoint.color = 'hsl(' + (360 * index / data.length) + ', 100%, 50%)';
}
this.addData(datapoint, index, true);
},this);
this.render();
},
getSegmentsAtEvent : function(e){
var segmentsArray = [];
var location = helpers.getRelativePosition(e);
helpers.each(this.segments,function(segment){
if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
},this);
return segmentsArray;
},
addData : function(segment, atIndex, silent){
var index = atIndex !== undefined ? atIndex : this.segments.length;
if ( typeof(segment.color) === "undefined" ) {
segment.color = Chart.defaults.global.segmentColorDefault[index % Chart.defaults.global.segmentColorDefault.length];
segment.highlight = Chart.defaults.global.segmentHighlightColorDefaults[index % Chart.defaults.global.segmentHighlightColorDefaults.length];
}
this.segments.splice(index, 0, new this.SegmentArc({
value : segment.value,
outerRadius : (this.options.animateScale) ? 0 : this.outerRadius,
innerRadius : (this.options.animateScale) ? 0 : (this.outerRadius/100) * this.options.percentageInnerCutout,
fillColor : segment.color,
highlightColor : segment.highlight || segment.color,
showStroke : this.options.segmentShowStroke,
strokeWidth : this.options.segmentStrokeWidth,
strokeColor : this.options.segmentStrokeColor,
startAngle : Math.PI * 1.5,
circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
label : segment.label
}));
if (!silent){
this.reflow();
this.update();
}
},
calculateCircumference : function(value) {
if ( this.total > 0 ) {
return (Math.PI*2)*(value / this.total);
} else {
return 0;
}
},
calculateTotal : function(data){
this.total = 0;
helpers.each(data,function(segment){
this.total += Math.abs(segment.value);
},this);
},
update : function(){
this.calculateTotal(this.segments);
// Reset any highlight colours before updating.
helpers.each(this.activeElements, function(activeElement){
activeElement.restore(['fillColor']);
});
helpers.each(this.segments,function(segment){
segment.save();
});
this.render();
},
removeData: function(atIndex){
var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
this.segments.splice(indexToDelete, 1);
this.reflow();
this.update();
},
reflow : function(){
helpers.extend(this.SegmentArc.prototype,{
x : this.chart.width/2,
y : this.chart.height/2
});
this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
helpers.each(this.segments, function(segment){
segment.update({
outerRadius : this.outerRadius,
innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
});
}, this);
},
draw : function(easeDecimal){
var animDecimal = (easeDecimal) ? easeDecimal : 1;
this.clear();
helpers.each(this.segments,function(segment,index){
segment.transition({
circumference : this.calculateCircumference(segment.value),
outerRadius : this.outerRadius,
innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
},animDecimal);
segment.endAngle = segment.startAngle + segment.circumference;
segment.draw();
if (index === 0){
segment.startAngle = Math.PI * 1.5;
}
//Check to see if it's the last segment, if not get the next and update the start angle
if (index < this.segments.length-1){
this.segments[index+1].startAngle = segment.endAngle;
}
},this);
}
});
Chart.types.Doughnut.extend({
name : "Pie",
defaults : helpers.merge(defaultConfig,{percentageInnerCutout : 0})
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
helpers = Chart.helpers;
var defaultConfig = {
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Number - Tension of the bezier curve between points
bezierCurveTension : 0.4,
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius : 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>",
//Boolean - Whether to horizontally center the label and point dot inside the grid
offsetGridLines : false
};
Chart.Type.extend({
name: "Line",
defaults : defaultConfig,
initialize: function(data){
//Declare the extension of the default point, to cater for the options passed in to the constructor
this.PointClass = Chart.Point.extend({
offsetGridLines : this.options.offsetGridLines,
strokeWidth : this.options.pointDotStrokeWidth,
radius : this.options.pointDotRadius,
display: this.options.pointDot,
hitDetectionRadius : this.options.pointHitDetectionRadius,
ctx : this.chart.ctx,
inRange : function(mouseX){
return (Math.pow(mouseX-this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius,2));
}
});
this.datasets = [];
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
this.eachPoints(function(point){
point.restore(['fillColor', 'strokeColor']);
});
helpers.each(activePoints, function(activePoint){
activePoint.fillColor = activePoint.highlightFill;
activePoint.strokeColor = activePoint.highlightStroke;
});
this.showTooltip(activePoints);
});
}
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset){
var datasetObject = {
label : dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
pointColor : dataset.pointColor,
pointStrokeColor : dataset.pointStrokeColor,
points : []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.points.push(new this.PointClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.pointStrokeColor,
fillColor : dataset.pointColor,
highlightFill : dataset.pointHighlightFill || dataset.pointColor,
highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
}));
},this);
this.buildScale(data.labels);
this.eachPoints(function(point, index){
helpers.extend(point, {
x: this.scale.calculateX(index),
y: this.scale.endPoint
});
point.save();
}, this);
},this);
this.render();
},
update : function(){
this.scale.update();
// Reset any highlight colours before updating.
helpers.each(this.activeElements, function(activeElement){
activeElement.restore(['fillColor', 'strokeColor']);
});
this.eachPoints(function(point){
point.save();
});
this.render();
},
eachPoints : function(callback){
helpers.each(this.datasets,function(dataset){
helpers.each(dataset.points,callback,this);
},this);
},
getPointsAtEvent : function(e){
var pointsArray = [],
eventPosition = helpers.getRelativePosition(e);
helpers.each(this.datasets,function(dataset){
helpers.each(dataset.points,function(point){
if (point.inRange(eventPosition.x,eventPosition.y)) pointsArray.push(point);
});
},this);
return pointsArray;
},
buildScale : function(labels){
var self = this;
var dataTotal = function(){
var values = [];
self.eachPoints(function(point){
values.push(point.value);
});
return values;
};
var scaleOptions = {
templateString : this.options.scaleLabel,
height : this.chart.height,
width : this.chart.width,
ctx : this.chart.ctx,
textColor : this.options.scaleFontColor,
offsetGridLines : this.options.offsetGridLines,
fontSize : this.options.scaleFontSize,
fontStyle : this.options.scaleFontStyle,
fontFamily : this.options.scaleFontFamily,
valuesCount : labels.length,
beginAtZero : this.options.scaleBeginAtZero,
integersOnly : this.options.scaleIntegersOnly,
calculateYRange : function(currentHeight){
var updatedRanges = helpers.calculateScaleRange(
dataTotal(),
currentHeight,
this.fontSize,
this.beginAtZero,
this.integersOnly
);
helpers.extend(this, updatedRanges);
},
xLabels : labels,
font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
lineWidth : this.options.scaleLineWidth,
lineColor : this.options.scaleLineColor,
showHorizontalLines : this.options.scaleShowHorizontalLines,
showVerticalLines : this.options.scaleShowVerticalLines,
gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
showLabels : this.options.scaleShowLabels,
display : this.options.showScale
};
if (this.options.scaleOverride){
helpers.extend(scaleOptions, {
calculateYRange: helpers.noop,
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
});
}
this.scale = new Chart.Scale(scaleOptions);
},
addData : function(valuesArray,label){
//Map the values array for each of the datasets
helpers.each(valuesArray,function(value,datasetIndex){
//Add a new point for each piece of data, passing any required data to draw.
this.datasets[datasetIndex].points.push(new this.PointClass({
value : value,
label : label,
datasetLabel: this.datasets[datasetIndex].label,
x: this.scale.calculateX(this.scale.valuesCount+1),
y: this.scale.endPoint,
strokeColor : this.datasets[datasetIndex].pointStrokeColor,
fillColor : this.datasets[datasetIndex].pointColor
}));
},this);
this.scale.addXLabel(label);
//Then re-render the chart.
this.update();
},
removeData : function(){
this.scale.removeXLabel();
//Then re-render the chart.
helpers.each(this.datasets,function(dataset){
dataset.points.shift();
},this);
this.update();
},
reflow : function(){
var newScaleProps = helpers.extend({
height : this.chart.height,
width : this.chart.width
});
this.scale.update(newScaleProps);
},
draw : function(ease){
var easingDecimal = ease || 1;
this.clear();
var ctx = this.chart.ctx;
// Some helper methods for getting the next/prev points
var hasValue = function(item){
return item.value !== null;
},
nextPoint = function(point, collection, index){
return helpers.findNextWhere(collection, hasValue, index) || point;
},
previousPoint = function(point, collection, index){
return helpers.findPreviousWhere(collection, hasValue, index) || point;
};
if (!this.scale) return;
this.scale.draw(easingDecimal);
helpers.each(this.datasets,function(dataset){
var pointsWithValues = helpers.where(dataset.points, hasValue);
//Transition each point first so that the line and point drawing isn't out of sync
//We can use this extra loop to calculate the control points of this dataset also in this loop
helpers.each(dataset.points, function(point, index){
if (point.hasValue()){
point.transition({
y : this.scale.calculateY(point.value),
x : this.scale.calculateX(index)
}, easingDecimal);
}
},this);
// Control points need to be calculated in a separate loop, because we need to know the current x/y of the point
// This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
if (this.options.bezierCurve){
helpers.each(pointsWithValues, function(point, index){
var tension = (index > 0 && index < pointsWithValues.length - 1) ? this.options.bezierCurveTension : 0;
point.controlPoints = helpers.splineCurve(
previousPoint(point, pointsWithValues, index),
point,
nextPoint(point, pointsWithValues, index),
tension
);
// Prevent the bezier going outside of the bounds of the graph
// Cap puter bezier handles to the upper/lower scale bounds
if (point.controlPoints.outer.y > this.scale.endPoint){
point.controlPoints.outer.y = this.scale.endPoint;
}
else if (point.controlPoints.outer.y < this.scale.startPoint){
point.controlPoints.outer.y = this.scale.startPoint;
}
// Cap inner bezier handles to the upper/lower scale bounds
if (point.controlPoints.inner.y > this.scale.endPoint){
point.controlPoints.inner.y = this.scale.endPoint;
}
else if (point.controlPoints.inner.y < this.scale.startPoint){
point.controlPoints.inner.y = this.scale.startPoint;
}
},this);
}
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
helpers.each(pointsWithValues, function(point, index){
if (index === 0){
ctx.moveTo(point.x, point.y);
}
else{
if(this.options.bezierCurve){
var previous = previousPoint(point, pointsWithValues, index);
ctx.bezierCurveTo(
previous.controlPoints.outer.x,
previous.controlPoints.outer.y,
point.controlPoints.inner.x,
point.controlPoints.inner.y,
point.x,
point.y
);
}
else{
ctx.lineTo(point.x,point.y);
}
}
}, this);
if (this.options.datasetStroke) {
ctx.stroke();
}
if (this.options.datasetFill && pointsWithValues.length > 0){
//Round off the line by going to the base of the chart, back to the start, then fill.
ctx.lineTo(pointsWithValues[pointsWithValues.length - 1].x, this.scale.endPoint);
ctx.lineTo(pointsWithValues[0].x, this.scale.endPoint);
ctx.fillStyle = dataset.fillColor;
ctx.closePath();
ctx.fill();
}
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
helpers.each(pointsWithValues,function(point){
point.draw();
});
},this);
}
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
//Cache a local reference to Chart.helpers
helpers = Chart.helpers;
var defaultConfig = {
//Boolean - Show a backdrop to the scale label
scaleShowLabelBackdrop : true,
//String - The colour of the label backdrop
scaleBackdropColor : "rgba(255,255,255,0.75)",
// Boolean - Whether the scale should begin at zero
scaleBeginAtZero : true,
//Number - The backdrop padding above & below the label in pixels
scaleBackdropPaddingY : 2,
//Number - The backdrop padding to the side of the label in pixels
scaleBackdropPaddingX : 2,
//Boolean - Show line for each value in the scale
scaleShowLine : true,
//Boolean - Stroke a line around each segment in the chart
segmentShowStroke : true,
//String - The colour of the stroke on each segment.
segmentStrokeColor : "#fff",
//Number - The width of the stroke value in pixels
segmentStrokeWidth : 2,
//Number - Amount of animation steps
animationSteps : 100,
//String - Animation easing effect.
animationEasing : "easeOutBounce",
//Boolean - Whether to animate the rotation of the chart
animateRotate : true,
//Boolean - Whether to animate scaling the chart from the centre
animateScale : false,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>"
};
Chart.Type.extend({
//Passing in a name registers this chart in the Chart namespace
name: "PolarArea",
//Providing a defaults will also register the deafults in the chart namespace
defaults : defaultConfig,
//Initialize is fired when the chart is initialized - Data is passed in as a parameter
//Config is automatically merged by the core of Chart.js, and is available at this.options
initialize: function(data){
this.segments = [];
//Declare segment class as a chart instance specific class, so it can share props for this instance
this.SegmentArc = Chart.Arc.extend({
showStroke : this.options.segmentShowStroke,
strokeWidth : this.options.segmentStrokeWidth,
strokeColor : this.options.segmentStrokeColor,
ctx : this.chart.ctx,
innerRadius : 0,
x : this.chart.width/2,
y : this.chart.height/2
});
this.scale = new Chart.RadialScale({
display: this.options.showScale,
fontStyle: this.options.scaleFontStyle,
fontSize: this.options.scaleFontSize,
fontFamily: this.options.scaleFontFamily,
fontColor: this.options.scaleFontColor,
showLabels: this.options.scaleShowLabels,
showLabelBackdrop: this.options.scaleShowLabelBackdrop,
backdropColor: this.options.scaleBackdropColor,
backdropPaddingY : this.options.scaleBackdropPaddingY,
backdropPaddingX: this.options.scaleBackdropPaddingX,
lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
lineColor: this.options.scaleLineColor,
lineArc: true,
width: this.chart.width,
height: this.chart.height,
xCenter: this.chart.width/2,
yCenter: this.chart.height/2,
ctx : this.chart.ctx,
templateString: this.options.scaleLabel,
valuesCount: data.length
});
this.updateScaleRange(data);
this.scale.update();
helpers.each(data,function(segment,index){
this.addData(segment,index,true);
},this);
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
helpers.each(this.segments,function(segment){
segment.restore(["fillColor"]);
});
helpers.each(activeSegments,function(activeSegment){
activeSegment.fillColor = activeSegment.highlightColor;
});
this.showTooltip(activeSegments);
});
}
this.render();
},
getSegmentsAtEvent : function(e){
var segmentsArray = [];
var location = helpers.getRelativePosition(e);
helpers.each(this.segments,function(segment){
if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
},this);
return segmentsArray;
},
addData : function(segment, atIndex, silent){
var index = atIndex || this.segments.length;
this.segments.splice(index, 0, new this.SegmentArc({
fillColor: segment.color,
highlightColor: segment.highlight || segment.color,
label: segment.label,
value: segment.value,
outerRadius: (this.options.animateScale) ? 0 : this.scale.calculateCenterOffset(segment.value),
circumference: (this.options.animateRotate) ? 0 : this.scale.getCircumference(),
startAngle: Math.PI * 1.5
}));
if (!silent){
this.reflow();
this.update();
}
},
removeData: function(atIndex){
var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
this.segments.splice(indexToDelete, 1);
this.reflow();
this.update();
},
calculateTotal: function(data){
this.total = 0;
helpers.each(data,function(segment){
this.total += segment.value;
},this);
this.scale.valuesCount = this.segments.length;
},
updateScaleRange: function(datapoints){
var valuesArray = [];
helpers.each(datapoints,function(segment){
valuesArray.push(segment.value);
});
var scaleSizes = (this.options.scaleOverride) ?
{
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
} :
helpers.calculateScaleRange(
valuesArray,
helpers.min([this.chart.width, this.chart.height])/2,
this.options.scaleFontSize,
this.options.scaleBeginAtZero,
this.options.scaleIntegersOnly
);
helpers.extend(
this.scale,
scaleSizes,
{
size: helpers.min([this.chart.width, this.chart.height]),
xCenter: this.chart.width/2,
yCenter: this.chart.height/2
}
);
},
update : function(){
this.calculateTotal(this.segments);
helpers.each(this.segments,function(segment){
segment.save();
});
this.reflow();
this.render();
},
reflow : function(){
helpers.extend(this.SegmentArc.prototype,{
x : this.chart.width/2,
y : this.chart.height/2
});
this.updateScaleRange(this.segments);
this.scale.update();
helpers.extend(this.scale,{
xCenter: this.chart.width/2,
yCenter: this.chart.height/2
});
helpers.each(this.segments, function(segment){
segment.update({
outerRadius : this.scale.calculateCenterOffset(segment.value)
});
}, this);
},
draw : function(ease){
var easingDecimal = ease || 1;
//Clear & draw the canvas
this.clear();
helpers.each(this.segments,function(segment, index){
segment.transition({
circumference : this.scale.getCircumference(),
outerRadius : this.scale.calculateCenterOffset(segment.value)
},easingDecimal);
segment.endAngle = segment.startAngle + segment.circumference;
// If we've removed the first segment we need to set the first one to
// start at the top.
if (index === 0){
segment.startAngle = Math.PI * 1.5;
}
//Check to see if it's the last segment, if not get the next and update the start angle
if (index < this.segments.length - 1){
this.segments[index+1].startAngle = segment.endAngle;
}
segment.draw();
}, this);
this.scale.draw();
}
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
helpers = Chart.helpers;
Chart.Type.extend({
name: "Radar",
defaults:{
//Boolean - Whether to show lines for each scale point
scaleShowLine : true,
//Boolean - Whether we show the angle lines out of the radar
angleShowLineOut : true,
//Boolean - Whether to show labels on the scale
scaleShowLabels : false,
// Boolean - Whether the scale should begin at zero
scaleBeginAtZero : true,
//String - Colour of the angle line
angleLineColor : "rgba(0,0,0,.1)",
//Number - Pixel width of the angle line
angleLineWidth : 1,
//String - Point label font declaration
pointLabelFontFamily : "'Arial'",
//String - Point label font weight
pointLabelFontStyle : "normal",
//Number - Point label font size in pixels
pointLabelFontSize : 10,
//String - Point label font colour
pointLabelFontColor : "#666",
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 3,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius : 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>"
},
initialize: function(data){
this.PointClass = Chart.Point.extend({
strokeWidth : this.options.pointDotStrokeWidth,
radius : this.options.pointDotRadius,
display: this.options.pointDot,
hitDetectionRadius : this.options.pointHitDetectionRadius,
ctx : this.chart.ctx
});
this.datasets = [];
this.buildScale(data);
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activePointsCollection = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
this.eachPoints(function(point){
point.restore(['fillColor', 'strokeColor']);
});
helpers.each(activePointsCollection, function(activePoint){
activePoint.fillColor = activePoint.highlightFill;
activePoint.strokeColor = activePoint.highlightStroke;
});
this.showTooltip(activePointsCollection);
});
}
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset){
var datasetObject = {
label: dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
pointColor : dataset.pointColor,
pointStrokeColor : dataset.pointStrokeColor,
points : []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
var pointPosition;
if (!this.scale.animation){
pointPosition = this.scale.getPointPosition(index, this.scale.calculateCenterOffset(dataPoint));
}
datasetObject.points.push(new this.PointClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
x: (this.options.animation) ? this.scale.xCenter : pointPosition.x,
y: (this.options.animation) ? this.scale.yCenter : pointPosition.y,
strokeColor : dataset.pointStrokeColor,
fillColor : dataset.pointColor,
highlightFill : dataset.pointHighlightFill || dataset.pointColor,
highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
}));
},this);
},this);
this.render();
},
eachPoints : function(callback){
helpers.each(this.datasets,function(dataset){
helpers.each(dataset.points,callback,this);
},this);
},
getPointsAtEvent : function(evt){
var mousePosition = helpers.getRelativePosition(evt),
fromCenter = helpers.getAngleFromPoint({
x: this.scale.xCenter,
y: this.scale.yCenter
}, mousePosition);
var anglePerIndex = (Math.PI * 2) /this.scale.valuesCount,
pointIndex = Math.round((fromCenter.angle - Math.PI * 1.5) / anglePerIndex),
activePointsCollection = [];
// If we're at the top, make the pointIndex 0 to get the first of the array.
if (pointIndex >= this.scale.valuesCount || pointIndex < 0){
pointIndex = 0;
}
if (fromCenter.distance <= this.scale.drawingArea){
helpers.each(this.datasets, function(dataset){
activePointsCollection.push(dataset.points[pointIndex]);
});
}
return activePointsCollection;
},
buildScale : function(data){
this.scale = new Chart.RadialScale({
display: this.options.showScale,
fontStyle: this.options.scaleFontStyle,
fontSize: this.options.scaleFontSize,
fontFamily: this.options.scaleFontFamily,
fontColor: this.options.scaleFontColor,
showLabels: this.options.scaleShowLabels,
showLabelBackdrop: this.options.scaleShowLabelBackdrop,
backdropColor: this.options.scaleBackdropColor,
backgroundColors: this.options.scaleBackgroundColors,
backdropPaddingY : this.options.scaleBackdropPaddingY,
backdropPaddingX: this.options.scaleBackdropPaddingX,
lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
lineColor: this.options.scaleLineColor,
angleLineColor : this.options.angleLineColor,
angleLineWidth : (this.options.angleShowLineOut) ? this.options.angleLineWidth : 0,
// Point labels at the edge of each line
pointLabelFontColor : this.options.pointLabelFontColor,
pointLabelFontSize : this.options.pointLabelFontSize,
pointLabelFontFamily : this.options.pointLabelFontFamily,
pointLabelFontStyle : this.options.pointLabelFontStyle,
height : this.chart.height,
width: this.chart.width,
xCenter: this.chart.width/2,
yCenter: this.chart.height/2,
ctx : this.chart.ctx,
templateString: this.options.scaleLabel,
labels: data.labels,
valuesCount: data.datasets[0].data.length
});
this.scale.setScaleSize();
this.updateScaleRange(data.datasets);
this.scale.buildYLabels();
},
updateScaleRange: function(datasets){
var valuesArray = (function(){
var totalDataArray = [];
helpers.each(datasets,function(dataset){
if (dataset.data){
totalDataArray = totalDataArray.concat(dataset.data);
}
else {
helpers.each(dataset.points, function(point){
totalDataArray.push(point.value);
});
}
});
return totalDataArray;
})();
var scaleSizes = (this.options.scaleOverride) ?
{
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
} :
helpers.calculateScaleRange(
valuesArray,
helpers.min([this.chart.width, this.chart.height])/2,
this.options.scaleFontSize,
this.options.scaleBeginAtZero,
this.options.scaleIntegersOnly
);
helpers.extend(
this.scale,
scaleSizes
);
},
addData : function(valuesArray,label){
//Map the values array for each of the datasets
this.scale.valuesCount++;
helpers.each(valuesArray,function(value,datasetIndex){
var pointPosition = this.scale.getPointPosition(this.scale.valuesCount, this.scale.calculateCenterOffset(value));
this.datasets[datasetIndex].points.push(new this.PointClass({
value : value,
label : label,
datasetLabel: this.datasets[datasetIndex].label,
x: pointPosition.x,
y: pointPosition.y,
strokeColor : this.datasets[datasetIndex].pointStrokeColor,
fillColor : this.datasets[datasetIndex].pointColor
}));
},this);
this.scale.labels.push(label);
this.reflow();
this.update();
},
removeData : function(){
this.scale.valuesCount--;
this.scale.labels.shift();
helpers.each(this.datasets,function(dataset){
dataset.points.shift();
},this);
this.reflow();
this.update();
},
update : function(){
this.eachPoints(function(point){
point.save();
});
this.reflow();
this.render();
},
reflow: function(){
helpers.extend(this.scale, {
width : this.chart.width,
height: this.chart.height,
size : helpers.min([this.chart.width, this.chart.height]),
xCenter: this.chart.width/2,
yCenter: this.chart.height/2
});
this.updateScaleRange(this.datasets);
this.scale.setScaleSize();
this.scale.buildYLabels();
},
draw : function(ease){
var easeDecimal = ease || 1,
ctx = this.chart.ctx;
this.clear();
this.scale.draw();
helpers.each(this.datasets,function(dataset){
//Transition each point first so that the line and point drawing isn't out of sync
helpers.each(dataset.points,function(point,index){
if (point.hasValue()){
point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
}
},this);
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
helpers.each(dataset.points,function(point,index){
if (index === 0){
ctx.moveTo(point.x,point.y);
}
else{
ctx.lineTo(point.x,point.y);
}
},this);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = dataset.fillColor;
if(this.options.datasetFill){
ctx.fill();
}
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
helpers.each(dataset.points,function(point){
if (point.hasValue()){
point.draw();
}
});
},this);
}
});
}).call(this);
| abhishekathakur/epinsight | www/js/Chart.js | JavaScript | apache-2.0 | 118,111 |
/*!
* @overview Ember Data
* @copyright Copyright 2011-2014 Tilde Inc. and contributors.
* Portions Copyright 2011 LivingSocial Inc.
* @license Licensed under MIT license (see license.js)
* @version 1.0.0-beta.7+canary.b45e23ba
*/
(function(global) {
var define, requireModule, require, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = require = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("activemodel-adapter/lib/initializers",
["../../ember-data/lib/system/container_proxy","./system/active_model_serializer","./system/active_model_adapter"],
function(__dependency1__, __dependency2__, __dependency3__) {
"use strict";
var ContainerProxy = __dependency1__["default"];
var ActiveModelSerializer = __dependency2__["default"];
var ActiveModelAdapter = __dependency3__["default"];
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "activeModelAdapter",
initialize: function(container, application) {
var proxy = new ContainerProxy(container);
proxy.registerDeprecations([
{deprecated: 'serializer:_ams', valid: 'serializer:-active-model'},
{deprecated: 'adapter:_ams', valid: 'adapter:-active-model'}
]);
application.register('serializer:-active-model', ActiveModelSerializer);
application.register('adapter:-active-model', ActiveModelAdapter);
}
});
});
});
define("activemodel-adapter/lib/main",
["./system","./initializers","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ActiveModelAdapter = __dependency1__.ActiveModelAdapter;
var ActiveModelSerializer = __dependency1__.ActiveModelSerializer;
var EmbeddedRecordsMixin = __dependency1__.EmbeddedRecordsMixin;
__exports__.ActiveModelAdapter = ActiveModelAdapter;
__exports__.ActiveModelSerializer = ActiveModelSerializer;
__exports__.EmbeddedRecordsMixin = EmbeddedRecordsMixin;
});
define("activemodel-adapter/lib/system",
["./system/embedded_records_mixin","./system/active_model_adapter","./system/active_model_serializer","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var EmbeddedRecordsMixin = __dependency1__["default"];
var ActiveModelAdapter = __dependency2__["default"];
var ActiveModelSerializer = __dependency3__["default"];
__exports__.EmbeddedRecordsMixin = EmbeddedRecordsMixin;
__exports__.ActiveModelAdapter = ActiveModelAdapter;
__exports__.ActiveModelSerializer = ActiveModelSerializer;
});
define("activemodel-adapter/lib/system/active_model_adapter",
["../../../ember-data/lib/adapters","../../../ember-data/lib/system/adapter","../../../ember-inflector/lib/main","./active_model_serializer","./embedded_records_mixin","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var RESTAdapter = __dependency1__.RESTAdapter;
var InvalidError = __dependency2__.InvalidError;
var pluralize = __dependency3__.pluralize;
var ActiveModelSerializer = __dependency4__["default"];
var EmbeddedRecordsMixin = __dependency5__["default"];
/**
@module ember-data
*/
var forEach = Ember.EnumerableUtils.forEach;
var decamelize = Ember.String.decamelize,
underscore = Ember.String.underscore;
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelcasing.
It has been designed to work out of the box with the
[active_model_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.Adapter
**/
var ActiveModelAdapter = RESTAdapter.extend({
defaultSerializer: '-active-model',
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} type
@returns String
*/
pathForType: function(type) {
var decamelized = decamelize(type);
var underscored = underscore(decamelized);
return pluralize(underscored);
},
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method ajaxError
@param jqXHR
@returns error
*/
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText),
errors = {};
if (response.errors !== undefined) {
var jsonErrors = response.errors;
forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
}
return new InvalidError(errors);
} else {
return error;
}
}
});
__exports__["default"] = ActiveModelAdapter;
});
define("activemodel-adapter/lib/system/active_model_serializer",
["../../../ember-inflector/lib/main","../../../ember-data/lib/serializers/rest_serializer","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var singularize = __dependency1__.singularize;
var RESTSerializer = __dependency2__["default"];
/**
@module ember-data
*/
var get = Ember.get,
forEach = Ember.EnumerableUtils.forEach,
camelize = Ember.String.camelize,
capitalize = Ember.String.capitalize,
decamelize = Ember.String.decamelize,
underscore = Ember.String.underscore;
var ActiveModelSerializer = RESTSerializer.extend({
// SERIALIZE
/**
Converts camelcased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@returns String
*/
keyForAttribute: function(attr) {
return decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} key
@param {String} kind
@returns String
*/
keyForRelationship: function(key, kind) {
key = decamelize(key);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return singularize(key) + "_ids";
} else {
return key;
}
},
/**
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
/**
Underscores the JSON root keys when serializing.
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(data, type, record, options) {
var root = underscore(decamelize(type.typeKey));
data[root] = this.serialize(record, options);
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute(key);
json[key + "_type"] = capitalize(camelize(belongsTo.constructor.typeKey));
},
// EXTRACT
/**
Extracts the model typeKey from underscored root objects.
@method typeForRoot
@param {String} root
@returns String the model's typeKey
*/
typeForRoot: function(root) {
var camelized = camelize(root);
return singularize(camelized);
},
/**
Add extra step to `DS.RESTSerializer.normalize` so links are
normalized.
If your payload looks like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@returns Object
*/
normalize: function(type, hash, prop) {
this.normalizeLinks(hash);
return this._super(type, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} hash
*/
normalizeLinks: function(data){
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
Normalize the polymorphic type from the JSON.
Normalize:
```js
{
id: "1"
minion: { type: "evil_minion", id: "12"}
}
```
To:
```js
{
id: "1"
minion: { type: "evilMinion", id: "12"}
}
```
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, payload;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
if (relationship.options.polymorphic) {
payloadKey = this.keyForAttribute(key);
payload = hash[payloadKey];
if (payload && payload.type) {
payload.type = this.typeForRoot(payload.type);
} else if (payload && relationship.kind === "hasMany") {
var self = this;
forEach(payload, function(single) {
single.type = self.typeForRoot(single.type);
});
}
} else {
payloadKey = this.keyForRelationship(key, relationship.kind);
payload = hash[payloadKey];
}
hash[key] = payload;
if (key !== payloadKey) {
delete hash[payloadKey];
}
}, this);
}
}
});
__exports__["default"] = ActiveModelSerializer;
});
define("activemodel-adapter/lib/system/embedded_records_mixin",
["../../../ember-inflector/lib/main","exports"],
function(__dependency1__, __exports__) {
"use strict";
var get = Ember.get;
var forEach = Ember.EnumerableUtils.forEach;
var pluralize = __dependency1__.pluralize;
/**
The EmbeddedRecordsMixin allows you to add embedded record support to your
serializers.
To set up embedded records, you include the mixin into the serializer and then
define your embedded relations.
```js
App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
})
```
Currently only `{embedded: 'always'}` records are supported.
@class EmbeddedRecordsMixin
@namespace DS
*/
var EmbeddedRecordsMixin = Ember.Mixin.create({
/**
Serialize has-may relationship when it is configured as embedded objects.
@method serializeHasMany
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key,
attrs = get(this, 'attrs'),
embed = attrs && attrs[key] && attrs[key].embedded === 'always';
if (embed) {
json[this.keyForAttribute(key)] = get(record, key).map(function(relation) {
var data = relation.serialize(),
primaryKey = get(this, 'primaryKey');
data[primaryKey] = get(relation, primaryKey);
return data;
}, this);
}
},
/**
Extract embedded objects out of the payload for a single object
and add them as sideloaded objects instead.
@method extractSingle
*/
extractSingle: function(store, primaryType, payload, recordId, requestType) {
var root = this.keyForAttribute(primaryType.typeKey),
partial = payload[root];
updatePayloadWithEmbedded(store, this, primaryType, partial, payload);
return this._super(store, primaryType, payload, recordId, requestType);
},
/**
Extract embedded objects out of a standard payload
and add them as sideloaded objects instead.
@method extractArray
*/
extractArray: function(store, type, payload) {
var root = this.keyForAttribute(type.typeKey),
partials = payload[pluralize(root)];
forEach(partials, function(partial) {
updatePayloadWithEmbedded(store, this, type, partial, payload);
}, this);
return this._super(store, type, payload);
}
});
function updatePayloadWithEmbedded(store, serializer, type, partial, payload) {
var attrs = get(serializer, 'attrs');
if (!attrs) {
return;
}
type.eachRelationship(function(key, relationship) {
var expandedKey, embeddedTypeKey, attribute, ids,
config = attrs[key],
serializer = store.serializerFor(relationship.type.typeKey),
primaryKey = get(serializer, "primaryKey");
if (relationship.kind !== "hasMany") {
return;
}
if (config && (config.embedded === 'always' || config.embedded === 'load')) {
// underscore forces the embedded records to be side loaded.
// it is needed when main type === relationship.type
embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey);
expandedKey = this.keyForRelationship(key, relationship.kind);
attribute = this.keyForAttribute(key);
ids = [];
if (!partial[attribute]) {
return;
}
payload[embeddedTypeKey] = payload[embeddedTypeKey] || [];
forEach(partial[attribute], function(data) {
var embeddedType = store.modelFor(relationship.type.typeKey);
updatePayloadWithEmbedded(store, serializer, embeddedType, data, payload);
ids.push(data[primaryKey]);
payload[embeddedTypeKey].push(data);
});
partial[expandedKey] = ids;
delete partial[attribute];
}
}, serializer);
}
__exports__["default"] = EmbeddedRecordsMixin;
});
define("ember-data/lib/adapters",
["./adapters/fixture_adapter","./adapters/rest_adapter","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var FixtureAdapter = __dependency1__["default"];
var RESTAdapter = __dependency2__["default"];
__exports__.RESTAdapter = RESTAdapter;
__exports__.FixtureAdapter = FixtureAdapter;
});
define("ember-data/lib/adapters/fixture_adapter",
["../system/adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, fmt = Ember.String.fmt,
indexOf = Ember.EnumerableUtils.indexOf;
var counter = 0;
var Adapter = __dependency1__["default"];
/**
`DS.FixtureAdapter` is an adapter that loads records from memory.
Its primarily used for development and testing. You can also use
`DS.FixtureAdapter` while working on the API but are not ready to
integrate yet. It is a fully functioning adapter. All CRUD methods
are implemented. You can also implement query logic that a remote
system would do. Its possible to do develop your entire application
with `DS.FixtureAdapter`.
For information on how to use the `FixtureAdapter` in your
application please see the [FixtureAdapter
guide](/guides/models/the-fixture-adapter/).
@class FixtureAdapter
@namespace DS
@extends DS.Adapter
*/
var FixtureAdapter = Adapter.extend({
// by default, fixtures are already in normalized form
serializer: null,
/**
If `simulateRemoteResponse` is `true` the `FixtureAdapter` will
wait a number of milliseconds before resolving promises with the
fixture values. The wait time can be configured via the `latency`
property.
@property simulateRemoteResponse
@type {Boolean}
@default true
*/
simulateRemoteResponse: true,
/**
By default the `FixtureAdapter` will simulate a wait of the
`latency` milliseconds before resolving promises with the fixture
values. This behavior can be turned off via the
`simulateRemoteResponse` property.
@property latency
@type {Number}
@default 50
*/
latency: 50,
/**
Implement this method in order to provide data associated with a type
@method fixturesForType
@param {Subclass of DS.Model} type
@return {Array}
*/
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture){
var fixtureIdType = typeof fixture.id;
if(fixtureIdType !== "number" && fixtureIdType !== "string"){
throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture]));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
/**
Implement this method in order to query fixtures data
@method queryFixtures
@param {Array} fixture
@param {Object} query
@param {Subclass of DS.Model} type
@return {Promise|Array}
*/
queryFixtures: function(fixtures, query, type) {
Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.');
},
/**
@method updateFixtures
@param {Subclass of DS.Model} type
@param {Array} fixture
*/
updateFixtures: function(type, fixture) {
if(!type.FIXTURES) {
type.FIXTURES = [];
}
var fixtures = type.FIXTURES;
this.deleteLoadedFixture(type, fixture);
fixtures.push(fixture);
},
/**
Implement this method in order to provide json for CRUD methods
@method mockJSON
@param {Subclass of DS.Model} type
@param {DS.Model} record
*/
mockJSON: function(store, type, record) {
return store.serializerFor(type).serialize(record, { includeId: true });
},
/**
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
@return {String} id
*/
generateIdForRecord: function(store) {
return "fixture-" + counter++;
},
/**
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: function(store, type, id) {
var fixtures = this.fixturesForType(type),
fixture;
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixture = Ember.A(fixtures).findProperty('id', id);
}
if (fixture) {
return this.simulateRemoteCall(function() {
return fixture;
}, this);
}
},
/**
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@return {Promise} promise
*/
findMany: function(store, type, ids) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixtures = fixtures.filter(function(item) {
return indexOf(ids, item.id) !== -1;
});
}
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function(store, type) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
},
/**
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: function(store, type, query, array) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type " + type.toString(), fixtures);
fixtures = this.queryFixtures(fixtures, query, type);
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.deleteLoadedFixture(type, fixture);
return this.simulateRemoteCall(function() {
// no payload in a deletion
return null;
});
},
/*
@method deleteLoadedFixture
@private
@param type
@param record
*/
deleteLoadedFixture: function(type, record) {
var existingFixture = this.findExistingFixture(type, record);
if(existingFixture) {
var index = indexOf(type.FIXTURES, existingFixture);
type.FIXTURES.splice(index, 1);
return true;
}
},
/*
@method findExistingFixture
@private
@param type
@param record
*/
findExistingFixture: function(type, record) {
var fixtures = this.fixturesForType(type);
var id = get(record, 'id');
return this.findFixtureById(fixtures, id);
},
/*
@method findFixtureById
@private
@param fixtures
@param id
*/
findFixtureById: function(fixtures, id) {
return Ember.A(fixtures).find(function(r) {
if(''+get(r, 'id') === ''+id) {
return true;
} else {
return false;
}
});
},
/*
@method simulateRemoteCall
@private
@param callback
@param context
*/
simulateRemoteCall: function(callback, context) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve) {
if (get(adapter, 'simulateRemoteResponse')) {
// Schedule with setTimeout
Ember.run.later(function() {
resolve(callback.call(context));
}, get(adapter, 'latency'));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.schedule('actions', null, function() {
resolve(callback.call(context));
});
}
}, "DS: FixtureAdapter#simulateRemoteCall");
}
});
__exports__["default"] = FixtureAdapter;
});
define("ember-data/lib/adapters/rest_adapter",
["../system/adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Adapter = __dependency1__["default"];
var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;
/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"post": {
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
}
}
```
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"person": {
"firstName": "Barack",
"lastName": "Obama",
"occupation": "President"
}
}
```
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```js
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Person` would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```js
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. An array of
headers can be added to the adapter which are passed with every request:
```js
DS.RESTAdapter.reopen({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
*/
var RESTAdapter = Adapter.extend({
defaultSerializer: '-rest',
/**
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```javascript
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Post` would now target `/api/1/post/`.
@property namespace
@type {String}
*/
/**
An adapter can target other hosts by setting the `host` property.
```javascript
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
Requests for `App.Post` would now target `https://api.example.com/post/`.
@property host
@type {String}
*/
/**
Some APIs require HTTP headers, e.g. to provide an API key. An array of
headers can be added to the adapter which are passed with every request:
```javascript
DS.RESTAdapter.reopen({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@property headers
@type {Object}
*/
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the query string.
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@returns {Promise} promise
*/
find: function(store, type, id) {
return this.ajax(this.buildURL(type.typeKey, id), 'GET');
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@returns {Promise} promise
*/
findAll: function(store, type, sinceToken) {
var query;
if (sinceToken) {
query = { since: sinceToken };
}
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@returns {Promise} promise
*/
findQuery: function(store, type, query) {
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as IDs.
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array} ids
@returns {Promise} promise
*/
findMany: function(store, type, ids) {
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
If the URL is host-relative (starting with a single slash), the
request will use the host specified on the adapter (if any).
@method findHasMany
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@returns {Promise} promise
*/
findHasMany: function(store, record, url) {
var host = get(this, 'host'),
id = get(record, 'id'),
type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a belongs-to relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findBelongsTo
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@returns {Promise} promise
*/
findBelongsTo: function(store, record, url) {
var id = get(record, 'id'),
type = record.constructor.typeKey;
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns {Promise} promise
*/
createRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record, { includeId: true });
return this.ajax(this.buildURL(type.typeKey), "POST", { data: data });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns {Promise} promise
*/
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns {Promise} promise
*/
deleteRecord: function(store, type, record) {
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id), "DELETE");
},
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example, 'post'
becomes 'posts' and 'person' becomes 'people'). To override the
pluralization see [pathForType](#method_pathForType).
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
@method buildURL
@param {String} type
@param {String} id
@returns {String} url
*/
buildURL: function(type, id) {
var url = [],
host = get(this, 'host'),
prefix = this.urlPrefix();
if (type) { url.push(this.pathForType(type)); }
if (id) { url.push(id); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url) { url = '/' + url; }
return url;
},
/**
@method urlPrefix
@private
@param {String} path
@param {String} parentUrl
@return {String} urlPrefix
*/
urlPrefix: function(path, parentURL) {
var host = get(this, 'host'),
namespace = get(this, 'namespace'),
url = [];
if (path) {
// Absolute path
if (path.charAt(0) === '/') {
if (host) {
path = path.slice(1);
url.push(host);
}
// Relative path
} else if (!/^http(s)?:\/\//.test(path)) {
url.push(parentURL);
}
} else {
if (host) { url.push(host); }
if (namespace) { url.push(namespace); }
}
if (path) {
url.push(path);
}
return url.join('/');
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```js
DS.RESTAdapter.reopen({
pathForType: function(type) {
var decamelized = Ember.String.decamelize(type);
return Ember.String.pluralize(decamelized);
};
});
```
@method pathForType
@param {String} type
@returns {String} path
**/
pathForType: function(type) {
var camelized = Ember.String.camelize(type);
return Ember.String.pluralize(camelized);
},
/**
Takes an ajax response, and returns a relevant error.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record.
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"];
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
Note: As a correctness optimization, the default implementation of
the `ajaxError` method strips out the `then` method from jquery's
ajax response (jqXHR). This is important because the jqXHR's
`then` method fulfills the promise with itself resulting in a
circular "thenable" chain which may cause problems for some
promise libraries.
@method ajaxError
@param {Object} jqXHR
@return {Object} jqXHR
*/
ajaxError: function(jqXHR) {
if (jqXHR) {
jqXHR.then = null;
}
return jqXHR;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} hash
@return {Promise} promise
*/
ajax: function(url, type, hash) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
hash = adapter.ajaxOptions(url, type, hash);
hash.success = function(json) {
Ember.run(null, resolve, json);
};
hash.error = function(jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR));
};
Ember.$.ajax(hash);
}, "DS: RestAdapter#ajax " + type + " to " + url);
},
/**
@method ajaxOptions
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} hash
@return {Object} hash
*/
ajaxOptions: function(url, type, hash) {
hash = hash || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
if (this.headers !== undefined) {
var headers = this.headers;
hash.beforeSend = function (xhr) {
forEach.call(Ember.keys(headers), function(key) {
xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
}
});
__exports__["default"] = RESTAdapter;
});
define("ember-data/lib/core",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
/**
All Ember Data methods and functions are defined inside of this namespace.
@class DS
@static
*/
var DS;
if ('undefined' === typeof DS) {
/**
@property VERSION
@type String
@default '1.0.0-beta.7+canary.b45e23ba'
@static
*/
DS = Ember.Namespace.create({
VERSION: '1.0.0-beta.7+canary.b45e23ba'
});
if ('undefined' !== typeof window) {
window.DS = DS;
}
if (Ember.libraries) {
Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION);
}
}
__exports__["default"] = DS;
});
define("ember-data/lib/ext/date",
[],
function() {
"use strict";
/**
@module ember-data
*/
/**
Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
© 2011 Colin Snover <http://zetafleet.com>
Released under MIT license.
@class Date
@namespace Ember
@static
*/
Ember.Date = Ember.Date || {};
var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
/**
@method parse
@param date
*/
Ember.Date.parse = function (date) {
var timestamp, struct, minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; (k = numericKeys[i]); ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
}
else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) {
Date.parse = Ember.Date.parse;
}
});
define("ember-data/lib/initializers",
["./system/store","./serializers","./adapters","./system/debug/debug_adapter","./system/container_proxy","./transforms"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__) {
"use strict";
var Store = __dependency1__["default"];
var JSONSerializer = __dependency2__.JSONSerializer;
var RESTSerializer = __dependency2__.RESTSerializer;
var RESTAdapter = __dependency3__.RESTAdapter;
var DebugAdapter = __dependency4__["default"];
var ContainerProxy = __dependency5__["default"];
var BooleanTransform = __dependency6__.BooleanTransform;
var DateTransform = __dependency6__.DateTransform;
var StringTransform = __dependency6__.StringTransform;
var NumberTransform = __dependency6__.NumberTransform;
/**
@module ember-data
*/
var set = Ember.set;
/*
This code registers an injection for Ember.Application.
If an Ember.js developer defines a subclass of DS.Store on their application,
this code will automatically instantiate it and make it available on the
router.
Additionally, after an application's controllers have been injected, they will
each have the store made available to them.
For example, imagine an Ember.js application with the following classes:
App.Store = DS.Store.extend({
adapter: 'custom'
});
App.PostsController = Ember.ArrayController.extend({
// ...
});
When the application is initialized, `App.Store` will automatically be
instantiated, and the instance of `App.PostsController` will have its `store`
property set to that instance.
Note that this code will only be run if the `ember-application` package is
loaded. If Ember Data is being used in an environment other than a
typical application (e.g., node.js where only `ember-runtime` is available),
this code will be ignored.
*/
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "store",
initialize: function(container, application) {
application.register('store:main', application.Store || Store);
// allow older names to be looked up
var proxy = new ContainerProxy(container);
proxy.registerDeprecations([
{deprecated: 'serializer:_default', valid: 'serializer:-default'},
{deprecated: 'serializer:_rest', valid: 'serializer:-rest'},
{deprecated: 'adapter:_rest', valid: 'adapter:-rest'}
]);
// new go forward paths
application.register('serializer:-default', JSONSerializer);
application.register('serializer:-rest', RESTSerializer);
application.register('adapter:-rest', RESTAdapter);
// Eagerly generate the store so defaultStore is populated.
// TODO: Do this in a finisher hook
container.lookup('store:main');
}
});
Application.initializer({
name: "transforms",
before: "store",
initialize: function(container, application) {
application.register('transform:boolean', BooleanTransform);
application.register('transform:date', DateTransform);
application.register('transform:number', NumberTransform);
application.register('transform:string', StringTransform);
}
});
Application.initializer({
name: "data-adapter",
before: "store",
initialize: function(container, application) {
application.register('data-adapter:main', DebugAdapter);
}
});
Application.initializer({
name: "injectStore",
before: "store",
initialize: function(container, application) {
application.inject('controller', 'store', 'store:main');
application.inject('route', 'store', 'store:main');
application.inject('serializer', 'store', 'store:main');
application.inject('data-adapter', 'store', 'store:main');
}
});
});
});
define("ember-data/lib/main",
["./core","./ext/date","./system/store","./system/model","./system/changes","./system/adapter","./system/debug","./system/record_arrays","./system/record_array_manager","./adapters","./serializers/json_serializer","./serializers/rest_serializer","../../ember-inflector/lib/main","../../activemodel-adapter/lib/main","./transforms","./system/relationships","./initializers","./system/container_proxy","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __dependency16__, __dependency17__, __dependency18__, __exports__) {
"use strict";
/**
Ember Data
@module ember-data
@main ember-data
*/
// support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast
Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve;
var DS = __dependency1__["default"];
var Store = __dependency3__.Store;
var PromiseArray = __dependency3__.PromiseArray;
var PromiseObject = __dependency3__.PromiseObject;
var Model = __dependency4__.Model;
var Errors = __dependency4__.Errors;
var RootState = __dependency4__.RootState;
var attr = __dependency4__.attr;
var AttributeChange = __dependency5__.AttributeChange;
var RelationshipChange = __dependency5__.RelationshipChange;
var RelationshipChangeAdd = __dependency5__.RelationshipChangeAdd;
var RelationshipChangeRemove = __dependency5__.RelationshipChangeRemove;
var OneToManyChange = __dependency5__.OneToManyChange;
var ManyToNoneChange = __dependency5__.ManyToNoneChange;
var OneToOneChange = __dependency5__.OneToOneChange;
var ManyToManyChange = __dependency5__.ManyToManyChange;
var InvalidError = __dependency6__.InvalidError;
var Adapter = __dependency6__.Adapter;
var DebugAdapter = __dependency7__["default"];
var RecordArray = __dependency8__.RecordArray;
var FilteredRecordArray = __dependency8__.FilteredRecordArray;
var AdapterPopulatedRecordArray = __dependency8__.AdapterPopulatedRecordArray;
var ManyArray = __dependency8__.ManyArray;
var RecordArrayManager = __dependency9__["default"];
var RESTAdapter = __dependency10__.RESTAdapter;
var FixtureAdapter = __dependency10__.FixtureAdapter;
var JSONSerializer = __dependency11__["default"];
var RESTSerializer = __dependency12__["default"];
var ActiveModelAdapter = __dependency14__.ActiveModelAdapter;
var ActiveModelSerializer = __dependency14__.ActiveModelSerializer;
var EmbeddedRecordsMixin = __dependency14__.EmbeddedRecordsMixin;
var Transform = __dependency15__.Transform;
var DateTransform = __dependency15__.DateTransform;
var NumberTransform = __dependency15__.NumberTransform;
var StringTransform = __dependency15__.StringTransform;
var BooleanTransform = __dependency15__.BooleanTransform;
var hasMany = __dependency16__.hasMany;
var belongsTo = __dependency16__.belongsTo;
var ContainerProxy = __dependency18__["default"];
DS.Store = Store;
DS.PromiseArray = PromiseArray;
DS.PromiseObject = PromiseObject;
DS.Model = Model;
DS.RootState = RootState;
DS.attr = attr;
DS.Errors = Errors;
DS.AttributeChange = AttributeChange;
DS.RelationshipChange = RelationshipChange;
DS.RelationshipChangeAdd = RelationshipChangeAdd;
DS.OneToManyChange = OneToManyChange;
DS.ManyToNoneChange = OneToManyChange;
DS.OneToOneChange = OneToOneChange;
DS.ManyToManyChange = ManyToManyChange;
DS.Adapter = Adapter;
DS.InvalidError = InvalidError;
DS.DebugAdapter = DebugAdapter;
DS.RecordArray = RecordArray;
DS.FilteredRecordArray = FilteredRecordArray;
DS.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray;
DS.ManyArray = ManyArray;
DS.RecordArrayManager = RecordArrayManager;
DS.RESTAdapter = RESTAdapter;
DS.FixtureAdapter = FixtureAdapter;
DS.RESTSerializer = RESTSerializer;
DS.JSONSerializer = JSONSerializer;
DS.Transform = Transform;
DS.DateTransform = DateTransform;
DS.StringTransform = StringTransform;
DS.NumberTransform = NumberTransform;
DS.BooleanTransform = BooleanTransform;
DS.ActiveModelAdapter = ActiveModelAdapter;
DS.ActiveModelSerializer = ActiveModelSerializer;
DS.EmbeddedRecordsMixin = EmbeddedRecordsMixin;
DS.belongsTo = belongsTo;
DS.hasMany = hasMany;
DS.ContainerProxy = ContainerProxy;
__exports__["default"] = DS;
});
define("ember-data/lib/serializers",
["./serializers/json_serializer","./serializers/rest_serializer","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var JSONSerializer = __dependency1__["default"];
var RESTSerializer = __dependency2__["default"];
__exports__.JSONSerializer = JSONSerializer;
__exports__.RESTSerializer = RESTSerializer;
});
define("ember-data/lib/serializers/json_serializer",
["exports"],
function(__exports__) {
"use strict";
var get = Ember.get, set = Ember.set, isNone = Ember.isNone;
/**
In Ember Data a Serializer is used to serialize and deserialize
records when they are transferred in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializing relationships.
For maximum performance Ember Data recommends you use the
[RESTSerializer](DS.RESTSerializer.html) or one of its subclasses.
`JSONSerializer` is useful for simpler or legacy backends that may
not support the http://jsonapi.org/ spec.
@class JSONSerializer
@namespace DS
*/
var JSONSerializer = Ember.Object.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {subclass of DS.Model} type
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function(type, data) {
type.eachTransformedAttribute(function(key, type) {
var transform = this.transformFor(type);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalize: function(type, hash) {
var fields = Ember.get(type, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@return {Object}
*/
normalize: function(type, hash) {
if (!hash) { return hash; }
this.applyTransforms(type, hash);
return hash;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```javascript
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapProperty('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {subclass of DS.Model} record
@param {Object} options
@return {Object} json
*/
serialize: function(record, options) {
var json = {};
if (options && options.includeId) {
var id = get(record, 'id');
if (id) {
json[get(this, 'primaryKey')] = id;
}
}
record.eachAttribute(function(key, attribute) {
this.serializeAttribute(record, json, key, attribute);
}, this);
record.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(record, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(record, json, relationship);
}
}, this);
return json;
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all you attributes were always
serialized as properties on an `attributes` object you could
write:
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serializeAttribute: function(record, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(record, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Model} record
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function(record, json, key, attribute) {
var attrs = get(this, 'attrs');
var value = get(record, key), type = attribute.type;
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key);
json[key] = value;
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
if (isNone(belongsTo)) {
json[key] = belongsTo;
} else {
json[key] = get(belongsTo, 'id');
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(record, json, relationship);
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[key] = get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany relationships
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```javascript
App.CommentSerializer = DS.JSONSerializer.extend({
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "_type"] = belongsTo.constructor.typeKey;
}
});
```
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method delegates to a more specific extract method based on
the `requestType`.
Example
```javascript
var get = Ember.get;
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
var type = store.modelFor(modelName);
var serializer = store.serializerFor(type.typeKey);
var record = serializer.extract(store, type, data, get(data, 'id'), 'single');
store.push(modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function(store, type, payload, id, requestType) {
this.extractMeta(store, type, payload);
var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, type, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindAll: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindQuery: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindMany: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: function(store, type, payload){
return this.extractArray(store, type, payload);
},
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Store#createRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractCreateRecord: function(store, type, payload) {
return this.extractSave(store, type, payload);
},
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Store#update`. By default this method is alias
for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractUpdateRecord: function(store, type, payload) {
return this.extractSave(store, type, payload);
},
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Store#deleteRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractDeleteRecord: function(store, type, payload) {
return this.extractSave(store, type, payload);
},
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractFind: function(store, type, payload) {
return this.extractSingle(store, type, payload);
},
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: function(store, type, payload) {
return this.extractSingle(store, type, payload);
},
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractSave: function(store, type, payload) {
return this.extractSingle(store, type, payload);
},
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractSingle: function(store, type, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, type, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractSingle: function(store, type, payload) {
return this.normalize(type, payload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractArray: function(store, type, payload) {
return payload.map(function(json) {
return this.extractSingle(store, type, json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractArray: function(store, type, payload) {
return this.normalize(type, payload);
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractMeta: function(store, type, payload) {
if (payload && payload._pagination) {
store.metaForType(type, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
*/
extractMeta: function(store, type, payload) {
if (payload && payload.meta) {
store.metaForType(type, payload.meta);
delete payload.meta;
}
},
/**
`keyForAttribute` can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
Example
```javascript
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
@method keyForAttribute
@param {String} key
@return {String} normalized key
*/
/**
`keyForRelationship` can be used to define a custom key when
serializing relationship properties. By default `JSONSerializer`
does not provide an implementation of this method.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} relationship type
@return {String} normalized key
*/
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function(attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform);
return transform;
}
});
__exports__["default"] = JSONSerializer;
});
define("ember-data/lib/serializers/rest_serializer",
["./json_serializer","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var JSONSerializer = __dependency1__["default"];
var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;
var map = Ember.ArrayPolyfills.map;
function coerceId(id) {
return id == null ? null : id+'';
}
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method and individual normalizations under
`normalizeHash`.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to defined
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Parse, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, and the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
var RESTSerializer = JSONSerializer.extend({
/**
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, given the following json where the the `IDs` under
`"comments"` are provided as `_id` instead of `id`.
```javascript
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"_id": 1,
"body": "FIRST"
}, {
"_id": 2,
"body": "Rails is unagi"
}]
}
```
You use `normalizeHash` to normalize just the comments:
```javascript
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is usually just the original key
that was in the original payload. However, key names will be
impacted by any modifications done in the `normalizePayload`
method. The `DS.RESTSerializer`'s default implementation makes no
changes to the payload keys.
@property normalizeHash
@type {Object}
@default undefined
*/
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
For example, if you have a payload that looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"id": 1,
"body": "FIRST"
}, {
"id": 2,
"body": "Rails is unagi"
}]
}
```
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```js
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is just the original key that was in the original
payload.
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@returns {Object}
*/
normalize: function(type, hash, prop) {
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
this.normalizeUsingDeclaredMapping(type, hash);
if (this.normalizeHash && this.normalizeHash[prop]) {
this.normalizeHash[prop](hash);
}
return this._super(type, hash, prop);
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function(type, payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {subclass of DS.Model} type
@param {Object} hash
@returns {Object} the normalized payload
*/
normalizePayload: function(type, payload) {
return payload;
},
/**
@method normalizeId
@private
*/
normalizeId: function(hash) {
var primaryKey = get(this, 'primaryKey');
if (primaryKey === 'id') { return; }
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function(type, hash) {
var attrs = get(this, 'attrs'), payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = attrs[key];
if (payloadKey && payloadKey.key) {
payloadKey = payloadKey.key;
}
if (typeof payloadKey === 'string') {
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function(type, hash) {
var payloadKey, key;
if (this.keyForAttribute) {
type.eachAttribute(function(key) {
payloadKey = this.keyForAttribute(key);
if (key === payloadKey) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, key;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (key === payloadKey) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
Called when the server has returned a payload representing
a single record, such as in response to a `find` or `save`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
post 1:
```js
{
"id": 1,
"title": "Rails is omakase",
"_embedded": {
"comment": [{
"_id": 1,
"comment_title": "FIRST"
}, {
"_id": 2,
"comment_title": "Rails is unagi"
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
extractSingle: function(store, type, payload, id, requestType) {
var comments = payload._embedded.comment;
delete payload._embedded;
payload = { comments: comments, post: payload };
return this._super(store, type, payload, id, requestType);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractSingle`, the
built-in implementation will find the primary record in your normalized
payload and push the remaining records into the store.
The primary record is the single hash found under `post` or the first
element of the `posts` array.
The primary record has special meaning when the record is being created
for the first time or updated (`createRecord` or `updateRecord`). In
particular, it will update the properties of the record that was saved.
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String} id
@param {'find'|'createRecord'|'updateRecord'|'deleteRecord'} requestType
@returns {Object} the primary response to the original request
*/
extractSingle: function(store, primaryType, payload, recordId, requestType) {
payload = this.normalizePayload(primaryType, payload);
var primaryTypeName = primaryType.typeKey,
primaryRecord;
for (var prop in payload) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName),
isPrimary = type.typeKey === primaryTypeName;
// legacy support for singular resources
if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) {
primaryRecord = this.normalize(primaryType, payload[prop], prop);
continue;
}
/*jshint loopfunc:true*/
forEach.call(payload[prop], function(hash) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName),
typeSerializer = store.serializerFor(type);
hash = typeSerializer.normalize(type, hash, prop);
var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord,
isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId;
// find the primary record.
//
// It's either:
// * the record with the same ID as the original request
// * in the case of a newly created record that didn't have an ID, the first
// record in the Array
if (isFirstCreatedRecord || isUpdatedRecord) {
primaryRecord = hash;
} else {
store.push(typeName, hash);
}
}, this);
}
return primaryRecord;
},
/**
Called when the server has returned a payload representing
multiple records, such as in response to a `findAll` or `findQuery`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
all posts:
```js
{
"_embedded": {
"post": [{
"id": 1,
"title": "Rails is omakase"
}, {
"id": 2,
"title": "The Parley Letter"
}],
"comment": [{
"_id": 1,
"comment_title": "Rails is unagi"
"post_id": 1
}, {
"_id": 2,
"comment_title": "Don't tread on me",
"post_id": 2
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
// and the comments are listed under a post's `comments` key.
extractArray: function(store, type, payload, id, requestType) {
var posts = payload._embedded.post;
var comments = [];
var postCache = {};
posts.forEach(function(post) {
post.comments = [];
postCache[post.id] = post;
});
payload._embedded.comment.forEach(function(comment) {
comments.push(comment);
postCache[comment.post_id].comments.push(comment);
delete comment.post_id;
}
payload = { comments: comments, posts: payload };
return this._super(store, type, payload, id, requestType);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractArray`, the
built-in implementation will find the primary array in your normalized
payload and push the remaining records into the store.
The primary array is the array found under `posts`.
The primary record has special meaning when responding to `findQuery`
or `findHasMany`. In particular, the primary array will become the
list of records in the record array that kicked off the request.
If your primary array contains secondary (embedded) records of the same type,
you cannot place these into the primary array `posts`. Instead, place the
secondary items into an underscore prefixed property `_posts`, which will
push these items into the store and will not affect the resulting query.
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {'findAll'|'findMany'|'findHasMany'|'findQuery'} requestType
@returns {Array} The primary array that was returned in response
to the original query.
*/
extractArray: function(store, primaryType, payload) {
payload = this.normalizePayload(primaryType, payload);
var primaryTypeName = primaryType.typeKey,
primaryArray;
for (var prop in payload) {
var typeKey = prop,
forcedSecondary = false;
if (prop.charAt(0) === '_') {
forcedSecondary = true;
typeKey = prop.substr(1);
}
var typeName = this.typeForRoot(typeKey),
type = store.modelFor(typeName),
typeSerializer = store.serializerFor(type),
isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName));
/*jshint loopfunc:true*/
var normalizedArray = map.call(payload[prop], function(hash) {
return typeSerializer.normalize(type, hash, prop);
}, this);
if (isPrimary) {
primaryArray = normalizedArray;
} else {
store.pushMany(typeName, normalizedArray);
}
}
return primaryArray;
},
/**
This method allows you to push a payload containing top-level
collections of records organized per type.
```js
{
"posts": [{
"id": "1",
"title": "Rails is omakase",
"author", "1",
"comments": [ "1" ]
}],
"comments": [{
"id": "1",
"body": "FIRST"
}],
"users": [{
"id": "1",
"name": "@d2h"
}]
}
```
It will first normalize the payload, so you can use this to push
in data streaming in from your server structured the same way
that fetches and saves are structured.
@method pushPayload
@param {DS.Store} store
@param {Object} payload
*/
pushPayload: function(store, payload) {
payload = this.normalizePayload(null, payload);
for (var prop in payload) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName);
/*jshint loopfunc:true*/
var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) {
return this.normalize(type, hash, prop);
}, this);
store.pushMany(typeName, normalizedArray);
}
},
/**
You can use this method to normalize the JSON root keys returned
into the model type expected by your store.
For example, your server may return underscored root keys rather than
the expected camelcased versions.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
typeForRoot: function(root) {
var camelized = Ember.String.camelize(root);
return Ember.String.singularize(camelized);
}
});
```
@method typeForRoot
@param {String} root
@returns {String} the model's typeKey
*/
typeForRoot: function(root) {
return Ember.String.singularize(root);
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```js
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```js
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapProperty('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```js
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = this._super(record, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param record
@param options
*/
serialize: function(record, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends camelized root keys.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(hash, type, record, options) {
var root = Ember.String.camelize(type.typeKey);
hash[root] = this.serialize(record, options);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "Type"] = Ember.String.camelize(belongsTo.constructor.typeKey);
}
});
__exports__["default"] = RESTSerializer;
});
define("ember-data/lib/system/adapter",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var map = Ember.ArrayPolyfills.map;
var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
/**
A `DS.InvalidError` is used by an adapter to signal the external API
was unable to process a request because the content was not
semantically correct or meaningful per the API. Usually this means a
record failed some form of server side validation. When a promise
from an adapter is rejected with a `DS.InvalidError` the record will
transition to the `invalid` state and the errors will be set to the
`errors` property on the record.
Example
```javascript
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"];
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
The `DS.InvalidError` must be constructed with a single object whose
keys are the invalid model properties, and whose values are the
corresponding error messages. For example:
```javascript
return new DS.InvalidError({
length: 'Must be less than 15',
name: 'Must not be blank
});
```
@class InvalidError
@namespace DS
*/
var InvalidError = function(errors) {
var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors));
this.errors = errors;
for (var i=0, l=errorProps.length; i<l; i++) {
this[errorProps[i]] = tmp[errorProps[i]];
}
};
InvalidError.prototype = Ember.create(Error.prototype);
/**
An adapter is an object that receives requests from a store and
translates them into the appropriate action to take against your
persistence layer. The persistence layer is usually an HTTP API, but
may be anything, such as the browser's local storage. Typically the
adapter is not invoked directly instead its functionality is accessed
through the `store`.
### Creating an Adapter
First, create a new subclass of `DS.Adapter`:
```javascript
App.MyAdapter = DS.Adapter.extend({
// ...your code here
});
```
To tell your store which adapter to use, set its `adapter` property:
```javascript
App.store = DS.Store.create({
adapter: 'MyAdapter'
});
```
`DS.Adapter` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `find()`
* `createRecord()`
* `updateRecord()`
* `deleteRecord()`
* `findAll()`
* `findQuery()`
To improve the network performance of your application, you can optimize
your adapter by overriding these lower-level methods:
* `findMany()`
For an example implementation, see `DS.RESTAdapter`, the
included REST adapter.
@class Adapter
@namespace DS
@extends Ember.Object
*/
var Adapter = Ember.Object.extend({
/**
If you would like your adapter to use a custom serializer you can
set the `defaultSerializer` property to be the name of the custom
serializer.
Note the `defaultSerializer` serializer has a lower priority then
a model specific serializer (i.e. `PostSerializer`) or the
`application` serializer.
```javascript
var DjangoAdapter = DS.Adapter.extend({
defaultSerializer: 'django'
});
```
@property defaultSerializer
@type {String}
*/
/**
The `find()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `find()` being called, you
should query your persistence layer for a record with the given ID. Once
found, you can asynchronously call the store's `push()` method to push
the record into the store.
Here is an example `find` implementation:
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
find: function(store, type, id) {
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method find
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@return {Promise} promise
*/
find: Ember.required(Function),
/**
The `findAll()` method is called when you call `find` on the store
without an ID (i.e. `store.find('post')`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findAll: function(store, type, sinceToken) {
var url = type;
var query = { since: sinceToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: null,
/**
This method is called when you call `find` on the store with a
query object as the second parameter (i.e. `store.find('person', {
page: 1 })`).
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findQuery: function(store, type, query) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
generateIdForRecord: function(store, record) {
var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
return uuid;
}
```
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
@return {String|Number} id
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
// ...
}
});
```
@method serialize
@param {DS.Model} record
@param {Object} options
@return {Object} serialized record
*/
serialize: function(record, options) {
return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
createRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
createRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and send it to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
updateRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'PUT',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
updateRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
deleteRecord: function(store, type, record) {
var data = this.serialize(record, { includeId: true });
var id = record.get('id');
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'DELETE',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
@return {Promise} promise
*/
deleteRecord: Ember.required(Function),
/**
Find multiple records at once.
By default, it loops over the provided ids and calls `find` on each.
May be overwritten to improve performance and reduce the number of
server requests.
Example
```javascript
App.ApplicationAdapter = DS.Adapter.extend({
findMany: function(store, type, ids) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, {ids: ids}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the records
@param {Array} ids
@return {Promise} promise
*/
findMany: function(store, type, ids) {
var promises = map.call(ids, function(id) {
return this.find(store, type, id);
}, this);
return Ember.RSVP.all(promises);
}
});
__exports__.InvalidError = InvalidError;
__exports__.Adapter = Adapter;
__exports__["default"] = Adapter;
});
define("ember-data/lib/system/changes",
["./changes/attribute_change","./changes/relationship_change","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var AttributeChange = __dependency1__["default"];
var RelationshipChange = __dependency2__.RelationshipChange;
var RelationshipChangeAdd = __dependency2__.RelationshipChangeAdd;
var RelationshipChangeRemove = __dependency2__.RelationshipChangeRemove;
var OneToManyChange = __dependency2__.OneToManyChange;
var ManyToNoneChange = __dependency2__.ManyToNoneChange;
var OneToOneChange = __dependency2__.OneToOneChange;
var ManyToManyChange = __dependency2__.ManyToManyChange;
__exports__.AttributeChange = AttributeChange;
__exports__.RelationshipChange = RelationshipChange;
__exports__.RelationshipChangeAdd = RelationshipChangeAdd;
__exports__.RelationshipChangeRemove = RelationshipChangeRemove;
__exports__.OneToManyChange = OneToManyChange;
__exports__.ManyToNoneChange = ManyToNoneChange;
__exports__.OneToOneChange = OneToOneChange;
__exports__.ManyToManyChange = ManyToManyChange;
});
define("ember-data/lib/system/changes/attribute_change",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
/**
An AttributeChange object is created whenever a record's
attribute changes value. It is used to track changes to a
record between transaction commits.
@class AttributeChange
@namespace DS
@private
@constructor
*/
function AttributeChange(options) {
this.record = options.record;
this.store = options.store;
this.name = options.name;
this.value = options.value;
this.oldValue = options.oldValue;
}
AttributeChange.createChange = function(options) {
return new AttributeChange(options);
};
AttributeChange.prototype = {
sync: function() {
if (this.value !== this.oldValue) {
this.record.send('becomeDirty');
this.record.updateRecordArraysLater();
}
// TODO: Use this object in the commit process
this.destroy();
},
/**
If the AttributeChange is destroyed (either by being rolled back
or being committed), remove it from the list of pending changes
on the record.
@method destroy
*/
destroy: function() {
delete this.record._changesToSync[this.name];
}
};
__exports__["default"] = AttributeChange;
});
define("ember-data/lib/system/changes/relationship_change",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__.Model;
var get = Ember.get, set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RelationshipChange
@namespace DS
@private
@constructor
*/
var RelationshipChange = function(options) {
this.parentRecord = options.parentRecord;
this.childRecord = options.childRecord;
this.firstRecord = options.firstRecord;
this.firstRecordKind = options.firstRecordKind;
this.firstRecordName = options.firstRecordName;
this.secondRecord = options.secondRecord;
this.secondRecordKind = options.secondRecordKind;
this.secondRecordName = options.secondRecordName;
this.changeType = options.changeType;
this.store = options.store;
this.committed = {};
};
/**
@class RelationshipChangeAdd
@namespace DS
@private
@constructor
*/
var RelationshipChangeAdd = function(options){
RelationshipChange.call(this, options);
};
/**
@class RelationshipChangeRemove
@namespace DS
@private
@constructor
*/
var RelationshipChangeRemove = function(options){
RelationshipChange.call(this, options);
};
RelationshipChange.create = function(options) {
return new RelationshipChange(options);
};
RelationshipChangeAdd.create = function(options) {
return new RelationshipChangeAdd(options);
};
RelationshipChangeRemove.create = function(options) {
return new RelationshipChangeRemove(options);
};
var OneToManyChange = {};
var OneToNoneChange = {};
var ManyToNoneChange = {};
var OneToOneChange = {};
var ManyToManyChange = {};
RelationshipChange._createChange = function(options){
if(options.changeType === "add"){
return RelationshipChangeAdd.create(options);
}
if(options.changeType === "remove"){
return RelationshipChangeRemove.create(options);
}
};
RelationshipChange.determineRelationshipType = function(recordType, knownSide){
var knownKey = knownSide.key, key, otherKind;
var knownKind = knownSide.kind;
var inverse = recordType.inverseFor(knownKey);
if (inverse){
key = inverse.name;
otherKind = inverse.kind;
}
if (!inverse){
return knownKind === "belongsTo" ? "oneToNone" : "manyToNone";
}
else{
if(otherKind === "belongsTo"){
return knownKind === "belongsTo" ? "oneToOne" : "manyToOne";
}
else{
return knownKind === "belongsTo" ? "oneToMany" : "manyToMany";
}
}
};
RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){
// Get the type of the child based on the child's client ID
var firstRecordType = firstRecord.constructor, changeType;
changeType = RelationshipChange.determineRelationshipType(firstRecordType, options);
if (changeType === "oneToMany"){
return OneToManyChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToOne"){
return OneToManyChange.createChange(secondRecord, firstRecord, store, options);
}
else if (changeType === "oneToNone"){
return OneToNoneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToNone"){
return ManyToNoneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "oneToOne"){
return OneToOneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToMany"){
return ManyToManyChange.createChange(firstRecord, secondRecord, store, options);
}
};
OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
store: store,
changeType: options.changeType,
firstRecordName: key,
firstRecordKind: "belongsTo"
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: childRecord,
childRecord: parentRecord,
secondRecord: childRecord,
store: store,
changeType: options.changeType,
secondRecordName: options.key,
secondRecordKind: "hasMany"
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) {
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
var key = options.key;
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "hasMany",
secondRecordKind: "hasMany",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
OneToOneChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
} else if (options.key) {
key = options.key;
} else {
Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false);
}
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "belongsTo",
secondRecordKind: "belongsTo",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
OneToOneChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) {
var oldParent = get(childRecord, key);
if (oldParent){
var correspondingChange = OneToOneChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: "remove",
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange);
correspondingChange.sync();
}
}
};
OneToManyChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
OneToManyChange.maintainInvariant( options, store, childRecord, key );
} else if (options.key) {
key = options.key;
} else {
Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false);
}
var change = RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "belongsTo",
secondRecordKind: "hasMany",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change);
return change;
};
OneToManyChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === "add" && childRecord) {
var oldParent = get(childRecord, key);
if (oldParent){
var correspondingChange = OneToManyChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: "remove",
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange);
correspondingChange.sync();
}
}
};
/**
@class RelationshipChange
@namespace DS
*/
RelationshipChange.prototype = {
getSecondRecordName: function() {
var name = this.secondRecordName, parent;
if (!name) {
parent = this.secondRecord;
if (!parent) { return; }
var childType = this.firstRecord.constructor;
var inverse = childType.inverseFor(this.firstRecordName);
this.secondRecordName = inverse.name;
}
return this.secondRecordName;
},
/**
Get the name of the relationship on the belongsTo side.
@method getFirstRecordName
@return {String}
*/
getFirstRecordName: function() {
var name = this.firstRecordName;
return name;
},
/**
@method destroy
@private
*/
destroy: function() {
var childRecord = this.childRecord,
belongsToName = this.getFirstRecordName(),
hasManyName = this.getSecondRecordName(),
store = this.store;
store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType);
},
getSecondRecord: function(){
return this.secondRecord;
},
/**
@method getFirstRecord
@private
*/
getFirstRecord: function() {
return this.firstRecord;
},
coalesce: function(){
var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord);
forEach(relationshipPairs, function(pair){
var addedChange = pair["add"];
var removedChange = pair["remove"];
if(addedChange && removedChange) {
addedChange.destroy();
removedChange.destroy();
}
});
}
};
RelationshipChangeAdd.prototype = Ember.create(RelationshipChange.create({}));
RelationshipChangeRemove.prototype = Ember.create(RelationshipChange.create({}));
// the object is a value, and not a promise
function isValue(object) {
return typeof object === 'object' && (!object.then || typeof object.then !== 'function');
}
RelationshipChangeAdd.prototype.changeType = "add";
RelationshipChangeAdd.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName(),
firstRecordName = this.getFirstRecordName(),
firstRecord = this.getFirstRecord(),
secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof Model && firstRecord instanceof Model) {
if(this.secondRecordKind === "belongsTo"){
secondRecord.suspendRelationshipObservers(function(){
set(secondRecord, secondRecordName, firstRecord);
});
}
else if(this.secondRecordKind === "hasMany"){
secondRecord.suspendRelationshipObservers(function(){
var relationship = get(secondRecord, secondRecordName);
if (isValue(relationship)) { relationship.addObject(firstRecord); }
});
}
}
if (firstRecord instanceof Model && secondRecord instanceof Model && get(firstRecord, firstRecordName) !== secondRecord) {
if(this.firstRecordKind === "belongsTo"){
firstRecord.suspendRelationshipObservers(function(){
set(firstRecord, firstRecordName, secondRecord);
});
}
else if(this.firstRecordKind === "hasMany"){
firstRecord.suspendRelationshipObservers(function(){
var relationship = get(firstRecord, firstRecordName);
if (isValue(relationship)) { relationship.addObject(secondRecord); }
});
}
}
this.coalesce();
};
RelationshipChangeRemove.prototype.changeType = "remove";
RelationshipChangeRemove.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName(),
firstRecordName = this.getFirstRecordName(),
firstRecord = this.getFirstRecord(),
secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof Model && firstRecord instanceof Model) {
if(this.secondRecordKind === "belongsTo"){
secondRecord.suspendRelationshipObservers(function(){
set(secondRecord, secondRecordName, null);
});
}
else if(this.secondRecordKind === "hasMany"){
secondRecord.suspendRelationshipObservers(function(){
var relationship = get(secondRecord, secondRecordName);
if (isValue(relationship)) { relationship.removeObject(firstRecord); }
});
}
}
if (firstRecord instanceof Model && get(firstRecord, firstRecordName)) {
if(this.firstRecordKind === "belongsTo"){
firstRecord.suspendRelationshipObservers(function(){
set(firstRecord, firstRecordName, null);
});
}
else if(this.firstRecordKind === "hasMany"){
firstRecord.suspendRelationshipObservers(function(){
var relationship = get(firstRecord, firstRecordName);
if (isValue(relationship)) { relationship.removeObject(secondRecord); }
});
}
}
this.coalesce();
};
__exports__.RelationshipChange = RelationshipChange;
__exports__.RelationshipChangeAdd = RelationshipChangeAdd;
__exports__.RelationshipChangeRemove = RelationshipChangeRemove;
__exports__.OneToManyChange = OneToManyChange;
__exports__.ManyToNoneChange = ManyToNoneChange;
__exports__.OneToOneChange = OneToOneChange;
__exports__.ManyToManyChange = ManyToManyChange;
});
define("ember-data/lib/system/container_proxy",
["exports"],
function(__exports__) {
"use strict";
/**
This is used internally to enable deprecation of container paths and provide
a decent message to the user indicating how to fix the issue.
@class ContainerProxy
@namespace DS
@private
*/
var ContainerProxy = function (container){
this.container = container;
};
ContainerProxy.prototype.aliasedFactory = function(path, preLookup) {
var _this = this;
return {create: function(){
if (preLookup) { preLookup(); }
return _this.container.lookup(path);
}};
};
ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) {
var factory = this.aliasedFactory(dest, preLookup);
return this.container.register(source, factory);
};
ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) {
var preLookupCallback = function(){
Ember.deprecate("You tried to look up '" + deprecated + "', " +
"but this has been deprecated in favor of '" + valid + "'.", false);
};
return this.registerAlias(deprecated, valid, preLookupCallback);
};
ContainerProxy.prototype.registerDeprecations = function(proxyPairs) {
for (var i = proxyPairs.length; i > 0; i--) {
var proxyPair = proxyPairs[i - 1],
deprecated = proxyPair['deprecated'],
valid = proxyPair['valid'];
this.registerDeprecation(deprecated, valid);
}
};
__exports__["default"] = ContainerProxy;
});
define("ember-data/lib/system/debug",
["./debug/debug_info","./debug/debug_adapter","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/**
@module ember-data
*/
var DebugAdapter = __dependency2__["default"];
__exports__["default"] = DebugAdapter;
});
define("ember-data/lib/system/debug/debug_adapter",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__.Model;
var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore;
/**
Extend `Ember.DataAdapter` with ED specific code.
@class DebugAdapter
@namespace DS
@extends Ember.DataAdapter
@private
*/
var DebugAdapter = Ember.DataAdapter.extend({
getFilters: function() {
return [
{ name: 'isNew', desc: 'New' },
{ name: 'isModified', desc: 'Modified' },
{ name: 'isClean', desc: 'Clean' }
];
},
detect: function(klass) {
return klass !== Model && Model.detect(klass);
},
columnsForType: function(type) {
var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this;
get(type, 'attributes').forEach(function(name, meta) {
if (count++ > self.attributeLimit) { return false; }
var desc = capitalize(underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function(type) {
return this.get('store').all(type);
},
getRecordColumnValues: function(record) {
var self = this, count = 0,
columnValues = { id: get(record, 'id') };
record.eachAttribute(function(key) {
if (count++ > self.attributeLimit) {
return false;
}
var value = get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords: function(record) {
var keywords = [], keys = Ember.A(['id']);
record.eachAttribute(function(key) {
keys.push(key);
});
keys.forEach(function(key) {
keywords.push(get(record, key));
});
return keywords;
},
getRecordFilterValues: function(record) {
return {
isNew: record.get('isNew'),
isModified: record.get('isDirty') && !record.get('isNew'),
isClean: !record.get('isDirty')
};
},
getRecordColor: function(record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('isDirty')) {
color = 'blue';
}
return color;
},
observeRecord: function(record, recordUpdated) {
var releaseMethods = Ember.A(), self = this,
keysToObserve = Ember.A(['id', 'isNew', 'isDirty']);
record.eachAttribute(function(key) {
keysToObserve.push(key);
});
keysToObserve.forEach(function(key) {
var handler = function() {
recordUpdated(self.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function() {
Ember.removeObserver(record, key, handler);
});
});
var release = function() {
releaseMethods.forEach(function(fn) { fn(); } );
};
return release;
}
});
__exports__["default"] = DebugAdapter;
});
define("ember-data/lib/system/debug/debug_info",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Model = __dependency1__.Model;
Model.reopen({
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo: function() {
var attributes = ['id'],
relationships = { belongsTo: [], hasMany: [] },
expensiveProperties = [];
this.eachAttribute(function(name, meta) {
attributes.push(name);
}, this);
this.eachRelationship(function(name, relationship) {
relationships[relationship.kind].push(name);
expensiveProperties.push(name);
});
var groups = [
{
name: 'Attributes',
properties: attributes,
expand: true
},
{
name: 'Belongs To',
properties: relationships.belongsTo,
expand: true
},
{
name: 'Has Many',
properties: relationships.hasMany,
expand: true
},
{
name: 'Flags',
properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
}
];
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
}
});
__exports__["default"] = Model;
});
define("ember-data/lib/system/model",
["./model/model","./model/attributes","./model/states","./model/errors","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/**
@module ember-data
*/
var Model = __dependency1__["default"];
var attr = __dependency2__["default"];
var RootState = __dependency3__["default"];
var Errors = __dependency4__["default"];
__exports__.Model = Model;
__exports__.RootState = RootState;
__exports__.attr = attr;
__exports__.Errors = Errors;
});
define("ember-data/lib/system/model/attributes",
["./model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Model = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get;
/**
@class Model
@namespace DS
*/
Model.reopenClass({
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
var attributes = Ember.get(App.Person, 'attributes')
attributes.forEach(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isAttribute) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');
meta.name = name;
map.set(name, meta);
}
});
return map;
}),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
var transformedAttributes = Ember.get(App.Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachAttribute(function(key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachAttribute: function(callback, binding) {
get(this, 'attributes').forEach(function(name, meta) {
callback.call(binding, name, meta);
}, binding);
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachTransformedAttribute: function(callback, binding) {
get(this, 'transformedAttributes').forEach(function(name, type) {
callback.call(binding, name, type);
});
}
});
Model.reopen({
eachAttribute: function(callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
function getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue.apply(null, arguments);
} else {
return options.defaultValue;
}
}
function hasValue(record, key) {
return record._attributes.hasOwnProperty(key) ||
record._inFlightAttributes.hasOwnProperty(key) ||
record._data.hasOwnProperty(key);
}
function getValue(record, key) {
if (record._attributes.hasOwnProperty(key)) {
return record._attributes[key];
} else if (record._inFlightAttributes.hasOwnProperty(key)) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](/api/data/classes/DS.Transform.html).
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
username: attr('string'),
email: attr('string'),
verified: attr('boolean', {defaultValue: false})
});
```
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
function attr(type, options) {
options = options || {};
var meta = {
type: type,
isAttribute: true,
options: options
};
return Ember.computed('data', function(key, value) {
if (arguments.length > 1) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id');
var oldValue = getValue(this, key);
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
this._attributes[key] = value;
this.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: this._data[key],
value: value
});
}
return value;
} else if (hasValue(this, key)) {
return getValue(this, key);
} else {
return getDefaultValue(this, options, key);
}
// `data` is never set directly. However, it may be
// invalidated from the state manager's setData
// event.
}).meta(meta);
}
__exports__["default"] = attr;
});
define("ember-data/lib/system/model/errors",
["exports"],
function(__exports__) {
"use strict";
var get = Ember.get, isEmpty = Ember.isEmpty;
/**
@module ember-data
*/
/**
Holds validation errors for a given record organized by attribute names.
@class Errors
@namespace DS
@extends Ember.Object
@uses Ember.Enumerable
@uses Ember.Evented
*/
var Errors = Ember.Object.extend(Ember.Enumerable, Ember.Evented, {
/**
Register with target handler
@method registerHandlers
@param {Object} target
@param {Function} becameInvalid
@param {Function} becameValid
*/
registerHandlers: function(target, becameInvalid, becameValid) {
this.on('becameInvalid', target, becameInvalid);
this.on('becameValid', target, becameValid);
},
/**
@property errorsByAttributeName
@type {Ember.MapWithDefault}
@private
*/
errorsByAttributeName: Ember.reduceComputed("content", {
initialValue: function() {
return Ember.MapWithDefault.create({
defaultValue: function() {
return Ember.A();
}
});
},
addedItem: function(errors, error) {
errors.get(error.attribute).pushObject(error);
return errors;
},
removedItem: function(errors, error) {
errors.get(error.attribute).removeObject(error);
return errors;
}
}),
/**
Returns errors for a given attribute
@method errorsFor
@param {String} attribute
@returns {Array}
*/
errorsFor: function(attribute) {
return get(this, 'errorsByAttributeName').get(attribute);
},
/**
*/
messages: Ember.computed.mapBy('content', 'message'),
/**
@property content
@type {Array}
@private
*/
content: Ember.computed(function() {
return Ember.A();
}),
/**
@method unknownProperty
@private
*/
unknownProperty: function(attribute) {
var errors = this.errorsFor(attribute);
if (isEmpty(errors)) { return null; }
return errors;
},
/**
@method nextObject
@private
*/
nextObject: function(index, previousObject, context) {
return get(this, 'content').objectAt(index);
},
/**
Total number of errors.
@property length
@type {Number}
@readOnly
*/
length: Ember.computed.oneWay('content.length').readOnly(),
/**
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: Ember.computed.not('length').readOnly(),
/**
Adds error messages to a given attribute and sends
`becameInvalid` event to the record.
@method add
@param {String} attribute
@param {Array|String} messages
*/
add: function(attribute, messages) {
var wasEmpty = get(this, 'isEmpty');
messages = this._findOrCreateMessages(attribute, messages);
get(this, 'content').addObjects(messages);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (wasEmpty && !get(this, 'isEmpty')) {
this.trigger('becameInvalid');
}
},
/**
@method _findOrCreateMessages
@private
*/
_findOrCreateMessages: function(attribute, messages) {
var errors = this.errorsFor(attribute);
return Ember.makeArray(messages).map(function(message) {
return errors.findBy('message', message) || {
attribute: attribute,
message: message
};
});
},
/**
Removes all error messages from the given attribute and sends
`becameValid` event to the record if there no more errors left.
@method remove
@param {String} attribute
*/
remove: function(attribute) {
if (get(this, 'isEmpty')) { return; }
var content = get(this, 'content').rejectBy('attribute', attribute);
get(this, 'content').setObjects(content);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (get(this, 'isEmpty')) {
this.trigger('becameValid');
}
},
/**
Removes all error messages and sends `becameValid` event
to the record.
@method clear
*/
clear: function() {
if (get(this, 'isEmpty')) { return; }
get(this, 'content').clear();
this.enumerableContentDidChange();
this.trigger('becameValid');
},
/**
Checks if there is error messages for the given attribute.
@method has
@param {String} attribute
@returns {Boolean} true if there some errors on given attribute
*/
has: function(attribute) {
return !isEmpty(this.errorsFor(attribute));
}
});
__exports__["default"] = Errors;
});
define("ember-data/lib/system/model/model",
["./states","./errors","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var RootState = __dependency1__["default"];
var Errors = __dependency2__["default"];
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set,
merge = Ember.merge,
Promise = Ember.RSVP.Promise;
var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) {
return get(get(this, 'currentState'), key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var Model = Ember.Object.extend(Ember.Evented, {
_recordArrays: undefined,
_relationships: undefined,
_loadingRecordArrays: undefined,
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.set('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
*/
isDirty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isDeleted'); // false
record.deleteRecord();
record.get('isDeleted'); // true
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state. A
record will be in the `valid` state when no client-side
validations have failed and the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend. This may also result in the record having
its `isValid` property become false if the adapter reported that
server-side validations failed.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
The `clientId` property is a transient numerical identifier
generated at runtime by the data store. It is important
primarily because newly created objects may not yet have an
externally generated id.
@property clientId
@private
@type {Number|String}
*/
clientId: null,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord(App.Model);
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: RootState.empty,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
typically contains keys corresponding to the invalid property names
and values which are an array of error messages.
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('errors').get('foo'); // ['foo should be a number.']
});
```
@property errors
@type {Object}
*/
errors: Ember.computed(function() {
var errors = Errors.create();
errors.registerHandlers(this, function() {
this.send('becameInvalid');
}, function() {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@returns {Object} an object whose values are primitive JSON values only
*/
serialize: function(options) {
var store = get(this, 'store');
return store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@returns {Object} A JSON representation of the object.
*/
toJSON: function(options) {
// container is for lazy transform lookups
var serializer = DS.JSONSerializer.create({ container: this.container });
return serializer.serialize(this, options);
},
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when the record is created.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed(function() {
this._data = this._data || {};
return this._data;
}).readOnly(),
_data: null,
init: function() {
this._super();
this._setup();
},
_setup: function() {
this._changesToSync = {};
this._deferredTriggers = [];
this._data = {};
this._attributes = {};
this._inFlightAttributes = {};
this._relationships = {};
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function(name, context) {
var currentState = get(this, 'currentState');
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct references to state objects
var pivotName = name.split(".", 1),
currentState = get(this, 'currentState'),
state = currentState;
do {
if (state.exit) { state.exit(this); }
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = name.split(".");
var setups = [], enters = [], i, l;
for (i=0, l=path.length; i<l; i++) {
state = state[path[i]];
if (state.enter) { enters.push(state); }
if (state.setup) { setups.push(state); }
}
for (i=0, l=enters.length; i<l; i++) {
enters[i].enter(this);
}
set(this, 'currentState', state);
for (i=0, l=setups.length; i<l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function(state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
withTransaction: function(fn) {
var transaction = get(this, 'transaction');
if (transaction) { fn(transaction); }
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function(promise) {
this.send('loadingData', promise);
},
/**
@method loadedData
@private
*/
loadedData: function() {
this.send('loadedData');
},
/**
@method notFound
@private
*/
notFound: function() {
this.send('notFound');
},
/**
@method pushedData
@private
*/
pushedData: function() {
this.send('pushedData');
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollback()` a
delete after it was made.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
softDelete: function() {
this.get('model').deleteRecord();
},
confirm: function() {
this.get('model').save();
},
undo: function() {
this.get('model').rollback();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function() {
this.send('deleteRecord');
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
this.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function() {
this.deleteRecord();
return this.save();
},
/**
@method unloadRecord
@private
*/
unloadRecord: function() {
if (this.isDestroyed) { return; }
this.send('unloadRecord');
},
/**
@method clearRelationships
@private
*/
clearRelationships: function() {
this.eachRelationship(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
set(this, name, null);
} else if (relationship.kind === 'hasMany') {
var hasMany = this._relationships[name];
if (hasMany) { // relationships are created lazily
hasMany.destroy();
}
}
}, this);
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function() {
this._updatingRecordArraysLater = false;
get(this, 'store').dataWasUpdated(this.constructor, this);
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```javascript
App.Mascot = DS.Model.extend({
name: attr('string')
});
var person = store.createRecord('person');
person.changedAttributes(); // {}
person.set('name', 'Tomster');
person.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function() {
var oldData = get(this, '_data'),
newData = get(this, '_attributes'),
diffData = {},
prop;
for (prop in newData) {
diffData[prop] = [oldData[prop], newData[prop]];
}
return diffData;
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function() {
this.send('willCommit');
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function(data) {
set(this, 'isError', false);
if (data) {
this._data = data;
} else {
Ember.mixin(this._data, this._inFlightAttributes);
}
this._inFlightAttributes = {};
this.send('didCommit');
this.updateRecordArraysLater();
if (!data) { return; }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
dataDidChange: Ember.observer(function() {
this.reloadHasManys();
}, 'data'),
reloadHasManys: function() {
var relationships = get(this.constructor, 'relationshipsByName');
this.updateRecordArraysLater();
relationships.forEach(function(name, relationship) {
if (this._data.links && this._data.links[name]) { return; }
if (relationship.kind === 'hasMany') {
this.hasManyDidChange(relationship.key);
}
}, this);
},
hasManyDidChange: function(key) {
var hasMany = this._relationships[key];
if (hasMany) {
var records = this._data[key] || [];
set(hasMany, 'content', Ember.A(records));
set(hasMany, 'isLoaded', true);
hasMany.trigger('didLoad');
}
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function() {
// quick hack (something like this could be pushed into run.once
if (this._updatingRecordArraysLater) { return; }
this._updatingRecordArraysLater = true;
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
/**
@method setupData
@private
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
setupData: function(data, partial) {
if (partial) {
Ember.merge(this._data, data);
} else {
this._data = data;
}
var relationships = this._relationships;
this.eachRelationship(function(name, rel) {
if (data.links && data.links[name]) { return; }
if (rel.options.async) { relationships[name] = null; }
});
if (data) { this.pushedData(); }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
materializeId: function(id) {
set(this, 'id', id);
},
materializeAttributes: function(attributes) {
Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes);
merge(this._data, attributes);
},
materializeAttribute: function(name, value) {
this._data[name] = value;
},
/**
@method updateHasMany
@private
@param {String} name
@param {Array} records
*/
updateHasMany: function(name, records) {
this._data[name] = records;
this.hasManyDidChange(name);
},
/**
@method updateBelongsTo
@private
@param {String} name
@param {DS.Model} record
*/
updateBelongsTo: function(name, record) {
this._data[name] = record;
},
/**
If the model `isDirty` this function will discard any unsaved
changes
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
*/
rollback: function() {
this._attributes = {};
if (get(this, 'isError')) {
this._inFlightAttributes = {};
set(this, 'isError', false);
}
if (!get(this, 'isValid')) {
this._inFlightAttributes = {};
}
this.send('rolledBack');
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
toStringExtension: function() {
return get(this, 'id');
},
/**
The goal of this method is to temporarily disable specific observers
that take action in response to application changes.
This allows the system to make changes (such as materialization and
rollback) that should not trigger secondary behavior (such as setting an
inverse relationship or marking records as dirty).
The specific implementation will likely change as Ember proper provides
better infrastructure for suspending groups of observers, and if Array
observation becomes more unified with regular observers.
@method suspendRelationshipObservers
@private
@param callback
@param binding
*/
suspendRelationshipObservers: function(callback, binding) {
var observers = get(this.constructor, 'relationshipNames').belongsTo;
var self = this;
try {
this._suspendedRelationships = true;
Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() {
Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() {
callback.call(binding || self);
});
});
} finally {
this._suspendedRelationships = false;
}
},
/**
Save the record and persist any changes to the record to an
extenal source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function(){
// Success callback
}, function() {
// Error callback
});
```
@method save
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function() {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.get('store').scheduleSave(this, resolver);
this._inFlightAttributes = this._attributes;
this._attributes = {};
return DS.PromiseObject.create({ promise: resolver.promise });
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```javascript
App.ModelViewRoute = Ember.Route.extend({
actions: {
reload: function() {
this.get('model').reload();
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function() {
set(this, 'isReloading', true);
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
var promise = new Promise(function(resolve){
record.send('reloadRecord', resolve);
}, promiseLabel).then(function() {
record.set('isReloading', false);
record.set('isError', false);
return record;
}, function(reason) {
record.set('isError', true);
throw reason;
}, "DS: Model#reload complete, update flags");
return DS.PromiseObject.create({ promise: promise });
},
// FOR USE DURING COMMIT PROCESS
adapterDidUpdateAttribute: function(attributeName, value) {
// If a value is passed in, update the internal attributes and clear
// the attribute cache so it picks up the new value. Otherwise,
// collapse the current value into the internal attributes because
// the adapter has acknowledged it.
if (value !== undefined) {
this._data[attributeName] = value;
this.notifyPropertyChange(attributeName);
} else {
this._data[attributeName] = this._inFlightAttributes[attributeName];
}
this.updateRecordArraysLater();
},
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function(errors) {
var recordErrors = get(this, 'errors');
function addError(name) {
if (errors[name]) {
recordErrors.add(name, errors[name]);
}
}
this.eachAttribute(addError);
this.eachRelationship(addError);
},
/**
@method adapterDidError
@private
*/
adapterDidError: function() {
this.send('becameError');
set(this, 'isError', true);
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param name
*/
trigger: function(name) {
Ember.tryInvoke(this, name, [].slice.call(arguments, 1));
this._super.apply(this, arguments);
},
triggerLater: function() {
if (this._deferredTriggers.push(arguments) !== 1) { return; }
Ember.run.schedule('actions', this, '_triggerDeferredTriggers');
},
_triggerDeferredTriggers: function() {
for (var i=0, l=this._deferredTriggers.length; i<l; i++) {
this.trigger.apply(this, this._deferredTriggers[i]);
}
this._deferredTriggers.length = 0;
},
willDestroy: function() {
this._super();
this.clearRelationships();
}
});
Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function() {
throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.");
}
});
__exports__["default"] = Model;
});
define("ember-data/lib/system/model/states",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (These state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What we mean is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [isDirty](DS.Model.html#property_isDirty)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
function hasDefinedProperties(object) {
// Ignore internal property defined by simulated `Ember.create`.
var names = Ember.keys(object);
var i, l, name;
for (i = 0, l = names.length; i < l; i++ ) {
name = names[i];
if (object.hasOwnProperty(name) && object[name]) { return true; }
}
return false;
}
function didSetProperty(record, context) {
if (context.value === context.originalValue) {
delete record._attributes[context.name];
record.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
record.send('becomeDirty');
}
record.updateRecordArraysLater();
}
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
// local changes to the backend. This may also result in the
// record having its `isValid` property become false if the
// adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: No client-side validations have failed and the
// adapter did not report any server-side validation failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// send to the adapter yet.
var DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: didSetProperty,
propertyWasReset: function(record, name) {
var stillDirty = false;
for (var prop in record._attributes) {
stillDirty = true;
break;
}
if (!stillDirty) { record.send('rolledBack'); }
},
pushedData: Ember.K,
becomeDirty: Ember.K,
willCommit: function(record) {
record.transitionTo('inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
rolledBack: function(record) {
record.transitionTo('loaded.saved');
},
becameInvalid: function(record) {
record.transitionTo('invalid');
},
rollback: function(record) {
record.rollback();
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: didSetProperty,
becomeDirty: Ember.K,
pushedData: Ember.K,
unloadRecord: function(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + " `", false);
},
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
var dirtyType = get(this, 'dirtyType');
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks', dirtyType);
},
becameInvalid: function(record) {
record.transitionTo('invalid');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// A record is in the `invalid` state when its client-side
// invalidations have failed, or if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
// EVENTS
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
didSetProperty: function(record, context) {
get(record, 'errors').remove(context.name);
didSetProperty(record, context);
},
becomeDirty: Ember.K,
rolledBack: function(record) {
get(record, 'errors').clear();
},
becameValid: function(record) {
record.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('becameInvalid', record);
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function deepClone(object) {
var clone = {}, value;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function dirtyState(options) {
var newState = deepClone(DirtyState);
return mixin(newState, options);
}
var createdState = dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
createdState.uncommitted.rolledBack = function(record) {
record.transitionTo('deleted.saved');
};
var updatedState = dirtyState({
dirtyType: 'updated'
});
createdState.uncommitted.deleteRecord = function(record) {
record.clearRelationships();
record.transitionTo('deleted.saved');
};
createdState.uncommitted.rollback = function(record) {
DirtyState.uncommitted.rollback.apply(this, arguments);
record.transitionTo('deleted.saved');
};
createdState.uncommitted.propertyWasReset = Ember.K;
function assertAgainstUnloadRecord(record) {
Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + "`", false);
}
updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord;
updatedState.uncommitted.deleteRecord = function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
};
var RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
// DEFAULT EVENTS
// Trying to roll back if you're not in the dirty state
// doesn't change your state. For example, if you're in the
// in-flight state, rolling back the record doesn't move
// you out of the in-flight state.
rolledBack: Ember.K,
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
propertyWasReset: Ember.K,
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
// EVENTS
loadingData: function(record, promise) {
record._loadingPromise = promise;
record.transitionTo('loading');
},
loadedData: function(record) {
record.transitionTo('loaded.created.uncommitted');
record.suspendRelationshipObservers(function() {
record.notifyPropertyChange('data');
});
},
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
}
},
// A record enters this state when the store asks
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function(record) {
record._loadingPromise = null;
},
// EVENTS
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
set(record, 'isError', false);
},
becameError: function(record) {
record.triggerLater('becameError', record);
},
notFound: function(record) {
record.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function(record) {
var attrs = record._attributes,
isDirty = false;
for (var prop in attrs) {
if (attrs.hasOwnProperty(prop)) {
isDirty = true;
break;
}
}
if (isDirty) {
record.adapterDidDirty();
}
},
// EVENTS
didSetProperty: didSetProperty,
pushedData: Ember.K,
becomeDirty: function(record) {
record.transitionTo('updated.uncommitted');
},
willCommit: function(record) {
record.transitionTo('updated.inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
didCommit: function(record) {
record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType'));
},
// loaded.saved.notFound would be triggered by a failed
// `reload()` on an unchanged record
notFound: Ember.K
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
// TRANSITIONS
setup: function(record) {
record.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
// EVENTS
willCommit: function(record) {
record.transitionTo('inFlight');
},
rollback: function(record) {
record.rollback();
},
becomeDirty: Ember.K,
deleteRecord: Ember.K,
rolledBack: function(record) {
record.transitionTo('loaded.saved');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
unloadRecord: assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function(record) {
var store = get(record, 'store');
store.dematerializeRecord(record);
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('didDelete', record);
record.triggerLater('didCommit', record);
}
}
},
invokeLifecycleCallbacks: function(record, dirtyType) {
if (dirtyType === 'created') {
record.triggerLater('didCreate', record);
} else {
record.triggerLater('didUpdate', record);
}
record.triggerLater('didCommit', record);
}
};
function wireState(object, parent, name) {
/*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = mixin(parent ? Ember.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; }
if (typeof object[prop] === 'object') {
object[prop] = wireState(object[prop], object, name + "." + prop);
}
}
return object;
}
RootState = wireState(RootState, null, "root");
__exports__["default"] = RootState;
});
define("ember-data/lib/system/record_array_manager",
["./record_arrays","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var ManyArray = __dependency1__.ManyArray;
var get = Ember.get, set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RecordArrayManager
@namespace DS
@private
@extends Ember.Object
*/
var RecordArrayManager = Ember.Object.extend({
init: function() {
this.filteredRecordArrays = Ember.MapWithDefault.create({
defaultValue: function() { return []; }
});
this.changedRecords = [];
this._adapterPopulatedRecordArrays = [];
},
recordDidChange: function(record) {
if (this.changedRecords.push(record) !== 1) { return; }
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
recordArraysForRecord: function(record) {
record._recordArrays = record._recordArrays || Ember.OrderedSet.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArrays: function() {
forEach(this.changedRecords, function(record) {
if (get(record, 'isDeleted')) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords.length = 0;
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) { return; }
forEach(recordArrays, function(array) {
array.removeRecord(record);
});
},
_recordWasChanged: function (record) {
var type = record.constructor,
recordArrays = this.filteredRecordArrays.get(type),
filter;
forEach(recordArrays, function(array) {
filter = get(array, 'filterFunction');
this.updateRecordArray(array, filter, type, record);
}, this);
// loop through all manyArrays containing an unloaded copy of this
// clientId and notify them that the record was loaded.
var manyArrays = record._loadingRecordArrays;
if (manyArrays) {
for (var i=0, l=manyArrays.length; i<l; i++) {
manyArrays[i].loadedRecord();
}
record._loadingRecordArrays = [];
}
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArray: function(array, filter, type, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record);
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
recordArrays.add(array);
array.addRecord(record);
} else if (!shouldBeInArray) {
recordArrays.remove(array);
array.removeRecord(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param array
@param type
@param filter
*/
updateFilter: function(array, type, filter) {
var typeMap = this.store.typeMapFor(type),
records = typeMap.records, record;
for (var i=0, l=records.length; i<l; i++) {
record = records[i];
if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) {
this.updateRecordArray(array, filter, type, record);
}
}
},
/**
Create a `DS.ManyArray` for a type and list of record references, and index
the `ManyArray` under each reference. This allows us to efficiently remove
records from `ManyArray`s when they are deleted.
@method createManyArray
@param {Class} type
@param {Array} references
@return {DS.ManyArray}
*/
createManyArray: function(type, records) {
var manyArray = ManyArray.create({
type: type,
content: records,
store: this.store
});
forEach(records, function(record) {
var arrays = this.recordArraysForRecord(record);
arrays.add(manyArray);
}, this);
return manyArray;
},
/**
Create a `DS.RecordArray` for a type and register it for updates.
@method createRecordArray
@param {Class} type
@return {DS.RecordArray}
*/
createRecordArray: function(type) {
var array = DS.RecordArray.create({
type: type,
content: Ember.A(),
store: this.store,
isLoaded: true
});
this.registerFilteredRecordArray(array, type);
return array;
},
/**
Create a `DS.FilteredRecordArray` for a type and register it for updates.
@method createFilteredRecordArray
@param {Class} type
@param {Function} filter
@return {DS.FilteredRecordArray}
*/
createFilteredRecordArray: function(type, filter) {
var array = DS.FilteredRecordArray.create({
type: type,
content: Ember.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, type, filter);
return array;
},
/**
Create a `DS.AdapterPopulatedRecordArray` for a type with given query.
@method createAdapterPopulatedRecordArray
@param {Class} type
@param {Object} query
@return {DS.AdapterPopulatedRecordArray}
*/
createAdapterPopulatedRecordArray: function(type, query) {
var array = DS.AdapterPopulatedRecordArray.create({
type: type,
query: query,
content: Ember.A(),
store: this.store
});
this._adapterPopulatedRecordArrays.push(array);
return array;
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {Class} type
@param {Function} filter
*/
registerFilteredRecordArray: function(array, type, filter) {
var recordArrays = this.filteredRecordArrays.get(type);
recordArrays.push(array);
this.updateFilter(array, type, filter);
},
// Internally, we maintain a map of all unloaded IDs requested by
// a ManyArray. As the adapter loads data into the store, the
// store notifies any interested ManyArrays. When the ManyArray's
// total number of loading records drops to zero, it becomes
// `isLoaded` and fires a `didLoad` event.
registerWaitingRecordArray: function(record, array) {
var loadingRecordArrays = record._loadingRecordArrays || [];
loadingRecordArrays.push(array);
record._loadingRecordArrays = loadingRecordArrays;
},
willDestroy: function(){
this._super();
flatten(values(this.filteredRecordArrays.values)).forEach(destroy);
this._adapterPopulatedRecordArrays.forEach(destroy);
}
});
function values(obj) {
var result = [];
var keys = Ember.keys(obj);
for (var i = 0; i < keys.length; i++) {
result.push(obj[keys[i]]);
}
return result;
}
function destroy(entry) {
entry.destroy();
}
function flatten(list) {
var length = list.length;
var result = Ember.A();
for (var i = 0; i < length; i++) {
result = result.concat(list[i]);
}
return result;
}
__exports__["default"] = RecordArrayManager;
});
define("ember-data/lib/system/record_arrays",
["./record_arrays/record_array","./record_arrays/filtered_record_array","./record_arrays/adapter_populated_record_array","./record_arrays/many_array","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/**
@module ember-data
*/
var RecordArray = __dependency1__["default"];
var FilteredRecordArray = __dependency2__["default"];
var AdapterPopulatedRecordArray = __dependency3__["default"];
var ManyArray = __dependency4__["default"];
__exports__.RecordArray = RecordArray;
__exports__.FilteredRecordArray = FilteredRecordArray;
__exports__.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray;
__exports__.ManyArray = ManyArray;
});
define("ember-data/lib/system/record_arrays/adapter_populated_record_array",
["./record_array","exports"],
function(__dependency1__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
/**
Represents an ordered list of records whose order and membership is
determined by the adapter. For example, a query sent to the adapter
may trigger a search on the server, whose results would be loaded
into an instance of the `AdapterPopulatedRecordArray`.
@class AdapterPopulatedRecordArray
@namespace DS
@extends DS.RecordArray
*/
var AdapterPopulatedRecordArray = RecordArray.extend({
query: null,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a server query (on " + type + ") is immutable.");
},
/**
@method load
@private
@param {Array} data
*/
load: function(data) {
var store = get(this, 'store'),
type = get(this, 'type'),
records = store.pushMany(type, data),
meta = store.metadataFor(type);
this.setProperties({
content: Ember.A(records),
isLoaded: true,
meta: meta
});
// TODO: should triggering didLoad event be the last action of the runLoop?
Ember.run.once(this, 'trigger', 'didLoad');
}
});
__exports__["default"] = AdapterPopulatedRecordArray;
});
define("ember-data/lib/system/record_arrays/filtered_record_array",
["./record_array","exports"],
function(__dependency1__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
/**
@module ember-data
*/
var get = Ember.get;
/**
Represents a list of records whose membership is determined by the
store. As records are created, loaded, or modified, the store
evaluates them to determine if they should be part of the record
array.
@class FilteredRecordArray
@namespace DS
@extends DS.RecordArray
*/
var FilteredRecordArray = RecordArray.extend({
/**
The filterFunction is a function used to test records from the store to
determine if they should be part of the record array.
Example
```javascript
var allPeople = store.all('person');
allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
var people = store.filter('person', function(person) {
if (person.get('name').match(/Katz$/)) { return true; }
});
people.mapBy('name'); // ["Yehuda Katz"]
var notKatzFilter = function(person) {
return !person.get('name').match(/Katz$/);
};
people.set('filterFunction', notKatzFilter);
people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
```
@method filterFunction
@param {DS.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
isLoaded: true,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
updateFilter: Ember.observer(function() {
var manager = get(this, 'manager');
manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction'));
}, 'filterFunction')
});
__exports__["default"] = FilteredRecordArray;
});
define("ember-data/lib/system/record_arrays/many_array",
["./record_array","../changes","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var RecordArray = __dependency1__["default"];
var RelationshipChange = __dependency2__.RelationshipChange;
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var map = Ember.EnumerableUtils.map;
function sync(change) {
change.sync();
}
/**
A `ManyArray` is a `RecordArray` that represents the contents of a has-many
relationship.
The `ManyArray` is instantiated lazily the first time the relationship is
requested.
### Inverses
Often, the relationships in Ember Data applications will have
an inverse. For example, imagine the following models are
defined:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
If you created a new instance of `App.Post` and added
a `App.Comment` record to its `comments` has-many
relationship, you would expect the comment's `post`
property to be set to the post that contained
the has-many.
We call the record to which a relationship belongs the
relationship's _owner_.
@class ManyArray
@namespace DS
@extends DS.RecordArray
*/
var ManyArray = RecordArray.extend({
init: function() {
this._super.apply(this, arguments);
this._changesToSync = Ember.OrderedSet.create();
},
/**
The property name of the relationship
@property {String} name
@private
*/
name: null,
/**
The record to which this relationship belongs.
@property {DS.Model} owner
@private
*/
owner: null,
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
isPolymorphic: false,
// LOADING STATE
isLoaded: false,
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise} promise
@private
*/
promise: null,
/**
@method loadingRecordsCount
@param {Number} count
@private
*/
loadingRecordsCount: function(count) {
this.loadingRecordsCount = count;
},
/**
@method loadedRecord
@private
*/
loadedRecord: function() {
this.loadingRecordsCount--;
if (this.loadingRecordsCount === 0) {
set(this, 'isLoaded', true);
this.trigger('didLoad');
}
},
/**
@method fetch
@private
*/
fetch: function() {
var records = get(this, 'content'),
store = get(this, 'store'),
owner = get(this, 'owner'),
resolver = Ember.RSVP.defer("DS: ManyArray#fetch " + get(this, 'type'));
var unloadedRecords = records.filterProperty('isEmpty', true);
store.fetchMany(unloadedRecords, owner, resolver);
},
// Overrides Ember.Array's replace method to implement
replaceContent: function(index, removed, added) {
// Map the array of record objects into an array of client ids.
added = map(added, function(record) {
Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type);
return record;
}, this);
this._super(index, removed, added);
},
arrangedContentDidChange: function() {
Ember.run.once(this, 'fetch');
},
arrayContentWillChange: function(index, removed, added) {
var owner = get(this, 'owner'),
name = get(this, 'name');
if (!owner._suspendedRelationships) {
// This code is the first half of code that continues inside
// of arrayContentDidChange. It gets or creates a change from
// the child object, adds the current owner as the old
// parent if this is the first time the object was removed
// from a ManyArray, and sets `newParent` to null.
//
// Later, if the object is added to another ManyArray,
// the `arrayContentDidChange` will set `newParent` on
// the change.
for (var i=index; i<index+removed; i++) {
var record = get(this, 'content').objectAt(i);
var change = RelationshipChange.createChange(owner, record, get(this, 'store'), {
parentType: owner.constructor,
changeType: "remove",
kind: "hasMany",
key: name
});
this._changesToSync.add(change);
}
}
return this._super.apply(this, arguments);
},
arrayContentDidChange: function(index, removed, added) {
this._super.apply(this, arguments);
var owner = get(this, 'owner'),
name = get(this, 'name'),
store = get(this, 'store');
if (!owner._suspendedRelationships) {
// This code is the second half of code that started in
// `arrayContentWillChange`. It gets or creates a change
// from the child object, and adds the current owner as
// the new parent.
for (var i=index; i<index+added; i++) {
var record = get(this, 'content').objectAt(i);
var change = RelationshipChange.createChange(owner, record, store, {
parentType: owner.constructor,
changeType: "add",
kind:"hasMany",
key: name
});
change.hasManyName = name;
this._changesToSync.add(change);
}
// We wait until the array has finished being
// mutated before syncing the OneToManyChanges created
// in arrayContentWillChange, so that the array
// membership test in the sync() logic operates
// on the final results.
this._changesToSync.forEach(sync);
this._changesToSync.clear();
}
},
/**
Create a child record within the owner
@method createRecord
@private
@param {Object} hash
@return {DS.Model} record
*/
createRecord: function(hash) {
var owner = get(this, 'owner'),
store = get(owner, 'store'),
type = get(this, 'type'),
record;
Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic'));
record = store.createRecord.call(store, type, hash);
this.pushObject(record);
return record;
}
});
__exports__["default"] = ManyArray;
});
define("ember-data/lib/system/record_arrays/record_array",
["../store","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
@module ember-data
*/
var PromiseArray = __dependency1__.PromiseArray;
var get = Ember.get, set = Ember.set;
/**
A record array is an array that contains records of a certain type. The record
array materializes records as needed when they are retrieved for the first
time. You should not create record arrays yourself. Instead, an instance of
`DS.RecordArray` or its subclasses will be returned by your application's store
in response to queries.
@class RecordArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.Evented
*/
var RecordArray = Ember.ArrayProxy.extend(Ember.Evented, {
/**
The model type contained by this record array.
@property type
@type DS.Model
*/
type: null,
/**
The array of client ids backing the record array. When a
record is requested from the record array, the record
for the client id at the same index is materialized, if
necessary, by the store.
@property content
@private
@type Ember.Array
*/
content: null,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all(App.Person);
people.get('isLoaded'); // true
```
@property isLoaded
@type Boolean
*/
isLoaded: false,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all(App.Person);
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@property isUpdating
@type Boolean
*/
isUpdating: false,
/**
The store that created this record array.
@property store
@private
@type DS.Store
*/
store: null,
/**
Retrieves an object from the content by index.
@method objectAtContent
@private
@param {Number} index
@return {DS.Model} record
*/
objectAtContent: function(index) {
var content = get(this, 'content');
return content.objectAt(index);
},
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
var people = store.all(App.Person);
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@method update
*/
update: function() {
if (get(this, 'isUpdating')) { return; }
var store = get(this, 'store'),
type = get(this, 'type');
return store.fetchAll(type, this);
},
/**
Adds a record to the `RecordArray`.
@method addRecord
@private
@param {DS.Model} record
*/
addRecord: function(record) {
get(this, 'content').addObject(record);
},
/**
Removes a record to the `RecordArray`.
@method removeRecord
@private
@param {DS.Model} record
*/
removeRecord: function(record) {
get(this, 'content').removeObject(record);
},
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
var messages = store.all(App.Message);
messages.forEach(function(message) {
message.set('hasBeenSeen', true);
});
messages.save();
```
@method save
@return {DS.PromiseArray} promise
*/
save: function() {
var promiseLabel = "DS: RecordArray#save " + get(this, 'type');
var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) {
return Ember.A(array);
}, null, "DS: RecordArray#save apply Ember.NativeArray");
return PromiseArray.create({ promise: promise });
},
_dissociateFromOwnRecords: function() {
var array = this;
this.forEach(function(record){
var recordArrays = record._recordArrays;
if (recordArrays) {
recordArrays.remove(array);
}
});
},
willDestroy: function(){
this._dissociateFromOwnRecords();
this._super();
}
});
__exports__["default"] = RecordArray;
});
define("ember-data/lib/system/relationships",
["./relationships/belongs_to","./relationships/has_many","../system/relationships/ext","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
/**
@module ember-data
*/
var belongsTo = __dependency1__["default"];
var hasMany = __dependency2__["default"];
__exports__.belongsTo = belongsTo;
__exports__.hasMany = hasMany;
});
define("ember-data/lib/system/relationships/belongs_to",
["../model","exports"],
function(__dependency1__, __exports__) {
"use strict";
var get = Ember.get, set = Ember.set,
isNone = Ember.isNone;
var Promise = Ember.RSVP.Promise;
var Model = __dependency1__.Model;
/**
@module ember-data
*/
function asyncBelongsTo(type, options, meta) {
return Ember.computed('data', function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'),
promiseLabel = "DS: Async belongsTo " + this + " : " + key,
promise;
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof store.modelFor(type));
return value === undefined ? null : DS.PromiseObject.create({
promise: Promise.cast(value, promiseLabel)
});
}
var link = data.links && data.links[key],
belongsTo = data[key];
if(!isNone(belongsTo)) {
promise = store.fetchRecord(belongsTo) || Promise.cast(belongsTo, promiseLabel);
return DS.PromiseObject.create({
promise: promise
});
} else if (link) {
promise = store.findBelongsTo(this, link, meta);
return DS.PromiseObject.create({
promise: promise
});
} else {
return null;
}
}).meta(meta);
}
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```javascript
App.User = DS.Model.extend({
profile: DS.belongsTo('profile')
});
App.Profile = DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
@namespace
@method belongsTo
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
function belongsTo(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
} else {
Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type)));
}
options = options || {};
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'belongsTo'
};
if (options.async) {
return asyncBelongsTo(type, options, meta);
}
return Ember.computed('data', function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'), belongsTo, typeClass;
if (typeof type === 'string') {
typeClass = store.modelFor(type);
} else {
typeClass = type;
}
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass);
return value === undefined ? null : value;
}
belongsTo = data[key];
if (isNone(belongsTo)) { return null; }
store.fetchRecord(belongsTo);
return belongsTo;
}).meta(meta);
}
/**
These observers observe all `belongsTo` relationships on the record. See
`relationships/ext` to see how these observers get their dependencies.
@class Model
@namespace DS
*/
Model.reopen({
/**
@method belongsToWillChange
@private
@static
@param record
@param key
*/
belongsToWillChange: Ember.beforeObserver(function(record, key) {
if (get(record, 'isLoaded')) {
var oldParent = get(record, key);
if (oldParent) {
var store = get(record, 'store'),
change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" });
change.sync();
this._changesToSync[key] = change;
}
}
}),
/**
@method belongsToDidChange
@private
@static
@param record
@param key
*/
belongsToDidChange: Ember.immediateObserver(function(record, key) {
if (get(record, 'isLoaded')) {
var newParent = get(record, key);
if (newParent) {
var store = get(record, 'store'),
change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" });
change.sync();
}
}
delete this._changesToSync[key];
})
});
__exports__["default"] = belongsTo;
});
define("ember-data/lib/system/relationships/ext",
["../../../../ember-inflector/lib/system","../model"],
function(__dependency1__, __dependency2__) {
"use strict";
var singularize = __dependency1__.singularize;
var Model = __dependency2__.Model;
var get = Ember.get, set = Ember.set;
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
Model.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param proto
@param key
@param value
*/
didDefineProperty: function(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.Descriptor) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
if (meta.isRelationship && meta.kind === 'belongsTo') {
Ember.addObserver(proto, key, null, 'belongsToDidChange');
Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange');
}
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
Model.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@return {subclass of DS.Model} the type of the relationship, or undefined
*/
typeForRelationship: function(name) {
var relationship = get(this, 'relationshipsByName').get(name);
return relationship && relationship.type;
},
inverseFor: function(name) {
var inverseType = this.typeForRelationship(name);
if (!inverseType) { return null; }
var options = this.metaForProperty(name).options;
if (options.inverse === null) { return null; }
var inverseName, inverseKind;
if (options.inverse) {
inverseName = options.inverse;
inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind;
} else {
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) { return null; }
Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, possibleRelationships) {
possibleRelationships = possibleRelationships || [];
var relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) { return; }
var relationships = relationshipMap.get(type);
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type));
}
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
var relationships = Ember.get(App.Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: Ember.computed(function() {
var map = new Ember.MapWithDefault({
defaultValue: function() { return []; }
});
// Loop through each computed property on the class
this.eachComputedProperty(function(name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
if (typeof meta.type === 'string') {
meta.type = this.store.modelFor(meta.type);
}
var relationshipsForType = map.get(meta.type);
relationshipsForType.push({ name: name, kind: meta.kind });
}
});
return map;
}),
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipNames = Ember.get(App.Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
var names = { hasMany: [], belongsTo: [] };
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relatedTypes = Ember.get(App.Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: Ember.computed(function() {
var type,
types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
type = meta.type;
if (typeof type === 'string') {
type = get(this, type, false) || this.store.modelFor(type);
}
Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type);
if (!types.contains(type)) {
Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type);
types.push(type);
}
}
});
return types;
}),
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: Ember.computed(function() {
var map = Ember.Map.create(), type;
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
meta.key = name;
type = meta.type;
if (!type && meta.kind === 'hasMany') {
type = singularize(name);
} else if (!type) {
type = name;
}
if (typeof type === 'string') {
meta.type = this.store.modelFor(type);
}
map.set(name, meta);
}
});
return map;
}),
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
var fields = Ember.get(App.Blog, 'fields');
fields.forEach(function(field, kind) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
get(this, 'relationshipsByName').forEach(function(name, relationship) {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType: function(callback, binding) {
get(this, 'relatedTypes').forEach(function(type) {
callback.call(binding, type);
});
}
});
Model.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
this.constructor.eachRelationship(callback, binding);
}
});
});
define("ember-data/lib/system/relationships/has_many",
["exports"],
function(__exports__) {
"use strict";
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties;
function asyncHasMany(type, options, meta) {
return Ember.computed('data', function(key) {
var relationship = this._relationships[key],
promiseLabel = "DS: Async hasMany " + this + " : " + key;
if (!relationship) {
var resolver = Ember.RSVP.defer(promiseLabel);
relationship = buildRelationship(this, key, options, function(store, data) {
var link = data.links && data.links[key];
var rel;
if (link) {
rel = store.findHasMany(this, link, meta, resolver);
} else {
rel = store.findMany(this, data[key], meta.type, resolver);
}
// cache the promise so we can use it
// when we come back and don't need to rebuild
// the relationship.
set(rel, 'promise', resolver.promise);
return rel;
});
}
var promise = relationship.get('promise').then(function() {
return relationship;
}, null, "DS: Async hasMany records received");
return DS.PromiseArray.create({
promise: promise
});
}).meta(meta).readOnly();
}
function buildRelationship(record, key, options, callback) {
var rels = record._relationships;
if (rels[key]) { return rels[key]; }
var data = get(record, 'data'),
store = get(record, 'store');
var relationship = rels[key] = callback.call(record, store, data);
return setProperties(relationship, {
owner: record,
name: key,
isPolymorphic: options.polymorphic
});
}
function hasRelationship(type, options) {
options = options || {};
var meta = {
type: type,
isRelationship: true,
options: options,
kind: 'hasMany'
};
if (options.async) {
return asyncHasMany(type, options, meta);
}
return Ember.computed('data', function(key) {
return buildRelationship(this, key, options, function(store, data) {
var records = data[key];
Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).everyProperty('isEmpty', false));
return store.findMany(this, data[key], meta.type);
});
}).meta(meta).readOnly();
}
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```javascript
App.Post = DS.Model.extend({
tags: DS.hasMany('tag')
});
App.Tag = DS.Model.extend({
posts: DS.hasMany('post')
});
```
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasManys` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```javascript
var belongsTo = DS.belongsTo,
hasMany = DS.hasMany;
App.Comment = DS.Model.extend({
onePost: belongsTo('post'),
twoPost: belongsTo('post'),
redPost: belongsTo('post'),
bluePost: belongsTo('post')
});
App.Post = DS.Model.extend({
comments: hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
function hasMany(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
}
return hasRelationship(type, options);
}
__exports__["default"] = hasMany;
});
define("ember-data/lib/system/store",
["exports"],
function(__exports__) {
"use strict";
/*globals Ember*/
/*jshint eqnull:true*/
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var once = Ember.run.once;
var isNone = Ember.isNone;
var forEach = Ember.EnumerableUtils.forEach;
var indexOf = Ember.EnumerableUtils.indexOf;
var map = Ember.EnumerableUtils.map;
var Promise = Ember.RSVP.Promise;
var copy = Ember.copy;
var Store, PromiseObject, PromiseArray;
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +reference+ means a record reference object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a subclass of DS.Model.
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function coerceId(id) {
return id == null ? null : id+'';
}
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```javascript
MyApp.Store = DS.Store.extend();
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `find()` method:
```javascript
var person = store.find('person', 123);
```
If your application has multiple `DS.Store` instances (an unusual case), you can
specify which store should be used:
```javascript
var person = store.find(App.Person, 123);
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```javascript
MyApp.store = DS.Store.create({
adapter: 'MyApp.CustomAdapter'
});
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
@class Store
@namespace DS
@extends Ember.Object
*/
Store = Ember.Object.extend({
/**
@method init
@private
*/
init: function() {
// internal bookkeeping; not observable
this.typeMaps = {};
this.recordArrayManager = DS.RecordArrayManager.create({
store: this
});
this._relationshipChanges = {};
this._pendingSave = [];
},
/**
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify `App.CustomAdapter` as a string, do:
```js
adapter: 'custom'
```
@property adapter
@default DS.RESTAdapter
@type {DS.Adapter|String}
*/
adapter: '-rest',
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function(record, options) {
return this.serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@returns DS.Adapter
*/
defaultAdapter: Ember.computed('adapter', function() {
var adapter = get(this, 'adapter');
Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof DS.Adapter));
if (typeof adapter === 'string') {
adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest');
}
if (DS.Adapter.detect(adapter)) {
adapter = adapter.create({
container: this.container
});
}
return adapter;
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of `App.Post`:
```js
store.createRecord('post', {
title: "Rails is omakase"
});
```
@method createRecord
@param {String} type
@param {Object} properties a hash of properties to set on the
newly created record.
@returns {DS.Model} record
*/
createRecord: function(type, properties) {
type = this.modelFor(type);
properties = copy(properties) || {};
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (isNone(properties.id)) {
properties.id = this._generateId(type);
}
// Coerce ID to a string
properties.id = coerceId(properties.id);
var record = this.buildRecord(type, properties.id);
// Move the record out of its initial `empty` state into
// the `loaded` state.
record.loadedData();
// Set the properties specified on the record.
record.setProperties(properties);
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} type
@returns {String} if the adapter can generate one, an ID
*/
_generateId: function(type) {
var adapter = this.adapterFor(type);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
var post = store.createRecord('post', {
title: "Rails is omakase"
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function(record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store. Only
non-dirty records can be unloaded.
Example
```javascript
store.find('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function(record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
This is the main entry point into finding records. The first parameter to
this method is the model's name as a string.
---
To find a record by ID, pass the `id` as the second parameter:
```javascript
store.find('person', 1);
```
The `find` method will always return a **promise** that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's `find`
method to find the necessary data.
The `find` method will always resolve its promise with the same object for
a given type and `id`.
---
To find all records for a type, call `find` with no additional parameters:
```javascript
store.find('person');
```
This will ask the adapter's `findAll` method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values.
---
To find a record by a query, call `find` with a hash as the second
parameter:
```javascript
store.find(App.Person, { page: 1 });
```
This will ask the adapter's `findQuery` method to find the records for
the query, and return a promise that will be resolved once the server
responds.
@method find
@param {String or subclass of DS.Model} type
@param {Object|String|Integer|null} id
@return {Promise} promise
*/
find: function(type, id) {
Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1);
Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id));
if (arguments.length === 1) {
return this.findAll(type);
}
// We are passed a query instead of an id.
if (Ember.typeOf(id) === 'object') {
return this.findQuery(type, id);
}
return this.findById(type, coerceId(id));
},
/**
This method returns a record for a given type and id combination.
@method findById
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@return {Promise} promise
*/
findById: function(type, id) {
type = this.modelFor(type);
var record = this.recordForId(type, id);
var fetchedRecord = this.fetchRecord(record);
return promiseObject(fetchedRecord || record, "DS: Store#findById " + type + " with id: " + id);
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} type
@param {Array} ids
@returns {Promise} promise
*/
findByIds: function(type, ids) {
var store = this;
var promiseLabel = "DS: Store#findByIds " + type;
return promiseArray(Ember.RSVP.all(map(ids, function(id) {
return store.findById(type, id);
})).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete"));
},
/**
This method is called by `findById` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method fetchRecord
@private
@param {DS.Model} record
@returns {Promise} promise
*/
fetchRecord: function(record) {
if (isNone(record)) { return null; }
if (record._loadingPromise) { return record._loadingPromise; }
if (!get(record, 'isEmpty')) { return null; }
var type = record.constructor,
id = get(record, 'id');
var adapter = this.adapterFor(type);
Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find);
var promise = _find(adapter, this, type, id);
record.loadingData(promise);
return promise;
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it's available.
Otherwise, it will return null.
```js
var post = store.getById('post', 1);
```
@method getById
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@param {DS.Model} record
*/
getById: function(type, id) {
if (this.hasRecordForId(type, id)) {
return this.recordForId(type, id);
} else {
return null;
}
},
/**
This method is called by the record's `reload` method.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} record
@return {Promise} promise
*/
reloadRecord: function(record) {
var type = record.constructor,
adapter = this.adapterFor(type),
id = get(record, 'id');
Ember.assert("You cannot reload a record without an ID", id);
Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find);
return _find(adapter, this, type, id);
},
/**
This method takes a list of records, groups the records by type,
converts the records into IDs, and then invokes the adapter's `findMany`
method.
The records are grouped by type to invoke `findMany` on adapters
for each unique type in records.
It is used both by a brand new relationship (via the `findMany`
method) or when the data underlying an existing relationship
changes.
@method fetchMany
@private
@param {Array} records
@param {DS.Model} owner
@return {Promise} promise
*/
fetchMany: function(records, owner) {
if (!records.length) { return; }
// Group By Type
var recordsByTypeMap = Ember.MapWithDefault.create({
defaultValue: function() { return Ember.A(); }
});
forEach(records, function(record) {
recordsByTypeMap.get(record.constructor).push(record);
});
var promises = [];
forEach(recordsByTypeMap, function(type, records) {
var ids = records.mapProperty('id'),
adapter = this.adapterFor(type);
Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany);
promises.push(_findMany(adapter, this, type, ids, owner));
}, this);
return Ember.RSVP.all(promises);
},
/**
Returns true if a record for a given type and ID is already loaded.
@method hasRecordForId
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@returns {Boolean}
*/
hasRecordForId: function(type, id) {
id = coerceId(id);
type = this.modelFor(type);
return !!this.typeMapFor(type).idToRecord[id];
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@private
@param {String or subclass of DS.Model} type
@param {String|Integer} id
@returns {DS.Model} record
*/
recordForId: function(type, id) {
type = this.modelFor(type);
id = coerceId(id);
var record = this.typeMapFor(type).idToRecord[id];
if (!record) {
record = this.buildRecord(type, id);
}
return record;
},
/**
@method findMany
@private
@param {DS.Model} owner
@param {Array} records
@param {String or subclass of DS.Model} type
@param {Resolver} resolver
@return {DS.ManyArray} records
*/
findMany: function(owner, records, type, resolver) {
type = this.modelFor(type);
records = Ember.A(records);
var unloadedRecords = records.filterProperty('isEmpty', true),
manyArray = this.recordArrayManager.createManyArray(type, records);
forEach(unloadedRecords, function(record) {
record.loadingData();
});
manyArray.loadingRecordsCount = unloadedRecords.length;
if (unloadedRecords.length) {
forEach(unloadedRecords, function(record) {
this.recordArrayManager.registerWaitingRecordArray(record, manyArray);
}, this);
resolver.resolve(this.fetchMany(unloadedRecords, owner));
} else {
if (resolver) { resolver.resolve(); }
manyArray.set('isLoaded', true);
once(manyArray, 'trigger', 'didLoad');
}
return manyArray;
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {DS.Model} owner
@param {any} link
@param {String or subclass of DS.Model} type
@return {Promise} promise
*/
findHasMany: function(owner, link, relationship, resolver) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany);
var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([]));
resolver.resolve(_findHasMany(adapter, this, owner, link, relationship));
return records;
},
/**
@method findBelongsTo
@private
@param {DS.Model} owner
@param {any} link
@param {Relationship} relationship
@return {Promise} promise
*/
findBelongsTo: function(owner, link, relationship) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo);
return _findBelongsTo(adapter, this, owner, link, relationship);
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
This method returns a promise, which is resolved with a `RecordArray`
once the server returns.
@method findQuery
@private
@param {String or subclass of DS.Model} type
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise
*/
findQuery: function(type, query) {
type = this.modelFor(type);
var array = this.recordArrayManager
.createAdapterPopulatedRecordArray(type, query);
var adapter = this.adapterFor(type);
Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery);
return promiseArray(_findQuery(adapter, this, type, query, array));
},
/**
This method returns an array of all records adapter can find.
It triggers the adapter's `findAll` method to give it an opportunity to populate
the array with records of that type.
@method findAll
@private
@param {String or subclass of DS.Model} type
@return {DS.AdapterPopulatedRecordArray}
*/
findAll: function(type) {
type = this.modelFor(type);
return this.fetchAll(type, this.all(type));
},
/**
@method fetchAll
@private
@param {DS.Model} type
@param {DS.RecordArray} array
@returns {Promise} promise
*/
fetchAll: function(type, array) {
var adapter = this.adapterFor(type),
sinceToken = this.typeMapFor(type).metadata.since;
set(array, 'isUpdating', true);
Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll);
return promiseArray(_findAll(adapter, this, type, sinceToken));
},
/**
@method didUpdateAll
@param {DS.Model} type
*/
didUpdateAll: function(type) {
var findAllCache = this.typeMapFor(type).findAllCache;
set(findAllCache, 'isUpdating', false);
},
/**
This method returns a filtered array that contains all of the known records
for a given type.
Note that because it's just a filter, it will have any locally
created records of the type.
Also note that multiple calls to `all` for a given type will always
return the same RecordArray.
Example
```javascript
var local_posts = store.all(App.Post);
```
@method all
@param {String or subclass of DS.Model} type
@return {DS.RecordArray}
*/
all: function(type) {
type = this.modelFor(type);
var typeMap = this.typeMapFor(type),
findAllCache = typeMap.findAllCache;
if (findAllCache) { return findAllCache; }
var array = this.recordArrayManager.createRecordArray(type);
typeMap.findAllCache = array;
return array;
},
/**
This method unloads all of the known records for a given type.
```javascript
store.unloadAll(App.Post);
```
@method unloadAll
@param {String or subclass of DS.Model} type
*/
unloadAll: function(type) {
var modelType = this.modelFor(type);
var typeMap = this.typeMapFor(modelType);
var records = typeMap.records.slice();
var record;
for (var i = 0; i < records.length; i++) {
record = records[i];
record.unloadRecord();
record.destroy(); // maybe within unloadRecord
}
typeMap.findAllCache = null;
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The callback function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query which will be triggered at first. The
results returned by the server could then appear in the filter if they
match the filter function.
Example
```javascript
store.filter(App.Post, {unread: true}, function(post) {
return post.get('unread');
}).then(function(unreadPosts) {
unreadPosts.get('length'); // 5
var unreadPost = unreadPosts.objectAt(0);
unreadPost.set('unread', false);
unreadPosts.get('length'); // 4
});
```
@method filter
@param {String or subclass of DS.Model} type
@param {Object} query optional query
@param {Function} filter
@return {DS.PromiseArray}
*/
filter: function(type, query, filter) {
var promise;
// allow an optional server query
if (arguments.length === 3) {
promise = this.findQuery(type, query);
} else if (arguments.length === 2) {
filter = query;
}
type = this.modelFor(type);
var array = this.recordArrayManager
.createFilteredRecordArray(type, filter);
promise = promise || Promise.cast(array);
return promiseArray(promise.then(function() {
return array;
}, null, "DS: Store#filter of " + type));
},
/**
This method returns if a certain record is already loaded
in the store. Use this function to know beforehand if a find()
will result in a request or that it will be a cache hit.
Example
```javascript
store.recordIsLoaded(App.Post, 1); // false
store.find(App.Post, 1).then(function() {
store.recordIsLoaded(App.Post, 1); // true
});
```
@method recordIsLoaded
@param {String or subclass of DS.Model} type
@param {string} id
@return {boolean}
*/
recordIsLoaded: function(type, id) {
if (!this.hasRecordForId(type, id)) { return false; }
return !get(this.recordForId(type, id), 'isEmpty');
},
/**
This method returns the metadata for a specific type.
@method metadataFor
@param {String or subclass of DS.Model} type
@return {object}
*/
metadataFor: function(type) {
type = this.modelFor(type);
return this.typeMapFor(type).metadata;
},
// ............
// . UPDATING .
// ............
/**
If the adapter updates attributes or acknowledges creation
or deletion, the record will notify the store to update its
membership in any filters.
To avoid thrashing, this method is invoked only once per
run loop per record.
@method dataWasUpdated
@private
@param {Class} type
@param {DS.Model} record
*/
dataWasUpdated: function(type, record) {
this.recordArrayManager.recordDidChange(record);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {DS.Model} record
@param {Resolver} resolver
*/
scheduleSave: function(record, resolver) {
record.adapterWillCommit();
this._pendingSave.push([record, resolver]);
once(this, 'flushPendingSave');
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function() {
var pending = this._pendingSave.slice();
this._pendingSave = [];
forEach(pending, function(tuple) {
var record = tuple[0], resolver = tuple[1],
adapter = this.adapterFor(record.constructor),
operation;
if (get(record, 'isNew')) {
operation = 'createRecord';
} else if (get(record, 'isDeleted')) {
operation = 'deleteRecord';
} else {
operation = 'updateRecord';
}
resolver.resolve(_commit(adapter, this, operation, record));
}, this);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {DS.Model} record the in-flight record
@param {Object} data optional data (see above)
*/
didSaveRecord: function(record, data) {
if (data) {
// normalize relationship IDs into records
data = normalizeRelationships(this, record.constructor, data, record);
this.updateId(record, data);
}
record.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {DS.Model} record
@param {Object} errors
*/
recordWasInvalid: function(record, errors) {
record.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {DS.Model} record
*/
recordWasError: function(record) {
record.adapterDidError();
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {DS.Model} record
@param {Object} data
*/
updateId: function(record, data) {
var oldId = get(record, 'id'),
id = coerceId(data.id);
Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId);
this.typeMapFor(record.constructor).idToRecord[id] = record;
set(record, 'id', id);
},
/**
Returns a map of IDs to client IDs for a given type.
@method typeMapFor
@private
@param type
@return {Object} typeMap
*/
typeMapFor: function(type) {
var typeMaps = get(this, 'typeMaps'),
guid = Ember.guidFor(type),
typeMap;
typeMap = typeMaps[guid];
if (typeMap) { return typeMap; }
typeMap = {
idToRecord: {},
records: [],
metadata: {},
type: type
};
typeMaps[guid] = typeMap;
return typeMap;
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {String or subclass of DS.Model} type
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
_load: function(type, data, partial) {
var id = coerceId(data.id),
record = this.recordForId(type, id);
record.setupData(data, partial);
this.recordArrayManager.recordDidChange(record);
return record;
},
/**
Returns a model class for a particular key. Used by
methods that take a type key (like `find`, `createRecord`,
etc.)
@method modelFor
@param {String or subclass of DS.Model} key
@returns {subclass of DS.Model}
*/
modelFor: function(key) {
var factory;
if (typeof key === 'string') {
var normalizedKey = this.container.normalize('model:' + key);
factory = this.container.lookupFactory(normalizedKey);
if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); }
factory.typeKey = normalizedKey.split(':', 2)[1];
} else {
// A factory already supplied.
factory = key;
}
factory.store = this;
return factory;
},
/**
Push some data for a given type into the store.
This method expects normalized data:
* The ID is a key named `id` (an ID is mandatory)
* The names of attributes are the ones you used in
your model's `DS.attr`s.
* Your relationships must be:
* represented as IDs or Arrays of IDs
* represented as model instances
* represented as URLs, under the `links` key
For this model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
children: [1, 2, 3]
}
```
To represent the children relationship as a URL:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
links: {
children: "/people/1/children"
}
}
```
If you're streaming data or implementing an adapter,
make sure that you have converted the incoming data
into this form.
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {String or subclass of DS.Model} type
@param {Object} data
@returns {DS.Model} the record that was created or
updated.
*/
push: function(type, data, _partial) {
// _partial is an internal param used by `update`.
// If passed, it means that the data should be
// merged into the existing data, not replace it.
Ember.assert("You must include an `id` in a hash passed to `push`", data.id != null);
type = this.modelFor(type);
// normalize relationship IDs into records
data = normalizeRelationships(this, type, data);
this._load(type, data, _partial);
return this.recordForId(type, data.id);
},
/**
Push some raw data into the store.
The data will be automatically deserialized using the
serializer for the `type` param.
This method can be used both to push in brand new
records, as well as to update existing records.
You can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```js
App.ApplicationSerializer = DS.ActiveModelSerializer;
var pushData = {
posts: [
{id: 1, post_title: "Great post", comment_ids: [2]}
],
comments: [
{id: 2, comment_body: "Insightful comment"}
]
}
store.pushPayload('post', pushData);
```
@method pushPayload
@param {String} type
@param {Object} payload
*/
pushPayload: function (type, payload) {
var serializer;
if (!payload) {
payload = type;
serializer = defaultSerializer(this.container);
Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", serializer.pushPayload);
} else {
serializer = this.serializerFor(type);
}
serializer.pushPayload(this, payload);
},
update: function(type, data) {
Ember.assert("You must include an `id` in a hash passed to `update`", data.id != null);
return this.push(type, data, true);
},
/**
If you have an Array of normalized data to push,
you can call `pushMany` with the Array, and it will
call `push` repeatedly for you.
@method pushMany
@param {String or subclass of DS.Model} type
@param {Array} datas
@return {Array}
*/
pushMany: function(type, datas) {
return map(datas, function(data) {
return this.push(type, data);
}, this);
},
/**
If you have some metadata to set for a type
you can call `metaForType`.
@method metaForType
@param {String or subclass of DS.Model} type
@param {Object} metadata
*/
metaForType: function(type, metadata) {
type = this.modelFor(type);
Ember.merge(this.typeMapFor(type).metadata, metadata);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method buildRecord
@private
@param {subclass of DS.Model} type
@param {String} id
@param {Object} data
@returns {DS.Model} record
*/
buildRecord: function(type, id, data) {
var typeMap = this.typeMapFor(type),
idToRecord = typeMap.idToRecord;
Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]);
Ember.assert("`" + Ember.inspect(type)+ "` does not appear to be an ember-data model", (typeof type._create === 'function') );
// lookupFactory should really return an object that creates
// instances with the injections applied
var record = type._create({
id: id,
store: this,
container: this.container
});
if (data) {
record.setupData(data);
}
// if we're creating an item, this process will be done
// later, once the object has been persisted.
if (id) {
idToRecord[id] = record;
}
typeMap.records.push(record);
return record;
},
// ...............
// . DESTRUCTION .
// ...............
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method dematerializeRecord
@private
@param {DS.Model} record
*/
dematerializeRecord: function(record) {
var type = record.constructor,
typeMap = this.typeMapFor(type),
id = get(record, 'id');
record.updateRecordArrays();
if (id) {
delete typeMap.idToRecord[id];
}
var loc = indexOf(typeMap.records, record);
typeMap.records.splice(loc, 1);
},
// ........................
// . RELATIONSHIP CHANGES .
// ........................
addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) {
var clientId = childRecord.clientId,
parentClientId = parentRecord ? parentRecord : parentRecord;
var key = childKey + parentKey;
var changes = this._relationshipChanges;
if (!(clientId in changes)) {
changes[clientId] = {};
}
if (!(parentClientId in changes[clientId])) {
changes[clientId][parentClientId] = {};
}
if (!(key in changes[clientId][parentClientId])) {
changes[clientId][parentClientId][key] = {};
}
changes[clientId][parentClientId][key][change.changeType] = change;
},
removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) {
var clientId = clientRecord.clientId,
parentClientId = parentRecord ? parentRecord.clientId : parentRecord;
var changes = this._relationshipChanges;
var key = childKey + parentKey;
if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){
return;
}
delete changes[clientId][parentClientId][key][type];
},
relationshipChangePairsFor: function(record){
var toReturn = [];
if( !record ) { return toReturn; }
//TODO(Igor) What about the other side
var changesObject = this._relationshipChanges[record.clientId];
for (var objKey in changesObject){
if(changesObject.hasOwnProperty(objKey)){
for (var changeKey in changesObject[objKey]){
if(changesObject[objKey].hasOwnProperty(changeKey)){
toReturn.push(changesObject[objKey][changeKey]);
}
}
}
}
return toReturn;
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns the adapter for a given type.
@method adapterFor
@private
@param {subclass of DS.Model} type
@returns DS.Adapter
*/
adapterFor: function(type) {
var container = this.container, adapter;
if (container) {
adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application');
}
return adapter || get(this, 'defaultAdapter');
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
If no `App.ApplicationSerializer` is found, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@private
@param {String} type the record to serialize
@return {DS.Serializer}
*/
serializerFor: function(type) {
type = this.modelFor(type);
var adapter = this.adapterFor(type);
return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer);
},
willDestroy: function() {
var map = this.typeMaps;
var keys = Ember.keys(map);
var store = this;
var types = keys.map(byType);
this.recordArrayManager.destroy();
types.forEach(this.unloadAll, this);
function byType(entry) {
return map[entry].type;
}
}
});
function normalizeRelationships(store, type, data, record) {
type.eachRelationship(function(key, relationship) {
// A link (usually a URL) was already provided in
// normalized form
if (data.links && data.links[key]) {
if (record && relationship.options.async) { record._relationships[key] = null; }
return;
}
var kind = relationship.kind,
value = data[key];
if (value == null) { return; }
if (kind === 'belongsTo') {
deserializeRecordId(store, data, key, relationship, value);
} else if (kind === 'hasMany') {
deserializeRecordIds(store, data, key, relationship, value);
addUnsavedRecords(record, key, value);
}
});
return data;
}
function deserializeRecordId(store, data, key, relationship, id) {
if (isNone(id) || id instanceof DS.Model) {
return;
}
var type;
if (typeof id === 'number' || typeof id === 'string') {
type = typeFor(relationship, key, data);
data[key] = store.recordForId(type, id);
} else if (typeof id === 'object') {
// polymorphic
data[key] = store.recordForId(id.type, id.id);
}
}
function typeFor(relationship, key, data) {
if (relationship.options.polymorphic) {
return data[key + "Type"];
} else {
return relationship.type;
}
}
function deserializeRecordIds(store, data, key, relationship, ids) {
for (var i=0, l=ids.length; i<l; i++) {
deserializeRecordId(store, ids, i, relationship, ids[i]);
}
}
// If there are any unsaved records that are in a hasMany they won't be
// in the payload, so add them back in manually.
function addUnsavedRecords(record, key, data) {
if(record) {
data.pushObjects(record.get(key).filterBy('isNew'));
}
}
// Delegation to the adapter and promise management
/**
A `PromiseArray` is an object that acts like both an `Ember.Array`
and a promise. When the promise is resolved the the resulting value
will be set to the `PromiseArray`'s `content` property. This makes
it easy to create data bindings with the `PromiseArray` that will be
updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseArray = DS.PromiseArray.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseArray.get('length'); // 0
promiseArray.then(function() {
promiseArray.get('length'); // 100
});
```
@class PromiseArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.PromiseProxyMixin
*/
PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);
/**
A `PromiseObject` is an object that acts like both an `Ember.Object`
and a promise. When the promise is resolved the the resulting value
will be set to the `PromiseObject`'s `content` property. This makes
it easy to create data bindings with the `PromiseObject` that will
be updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseObject = DS.PromiseObject.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseObject.get('name'); // null
promiseObject.then(function() {
promiseObject.get('name'); // 'Tomster'
});
```
@class PromiseObject
@namespace DS
@extends Ember.ObjectProxy
@uses Ember.PromiseProxyMixin
*/
PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
function promiseObject(promise, label) {
return PromiseObject.create({
promise: Promise.cast(promise, label)
});
}
function promiseArray(promise, label) {
return PromiseArray.create({
promise: Promise.cast(promise, label)
});
}
function isThenable(object) {
return object && typeof object.then === 'function';
}
function serializerFor(container, type, defaultSerializer) {
return container.lookup('serializer:'+type) ||
container.lookup('serializer:application') ||
container.lookup('serializer:' + defaultSerializer) ||
container.lookup('serializer:-default');
}
function defaultSerializer(container) {
return container.lookup('serializer:application') ||
container.lookup('serializer:-default');
}
function serializerForAdapter(adapter, type) {
var serializer = adapter.serializer,
defaultSerializer = adapter.defaultSerializer,
container = adapter.container;
if (container && serializer === undefined) {
serializer = serializerFor(container, type.typeKey, defaultSerializer);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function(store, type, payload) { return payload; }
};
}
return serializer;
}
function _find(adapter, store, type, id) {
var promise = adapter.find(store, type, id),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#find of " + type + " with id: " + id;
return Promise.cast(promise, label).then(function(adapterPayload) {
Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload);
var payload = serializer.extract(store, type, adapterPayload, id, 'find');
return store.push(type, payload);
}, function(error) {
var record = store.getById(type, id);
record.notFound();
throw error;
}, "DS: Extract payload of '" + type + "'");
}
function _findMany(adapter, store, type, ids, owner) {
var promise = adapter.findMany(store, type, ids, owner),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#findMany of " + type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findMany');
Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
}, null, "DS: Extract payload of " + type);
}
function _findHasMany(adapter, store, record, link, relationship) {
var promise = adapter.findHasMany(store, record, link, relationship),
serializer = serializerForAdapter(adapter, relationship.type),
label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany');
Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
var records = store.pushMany(relationship.type, payload);
record.updateHasMany(relationship.key, records);
}, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type);
}
function _findBelongsTo(adapter, store, record, link, relationship) {
var promise = adapter.findBelongsTo(store, record, link, relationship),
serializer = serializerForAdapter(adapter, relationship.type),
label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo');
var record = store.push(relationship.type, payload);
record.updateBelongsTo(relationship.key, record);
return record;
}, null, "DS: Extract payload of " + record + " : " + relationship.type);
}
function _findAll(adapter, store, type, sinceToken) {
var promise = adapter.findAll(store, type, sinceToken),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#findAll of " + type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findAll');
Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
store.didUpdateAll(type);
return store.all(type);
}, null, "DS: Extract payload of findAll " + type);
}
function _findQuery(adapter, store, type, query, recordArray) {
var promise = adapter.findQuery(store, type, query, recordArray),
serializer = serializerForAdapter(adapter, type),
label = "DS: Handle Adapter#findQuery of " + type;
return Promise.cast(promise, label).then(function(adapterPayload) {
var payload = serializer.extract(store, type, adapterPayload, null, 'findQuery');
Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
recordArray.load(payload);
return recordArray;
}, null, "DS: Extract payload of findQuery " + type);
}
function _commit(adapter, store, operation, record) {
var type = record.constructor,
promise = adapter[operation](store, type, record),
serializer = serializerForAdapter(adapter, type),
label = "DS: Extract and notify about " + operation + " completion of " + record;
Ember.assert("Your adapter's '" + operation + "' method must return a promise, but it returned " + promise, isThenable(promise));
return promise.then(function(adapterPayload) {
var payload;
if (adapterPayload) {
payload = serializer.extract(store, type, adapterPayload, get(record, 'id'), operation);
} else {
payload = adapterPayload;
}
store.didSaveRecord(record, payload);
return record;
}, function(reason) {
if (reason instanceof DS.InvalidError) {
store.recordWasInvalid(record, reason.errors);
} else {
store.recordWasError(record, reason);
}
throw reason;
}, label);
}
__exports__.Store = Store;
__exports__.PromiseArray = PromiseArray;
__exports__.PromiseObject = PromiseObject;
__exports__["default"] = Store;
});
define("ember-data/lib/transforms",
["./transforms/base","./transforms/number","./transforms/date","./transforms/string","./transforms/boolean","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var NumberTransform = __dependency2__["default"];
var DateTransform = __dependency3__["default"];
var StringTransform = __dependency4__["default"];
var BooleanTransform = __dependency5__["default"];
__exports__.Transform = Transform;
__exports__.NumberTransform = NumberTransform;
__exports__.DateTransform = DateTransform;
__exports__.StringTransform = StringTransform;
__exports__.BooleanTransform = BooleanTransform;
});
define("ember-data/lib/transforms/base",
["exports"],
function(__exports__) {
"use strict";
/**
The `DS.Transform` class is used to serialize and deserialize model
attributes when they are saved or loaded from an
adapter. Subclassing `DS.Transform` is useful for creating custom
attributes. All subclasses of `DS.Transform` must implement a
`serialize` and a `deserialize` method.
Example
```javascript
App.RawTransform = DS.Transform.extend({
deserialize: function(serialized) {
return serialized;
},
serialize: function(deserialized) {
return deserialized;
}
});
```
Usage
```javascript
var attr = DS.attr;
App.Requirement = DS.Model.extend({
name: attr('string'),
optionsArray: attr('raw')
});
```
@class Transform
@namespace DS
*/
var Transform = Ember.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize: function(deserialized) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
@return The serialized value
*/
serialize: Ember.required(),
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param serialized The serialized value
@return The deserialized value
*/
deserialize: Ember.required()
});
__exports__["default"] = Transform;
});
define("ember-data/lib/transforms/boolean",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
/**
The `DS.BooleanTransform` class is used to serialize and deserialize
boolean attributes on Ember Data record objects. This transform is
used when `boolean` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class BooleanTransform
@extends DS.Transform
@namespace DS
*/
var BooleanTransform = Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function(deserialized) {
return Boolean(deserialized);
}
});
__exports__["default"] = BooleanTransform;
});
define("ember-data/lib/transforms/date",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
/**
The `DS.DateTransform` class is used to serialize and deserialize
date attributes on Ember Data record objects. This transform is used
when `date` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class DateTransform
@extends DS.Transform
@namespace DS
*/
var Transform = __dependency1__["default"];
var DateTransform = Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "string") {
return new Date(Ember.Date.parse(serialized));
} else if (type === "number") {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is not present in the data,
// return undefined, not null.
return serialized;
} else {
return null;
}
},
serialize: function(date) {
if (date instanceof Date) {
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var pad = function(num) {
return num < 10 ? "0"+num : ""+num;
};
var utcYear = date.getUTCFullYear(),
utcMonth = date.getUTCMonth(),
utcDayOfMonth = date.getUTCDate(),
utcDay = date.getUTCDay(),
utcHours = date.getUTCHours(),
utcMinutes = date.getUTCMinutes(),
utcSeconds = date.getUTCSeconds();
var dayOfWeek = days[utcDay];
var dayOfMonth = pad(utcDayOfMonth);
var month = months[utcMonth];
return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " +
pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT";
} else {
return null;
}
}
});
__exports__["default"] = DateTransform;
});
define("ember-data/lib/transforms/number",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var empty = Ember.isEmpty;
/**
The `DS.NumberTransform` class is used to serialize and deserialize
numeric attributes on Ember Data record objects. This transform is
used when `number` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class NumberTransform
@extends DS.Transform
@namespace DS
*/
var NumberTransform = Transform.extend({
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
},
serialize: function(deserialized) {
return empty(deserialized) ? null : Number(deserialized);
}
});
__exports__["default"] = NumberTransform;
});
define("ember-data/lib/transforms/string",
["./base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Transform = __dependency1__["default"];
var none = Ember.isNone;
/**
The `DS.StringTransform` class is used to serialize and deserialize
string attributes on Ember Data record objects. This transform is
used when `string` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class StringTransform
@extends DS.Transform
@namespace DS
*/
var StringTransform = Transform.extend({
deserialize: function(serialized) {
return none(serialized) ? null : String(serialized);
},
serialize: function(deserialized) {
return none(deserialized) ? null : String(deserialized);
}
});
__exports__["default"] = StringTransform;
});
define("ember-inflector/lib/ext/string",
["../system/string"],
function(__dependency1__) {
"use strict";
var pluralize = __dependency1__.pluralize;
var singularize = __dependency1__.singularize;
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function() {
return pluralize(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function() {
return singularize(this);
};
}
});
define("ember-inflector/lib/main",
["./system","./ext/string","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var Inflector = __dependency1__.Inflector;
var inflections = __dependency1__.inflections;
var pluralize = __dependency1__.pluralize;
var singularize = __dependency1__.singularize;
Inflector.defaultRules = inflections;
Ember.Inflector = Inflector;
Ember.String.pluralize = pluralize;
Ember.String.singularize = singularize;
__exports__["default"] = Inflector;
__exports__.pluralize = pluralize;
__exports__.singularize = singularize;
});
define("ember-inflector/lib/system",
["./system/inflector","./system/string","./system/inflections","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var Inflector = __dependency1__["default"];
var pluralize = __dependency2__.pluralize;
var singularize = __dependency2__.singularize;
var defaultRules = __dependency3__["default"];
Inflector.inflector = new Inflector(defaultRules);
__exports__.Inflector = Inflector;
__exports__.singularize = singularize;
__exports__.pluralize = pluralize;
__exports__.defaultRules = defaultRules;
});
define("ember-inflector/lib/system/inflections",
["exports"],
function(__exports__) {
"use strict";
var defaultRules = {
plurals: [
[/$/, 's'],
[/s$/i, 's'],
[/^(ax|test)is$/i, '$1es'],
[/(octop|vir)us$/i, '$1i'],
[/(octop|vir)i$/i, '$1i'],
[/(alias|status)$/i, '$1es'],
[/(bu)s$/i, '$1ses'],
[/(buffal|tomat)o$/i, '$1oes'],
[/([ti])um$/i, '$1a'],
[/([ti])a$/i, '$1a'],
[/sis$/i, 'ses'],
[/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],
[/(hive)$/i, '$1s'],
[/([^aeiouy]|qu)y$/i, '$1ies'],
[/(x|ch|ss|sh)$/i, '$1es'],
[/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],
[/^(m|l)ouse$/i, '$1ice'],
[/^(m|l)ice$/i, '$1ice'],
[/^(ox)$/i, '$1en'],
[/^(oxen)$/i, '$1'],
[/(quiz)$/i, '$1zes']
],
singular: [
[/s$/i, ''],
[/(ss)$/i, '$1'],
[/(n)ews$/i, '$1ews'],
[/([ti])a$/i, '$1um'],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'],
[/(^analy)(sis|ses)$/i, '$1sis'],
[/([^f])ves$/i, '$1fe'],
[/(hive)s$/i, '$1'],
[/(tive)s$/i, '$1'],
[/([lr])ves$/i, '$1f'],
[/([^aeiouy]|qu)ies$/i, '$1y'],
[/(s)eries$/i, '$1eries'],
[/(m)ovies$/i, '$1ovie'],
[/(x|ch|ss|sh)es$/i, '$1'],
[/^(m|l)ice$/i, '$1ouse'],
[/(bus)(es)?$/i, '$1'],
[/(o)es$/i, '$1'],
[/(shoe)s$/i, '$1'],
[/(cris|test)(is|es)$/i, '$1is'],
[/^(a)x[ie]s$/i, '$1xis'],
[/(octop|vir)(us|i)$/i, '$1us'],
[/(alias|status)(es)?$/i, '$1'],
[/^(ox)en/i, '$1'],
[/(vert|ind)ices$/i, '$1ex'],
[/(matr)ices$/i, '$1ix'],
[/(quiz)zes$/i, '$1'],
[/(database)s$/i, '$1']
],
irregularPairs: [
['person', 'people'],
['man', 'men'],
['child', 'children'],
['sex', 'sexes'],
['move', 'moves'],
['cow', 'kine'],
['zombie', 'zombies']
],
uncountable: [
'equipment',
'information',
'rice',
'money',
'species',
'series',
'fish',
'sheep',
'jeans',
'police'
]
};
__exports__["default"] = defaultRules;
});
define("ember-inflector/lib/system/inflector",
["exports"],
function(__exports__) {
"use strict";
var BLANK_REGEX = /^\s*$/;
function loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow') //=> 'kine'
inflector.singularize('kine') //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice') // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice') // => 'advice'
inflector.pluralize('formula') // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula') // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [ /$/, 's' ],
singular: [ /\s$/, '' ],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || {};
ruleSet.irregularPairs = ruleSet.irregularPairs || {};
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: {},
irregularInverse: {},
uncountable: {}
};
loadUncountable(rules, ruleSet.uncountable);
loadIrregular(rules, ruleSet.irregularPairs);
}
Inflector.prototype = {
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function(regex, string) {
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function(regex, string) {
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function(string) {
loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function(word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function(word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function(word, typeRules, irregular) {
var inflection, substitution, result, lowercase, isBlank,
isUncountable, isIrregular, isIrregularInverse, rule;
isBlank = BLANK_REGEX.test(word);
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
isUncountable = this.rules.uncountable[lowercase];
if (isUncountable) {
return word;
}
isIrregular = irregular && irregular[lowercase];
if (isIrregular) {
return isIrregular;
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i-1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
__exports__["default"] = Inflector;
});
define("ember-inflector/lib/system/string",
["./inflector","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Inflector = __dependency1__["default"];
var pluralize = function(word) {
return Inflector.inflector.pluralize(word);
};
var singularize = function(word) {
return Inflector.inflector.singularize(word);
};
__exports__.pluralize = pluralize;
__exports__.singularize = singularize;
});
global.DS = requireModule('ember-data/lib/main')['default'];
}(window)); | thebitfarm/devweb | webroot/js/libs/ember-data/ember-data.js | JavaScript | mit | 340,618 |
/*
* Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/mlx5/cmd.h>
#include <linux/mlx5/vport.h>
#include <rdma/ib_mad.h>
#include <rdma/ib_smi.h>
#include <rdma/ib_pma.h>
#include "mlx5_ib.h"
enum {
MLX5_IB_VENDOR_CLASS1 = 0x9,
MLX5_IB_VENDOR_CLASS2 = 0xa
};
int mlx5_MAD_IFC(struct mlx5_ib_dev *dev, int ignore_mkey, int ignore_bkey,
u8 port, const struct ib_wc *in_wc, const struct ib_grh *in_grh,
const void *in_mad, void *response_mad)
{
u8 op_modifier = 0;
/* Key check traps can't be generated unless we have in_wc to
* tell us where to send the trap.
*/
if (ignore_mkey || !in_wc)
op_modifier |= 0x1;
if (ignore_bkey || !in_wc)
op_modifier |= 0x2;
return mlx5_core_mad_ifc(dev->mdev, in_mad, response_mad, op_modifier, port);
}
static int process_mad(struct ib_device *ibdev, int mad_flags, u8 port_num,
const struct ib_wc *in_wc, const struct ib_grh *in_grh,
const struct ib_mad *in_mad, struct ib_mad *out_mad)
{
u16 slid;
int err;
slid = in_wc ? in_wc->slid : be16_to_cpu(IB_LID_PERMISSIVE);
if (in_mad->mad_hdr.method == IB_MGMT_METHOD_TRAP && slid == 0)
return IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_CONSUMED;
if (in_mad->mad_hdr.mgmt_class == IB_MGMT_CLASS_SUBN_LID_ROUTED ||
in_mad->mad_hdr.mgmt_class == IB_MGMT_CLASS_SUBN_DIRECTED_ROUTE) {
if (in_mad->mad_hdr.method != IB_MGMT_METHOD_GET &&
in_mad->mad_hdr.method != IB_MGMT_METHOD_SET &&
in_mad->mad_hdr.method != IB_MGMT_METHOD_TRAP_REPRESS)
return IB_MAD_RESULT_SUCCESS;
/* Don't process SMInfo queries -- the SMA can't handle them.
*/
if (in_mad->mad_hdr.attr_id == IB_SMP_ATTR_SM_INFO)
return IB_MAD_RESULT_SUCCESS;
} else if (in_mad->mad_hdr.mgmt_class == IB_MGMT_CLASS_PERF_MGMT ||
in_mad->mad_hdr.mgmt_class == MLX5_IB_VENDOR_CLASS1 ||
in_mad->mad_hdr.mgmt_class == MLX5_IB_VENDOR_CLASS2 ||
in_mad->mad_hdr.mgmt_class == IB_MGMT_CLASS_CONG_MGMT) {
if (in_mad->mad_hdr.method != IB_MGMT_METHOD_GET &&
in_mad->mad_hdr.method != IB_MGMT_METHOD_SET)
return IB_MAD_RESULT_SUCCESS;
} else {
return IB_MAD_RESULT_SUCCESS;
}
err = mlx5_MAD_IFC(to_mdev(ibdev),
mad_flags & IB_MAD_IGNORE_MKEY,
mad_flags & IB_MAD_IGNORE_BKEY,
port_num, in_wc, in_grh, in_mad, out_mad);
if (err)
return IB_MAD_RESULT_FAILURE;
/* set return bit in status of directed route responses */
if (in_mad->mad_hdr.mgmt_class == IB_MGMT_CLASS_SUBN_DIRECTED_ROUTE)
out_mad->mad_hdr.status |= cpu_to_be16(1 << 15);
if (in_mad->mad_hdr.method == IB_MGMT_METHOD_TRAP_REPRESS)
/* no response for trap repress */
return IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_CONSUMED;
return IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_REPLY;
}
static void pma_cnt_ext_assign(struct ib_pma_portcounters_ext *pma_cnt_ext,
void *out)
{
#define MLX5_SUM_CNT(p, cntr1, cntr2) \
(MLX5_GET64(query_vport_counter_out, p, cntr1) + \
MLX5_GET64(query_vport_counter_out, p, cntr2))
pma_cnt_ext->port_xmit_data =
cpu_to_be64(MLX5_SUM_CNT(out, transmitted_ib_unicast.octets,
transmitted_ib_multicast.octets) >> 2);
pma_cnt_ext->port_rcv_data =
cpu_to_be64(MLX5_SUM_CNT(out, received_ib_unicast.octets,
received_ib_multicast.octets) >> 2);
pma_cnt_ext->port_xmit_packets =
cpu_to_be64(MLX5_SUM_CNT(out, transmitted_ib_unicast.packets,
transmitted_ib_multicast.packets));
pma_cnt_ext->port_rcv_packets =
cpu_to_be64(MLX5_SUM_CNT(out, received_ib_unicast.packets,
received_ib_multicast.packets));
pma_cnt_ext->port_unicast_xmit_packets =
MLX5_GET64_BE(query_vport_counter_out,
out, transmitted_ib_unicast.packets);
pma_cnt_ext->port_unicast_rcv_packets =
MLX5_GET64_BE(query_vport_counter_out,
out, received_ib_unicast.packets);
pma_cnt_ext->port_multicast_xmit_packets =
MLX5_GET64_BE(query_vport_counter_out,
out, transmitted_ib_multicast.packets);
pma_cnt_ext->port_multicast_rcv_packets =
MLX5_GET64_BE(query_vport_counter_out,
out, received_ib_multicast.packets);
}
static void pma_cnt_assign(struct ib_pma_portcounters *pma_cnt,
void *out)
{
/* Traffic counters will be reported in
* their 64bit form via ib_pma_portcounters_ext by default.
*/
void *out_pma = MLX5_ADDR_OF(ppcnt_reg, out,
counter_set);
#define MLX5_ASSIGN_PMA_CNTR(counter_var, counter_name) { \
counter_var = MLX5_GET_BE(typeof(counter_var), \
ib_port_cntrs_grp_data_layout, \
out_pma, counter_name); \
}
MLX5_ASSIGN_PMA_CNTR(pma_cnt->symbol_error_counter,
symbol_error_counter);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->link_error_recovery_counter,
link_error_recovery_counter);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->link_downed_counter,
link_downed_counter);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->port_rcv_errors,
port_rcv_errors);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->port_rcv_remphys_errors,
port_rcv_remote_physical_errors);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->port_rcv_switch_relay_errors,
port_rcv_switch_relay_errors);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->port_xmit_discards,
port_xmit_discards);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->port_xmit_constraint_errors,
port_xmit_constraint_errors);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->port_rcv_constraint_errors,
port_rcv_constraint_errors);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->link_overrun_errors,
link_overrun_errors);
MLX5_ASSIGN_PMA_CNTR(pma_cnt->vl15_dropped,
vl_15_dropped);
}
static int process_pma_cmd(struct ib_device *ibdev, u8 port_num,
const struct ib_mad *in_mad, struct ib_mad *out_mad)
{
struct mlx5_ib_dev *dev = to_mdev(ibdev);
int err;
void *out_cnt;
/* Decalring support of extended counters */
if (in_mad->mad_hdr.attr_id == IB_PMA_CLASS_PORT_INFO) {
struct ib_class_port_info cpi = {};
cpi.capability_mask = IB_PMA_CLASS_CAP_EXT_WIDTH;
memcpy((out_mad->data + 40), &cpi, sizeof(cpi));
return IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_REPLY;
}
if (in_mad->mad_hdr.attr_id == IB_PMA_PORT_COUNTERS_EXT) {
struct ib_pma_portcounters_ext *pma_cnt_ext =
(struct ib_pma_portcounters_ext *)(out_mad->data + 40);
int sz = MLX5_ST_SZ_BYTES(query_vport_counter_out);
out_cnt = mlx5_vzalloc(sz);
if (!out_cnt)
return IB_MAD_RESULT_FAILURE;
err = mlx5_core_query_vport_counter(dev->mdev, 0, 0,
port_num, out_cnt, sz);
if (!err)
pma_cnt_ext_assign(pma_cnt_ext, out_cnt);
} else {
struct ib_pma_portcounters *pma_cnt =
(struct ib_pma_portcounters *)(out_mad->data + 40);
int sz = MLX5_ST_SZ_BYTES(ppcnt_reg);
out_cnt = mlx5_vzalloc(sz);
if (!out_cnt)
return IB_MAD_RESULT_FAILURE;
err = mlx5_core_query_ib_ppcnt(dev->mdev, port_num,
out_cnt, sz);
if (!err)
pma_cnt_assign(pma_cnt, out_cnt);
}
kvfree(out_cnt);
if (err)
return IB_MAD_RESULT_FAILURE;
return IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_REPLY;
}
int mlx5_ib_process_mad(struct ib_device *ibdev, int mad_flags, u8 port_num,
const struct ib_wc *in_wc, const struct ib_grh *in_grh,
const struct ib_mad_hdr *in, size_t in_mad_size,
struct ib_mad_hdr *out, size_t *out_mad_size,
u16 *out_mad_pkey_index)
{
struct mlx5_ib_dev *dev = to_mdev(ibdev);
struct mlx5_core_dev *mdev = dev->mdev;
const struct ib_mad *in_mad = (const struct ib_mad *)in;
struct ib_mad *out_mad = (struct ib_mad *)out;
if (WARN_ON_ONCE(in_mad_size != sizeof(*in_mad) ||
*out_mad_size != sizeof(*out_mad)))
return IB_MAD_RESULT_FAILURE;
memset(out_mad->data, 0, sizeof(out_mad->data));
if (MLX5_CAP_GEN(mdev, vport_counters) &&
in_mad->mad_hdr.mgmt_class == IB_MGMT_CLASS_PERF_MGMT &&
in_mad->mad_hdr.method == IB_MGMT_METHOD_GET) {
return process_pma_cmd(ibdev, port_num, in_mad, out_mad);
} else {
return process_mad(ibdev, mad_flags, port_num, in_wc, in_grh,
in_mad, out_mad);
}
}
int mlx5_query_ext_port_caps(struct mlx5_ib_dev *dev, u8 port)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
u16 packet_error;
in_mad = kzalloc(sizeof(*in_mad), GFP_KERNEL);
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = MLX5_ATTR_EXTENDED_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
err = mlx5_MAD_IFC(dev, 1, 1, 1, NULL, NULL, in_mad, out_mad);
packet_error = be16_to_cpu(out_mad->status);
dev->mdev->port_caps[port - 1].ext_port_cap = (!err && !packet_error) ?
MLX_EXT_PORT_CAP_FLAG_EXTENDED_PORT_INFO : 0;
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_smp_attr_node_info(struct ib_device *ibdev,
struct ib_smp *out_mad)
{
struct ib_smp *in_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof(*in_mad), GFP_KERNEL);
if (!in_mad)
return -ENOMEM;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_NODE_INFO;
err = mlx5_MAD_IFC(to_mdev(ibdev), 1, 1, 1, NULL, NULL, in_mad,
out_mad);
kfree(in_mad);
return err;
}
int mlx5_query_mad_ifc_system_image_guid(struct ib_device *ibdev,
__be64 *sys_image_guid)
{
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!out_mad)
return -ENOMEM;
err = mlx5_query_mad_ifc_smp_attr_node_info(ibdev, out_mad);
if (err)
goto out;
memcpy(sys_image_guid, out_mad->data + 4, 8);
out:
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_max_pkeys(struct ib_device *ibdev,
u16 *max_pkeys)
{
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!out_mad)
return -ENOMEM;
err = mlx5_query_mad_ifc_smp_attr_node_info(ibdev, out_mad);
if (err)
goto out;
*max_pkeys = be16_to_cpup((__be16 *)(out_mad->data + 28));
out:
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_vendor_id(struct ib_device *ibdev,
u32 *vendor_id)
{
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!out_mad)
return -ENOMEM;
err = mlx5_query_mad_ifc_smp_attr_node_info(ibdev, out_mad);
if (err)
goto out;
*vendor_id = be32_to_cpup((__be32 *)(out_mad->data + 36)) & 0xffff;
out:
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_node_desc(struct mlx5_ib_dev *dev, char *node_desc)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof(*in_mad), GFP_KERNEL);
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_NODE_DESC;
err = mlx5_MAD_IFC(dev, 1, 1, 1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(node_desc, out_mad->data, 64);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_node_guid(struct mlx5_ib_dev *dev, __be64 *node_guid)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof(*in_mad), GFP_KERNEL);
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_NODE_INFO;
err = mlx5_MAD_IFC(dev, 1, 1, 1, NULL, NULL, in_mad, out_mad);
if (err)
goto out;
memcpy(node_guid, out_mad->data + 12, 8);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_pkey(struct ib_device *ibdev, u8 port, u16 index,
u16 *pkey)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof(*in_mad), GFP_KERNEL);
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PKEY_TABLE;
in_mad->attr_mod = cpu_to_be32(index / 32);
err = mlx5_MAD_IFC(to_mdev(ibdev), 1, 1, port, NULL, NULL, in_mad,
out_mad);
if (err)
goto out;
*pkey = be16_to_cpu(((__be16 *)out_mad->data)[index % 32]);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_gids(struct ib_device *ibdev, u8 port, int index,
union ib_gid *gid)
{
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int err = -ENOMEM;
in_mad = kzalloc(sizeof(*in_mad), GFP_KERNEL);
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
err = mlx5_MAD_IFC(to_mdev(ibdev), 1, 1, port, NULL, NULL, in_mad,
out_mad);
if (err)
goto out;
memcpy(gid->raw, out_mad->data + 8, 8);
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_GUID_INFO;
in_mad->attr_mod = cpu_to_be32(index / 8);
err = mlx5_MAD_IFC(to_mdev(ibdev), 1, 1, port, NULL, NULL, in_mad,
out_mad);
if (err)
goto out;
memcpy(gid->raw + 8, out_mad->data + (index % 8) * 8, 8);
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
int mlx5_query_mad_ifc_port(struct ib_device *ibdev, u8 port,
struct ib_port_attr *props)
{
struct mlx5_ib_dev *dev = to_mdev(ibdev);
struct mlx5_core_dev *mdev = dev->mdev;
struct ib_smp *in_mad = NULL;
struct ib_smp *out_mad = NULL;
int ext_active_speed;
int err = -ENOMEM;
if (port < 1 || port > MLX5_CAP_GEN(mdev, num_ports)) {
mlx5_ib_warn(dev, "invalid port number %d\n", port);
return -EINVAL;
}
in_mad = kzalloc(sizeof(*in_mad), GFP_KERNEL);
out_mad = kmalloc(sizeof(*out_mad), GFP_KERNEL);
if (!in_mad || !out_mad)
goto out;
memset(props, 0, sizeof(*props));
init_query_mad(in_mad);
in_mad->attr_id = IB_SMP_ATTR_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
err = mlx5_MAD_IFC(dev, 1, 1, port, NULL, NULL, in_mad, out_mad);
if (err) {
mlx5_ib_warn(dev, "err %d\n", err);
goto out;
}
props->lid = be16_to_cpup((__be16 *)(out_mad->data + 16));
props->lmc = out_mad->data[34] & 0x7;
props->sm_lid = be16_to_cpup((__be16 *)(out_mad->data + 18));
props->sm_sl = out_mad->data[36] & 0xf;
props->state = out_mad->data[32] & 0xf;
props->phys_state = out_mad->data[33] >> 4;
props->port_cap_flags = be32_to_cpup((__be32 *)(out_mad->data + 20));
props->gid_tbl_len = out_mad->data[50];
props->max_msg_sz = 1 << MLX5_CAP_GEN(mdev, log_max_msg);
props->pkey_tbl_len = mdev->port_caps[port - 1].pkey_table_len;
props->bad_pkey_cntr = be16_to_cpup((__be16 *)(out_mad->data + 46));
props->qkey_viol_cntr = be16_to_cpup((__be16 *)(out_mad->data + 48));
props->active_width = out_mad->data[31] & 0xf;
props->active_speed = out_mad->data[35] >> 4;
props->max_mtu = out_mad->data[41] & 0xf;
props->active_mtu = out_mad->data[36] >> 4;
props->subnet_timeout = out_mad->data[51] & 0x1f;
props->max_vl_num = out_mad->data[37] >> 4;
props->init_type_reply = out_mad->data[41] >> 4;
/* Check if extended speeds (EDR/FDR/...) are supported */
if (props->port_cap_flags & IB_PORT_EXTENDED_SPEEDS_SUP) {
ext_active_speed = out_mad->data[62] >> 4;
switch (ext_active_speed) {
case 1:
props->active_speed = 16; /* FDR */
break;
case 2:
props->active_speed = 32; /* EDR */
break;
}
}
/* If reported active speed is QDR, check if is FDR-10 */
if (props->active_speed == 4) {
if (mdev->port_caps[port - 1].ext_port_cap &
MLX_EXT_PORT_CAP_FLAG_EXTENDED_PORT_INFO) {
init_query_mad(in_mad);
in_mad->attr_id = MLX5_ATTR_EXTENDED_PORT_INFO;
in_mad->attr_mod = cpu_to_be32(port);
err = mlx5_MAD_IFC(dev, 1, 1, port,
NULL, NULL, in_mad, out_mad);
if (err)
goto out;
/* Checking LinkSpeedActive for FDR-10 */
if (out_mad->data[15] & 0x1)
props->active_speed = 8;
}
}
out:
kfree(in_mad);
kfree(out_mad);
return err;
}
| geminy/aidear | oss/linux/linux-4.7/drivers/infiniband/hw/mlx5/mad.c | C | gpl-3.0 | 16,987 |
// "Create class 'MyCollection'" "true"
import java.util.*;
public class Test {
public static void main() {
Collection c = new MyCollection(1, "test");
}
}
public class MyCollection implements Collection {
public MyCollection(int i, String test) {<caret>
}
} | asedunov/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/after1.java | Java | apache-2.0 | 284 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.dom.model.presentation;
import com.intellij.ide.presentation.PresentationProvider;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.dom.model.MavenDomRepository;
/**
*
*/
public class MavenDomRepositoryPresentationProvider extends PresentationProvider<MavenDomRepository> {
@Nullable
@Override
public String getName(MavenDomRepository mavenDomRepository) {
return "Repository (id=" + mavenDomRepository.getId().getStringValue()
+ ", url=" + mavenDomRepository.getUrl().getStringValue()
+ ')';
}
}
| idea4bsd/idea4bsd | plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/presentation/MavenDomRepositoryPresentationProvider.java | Java | apache-2.0 | 1,195 |
<?php
namespace Gedmo\Mapping;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Common\EventManager;
use Doctrine\ORM\Mapping\Driver\DriverChain;
use Doctrine\ORM\Mapping\Driver\YamlDriver;
use Gedmo\SoftDeleteable\SoftDeleteableListener;
use Tool\BaseTestCaseOM;
/**
* These are mapping tests for SoftDeleteable extension
*
* @author Gustavo Falco <[email protected]>
* @author Gediminas Morkevicius <[email protected]>
* @link http://www.gediminasm.org
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class SoftDeleteableMappingTest extends BaseTestCaseOM
{
/**
* @var Doctrine\ORM\EntityManager
*/
private $em;
/**
* @var Gedmo\SoftDeleteable\SoftDeleteableListener
*/
private $softDeleteable;
public function setUp()
{
parent::setUp();
$reader = new AnnotationReader();
$annotationDriver = new AnnotationDriver($reader);
$yamlDriver = new YamlDriver(__DIR__.'/Driver/Yaml');
$chain = new DriverChain();
$chain->addDriver($yamlDriver, 'Mapping\Fixture\Yaml');
$chain->addDriver($annotationDriver, 'Mapping\Fixture');
$this->softDeleteable = new SoftDeleteableListener();
$this->evm = new EventManager();
$this->evm->addEventSubscriber($this->softDeleteable);
$this->em = $this->getMockSqliteEntityManager(array(
'Mapping\Fixture\Yaml\SoftDeleteable',
'Mapping\Fixture\SoftDeleteable',
), $chain);
}
public function testYamlMapping()
{
$meta = $this->em->getClassMetadata('Mapping\Fixture\Yaml\SoftDeleteable');
$config = $this->softDeleteable->getConfiguration($this->em, $meta->name);
$this->assertArrayHasKey('softDeleteable', $config);
$this->assertTrue($config['softDeleteable']);
$this->assertArrayHasKey('timeAware', $config);
$this->assertFalse($config['timeAware']);
$this->assertArrayHasKey('fieldName', $config);
$this->assertEquals('deletedAt', $config['fieldName']);
}
}
| bantudevelopment/smis | vendor/gedmo1/doctrine-extensions/tests/Gedmo/Mapping/SoftDeleteableMappingTest.php | PHP | bsd-3-clause | 2,168 |
package spdystream
import (
"errors"
"fmt"
"io"
"net"
"net/http"
"sync"
"time"
"github.com/docker/spdystream/spdy"
)
var (
ErrUnreadPartialData = errors.New("unread partial data")
)
type Stream struct {
streamId spdy.StreamId
parent *Stream
conn *Connection
startChan chan error
dataLock sync.RWMutex
dataChan chan []byte
unread []byte
priority uint8
headers http.Header
headerChan chan http.Header
finishLock sync.Mutex
finished bool
replyCond *sync.Cond
replied bool
closeLock sync.Mutex
closeChan chan bool
}
// WriteData writes data to stream, sending a dataframe per call
func (s *Stream) WriteData(data []byte, fin bool) error {
s.waitWriteReply()
var flags spdy.DataFlags
if fin {
flags = spdy.DataFlagFin
s.finishLock.Lock()
if s.finished {
s.finishLock.Unlock()
return ErrWriteClosedStream
}
s.finished = true
s.finishLock.Unlock()
}
dataFrame := &spdy.DataFrame{
StreamId: s.streamId,
Flags: flags,
Data: data,
}
debugMessage("(%p) (%d) Writing data frame", s, s.streamId)
return s.conn.framer.WriteFrame(dataFrame)
}
// Write writes bytes to a stream, calling write data for each call.
func (s *Stream) Write(data []byte) (n int, err error) {
err = s.WriteData(data, false)
if err == nil {
n = len(data)
}
return
}
// Read reads bytes from a stream, a single read will never get more
// than what is sent on a single data frame, but a multiple calls to
// read may get data from the same data frame.
func (s *Stream) Read(p []byte) (n int, err error) {
if s.unread == nil {
select {
case <-s.closeChan:
return 0, io.EOF
case read, ok := <-s.dataChan:
if !ok {
return 0, io.EOF
}
s.unread = read
}
}
n = copy(p, s.unread)
if n < len(s.unread) {
s.unread = s.unread[n:]
} else {
s.unread = nil
}
return
}
// ReadData reads an entire data frame and returns the byte array
// from the data frame. If there is unread data from the result
// of a Read call, this function will return an ErrUnreadPartialData.
func (s *Stream) ReadData() ([]byte, error) {
debugMessage("(%p) Reading data from %d", s, s.streamId)
if s.unread != nil {
return nil, ErrUnreadPartialData
}
select {
case <-s.closeChan:
return nil, io.EOF
case read, ok := <-s.dataChan:
if !ok {
return nil, io.EOF
}
return read, nil
}
}
func (s *Stream) waitWriteReply() {
if s.replyCond != nil {
s.replyCond.L.Lock()
for !s.replied {
s.replyCond.Wait()
}
s.replyCond.L.Unlock()
}
}
// Wait waits for the stream to receive a reply.
func (s *Stream) Wait() error {
return s.WaitTimeout(time.Duration(0))
}
// WaitTimeout waits for the stream to receive a reply or for timeout.
// When the timeout is reached, ErrTimeout will be returned.
func (s *Stream) WaitTimeout(timeout time.Duration) error {
var timeoutChan <-chan time.Time
if timeout > time.Duration(0) {
timeoutChan = time.After(timeout)
}
select {
case err := <-s.startChan:
if err != nil {
return err
}
break
case <-timeoutChan:
return ErrTimeout
}
return nil
}
// Close closes the stream by sending an empty data frame with the
// finish flag set, indicating this side is finished with the stream.
func (s *Stream) Close() error {
select {
case <-s.closeChan:
// Stream is now fully closed
s.conn.removeStream(s)
default:
break
}
return s.WriteData([]byte{}, true)
}
// Reset sends a reset frame, putting the stream into the fully closed state.
func (s *Stream) Reset() error {
s.conn.removeStream(s)
return s.resetStream()
}
func (s *Stream) resetStream() error {
s.finishLock.Lock()
if s.finished {
s.finishLock.Unlock()
return nil
}
s.finished = true
s.finishLock.Unlock()
s.closeRemoteChannels()
resetFrame := &spdy.RstStreamFrame{
StreamId: s.streamId,
Status: spdy.Cancel,
}
return s.conn.framer.WriteFrame(resetFrame)
}
// CreateSubStream creates a stream using the current as the parent
func (s *Stream) CreateSubStream(headers http.Header, fin bool) (*Stream, error) {
return s.conn.CreateStream(headers, s, fin)
}
// SetPriority sets the stream priority, does not affect the
// remote priority of this stream after Open has been called.
// Valid values are 0 through 7, 0 being the highest priority
// and 7 the lowest.
func (s *Stream) SetPriority(priority uint8) {
s.priority = priority
}
// SendHeader sends a header frame across the stream
func (s *Stream) SendHeader(headers http.Header, fin bool) error {
return s.conn.sendHeaders(headers, s, fin)
}
// SendReply sends a reply on a stream, only valid to be called once
// when handling a new stream
func (s *Stream) SendReply(headers http.Header, fin bool) error {
if s.replyCond == nil {
return errors.New("cannot reply on initiated stream")
}
s.replyCond.L.Lock()
defer s.replyCond.L.Unlock()
if s.replied {
return nil
}
err := s.conn.sendReply(headers, s, fin)
if err != nil {
return err
}
s.replied = true
s.replyCond.Broadcast()
return nil
}
// Refuse sends a reset frame with the status refuse, only
// valid to be called once when handling a new stream. This
// may be used to indicate that a stream is not allowed
// when http status codes are not being used.
func (s *Stream) Refuse() error {
if s.replied {
return nil
}
s.replied = true
return s.conn.sendReset(spdy.RefusedStream, s)
}
// Cancel sends a reset frame with the status canceled. This
// can be used at any time by the creator of the Stream to
// indicate the stream is no longer needed.
func (s *Stream) Cancel() error {
return s.conn.sendReset(spdy.Cancel, s)
}
// ReceiveHeader receives a header sent on the other side
// of the stream. This function will block until a header
// is received or stream is closed.
func (s *Stream) ReceiveHeader() (http.Header, error) {
select {
case <-s.closeChan:
break
case header, ok := <-s.headerChan:
if !ok {
return nil, fmt.Errorf("header chan closed")
}
return header, nil
}
return nil, fmt.Errorf("stream closed")
}
// Parent returns the parent stream
func (s *Stream) Parent() *Stream {
return s.parent
}
// Headers returns the headers used to create the stream
func (s *Stream) Headers() http.Header {
return s.headers
}
// String returns the string version of stream using the
// streamId to uniquely identify the stream
func (s *Stream) String() string {
return fmt.Sprintf("stream:%d", s.streamId)
}
// Identifier returns a 32 bit identifier for the stream
func (s *Stream) Identifier() uint32 {
return uint32(s.streamId)
}
// IsFinished returns whether the stream has finished
// sending data
func (s *Stream) IsFinished() bool {
return s.finished
}
// Implement net.Conn interface
func (s *Stream) LocalAddr() net.Addr {
return s.conn.conn.LocalAddr()
}
func (s *Stream) RemoteAddr() net.Addr {
return s.conn.conn.RemoteAddr()
}
// TODO set per stream values instead of connection-wide
func (s *Stream) SetDeadline(t time.Time) error {
return s.conn.conn.SetDeadline(t)
}
func (s *Stream) SetReadDeadline(t time.Time) error {
return s.conn.conn.SetReadDeadline(t)
}
func (s *Stream) SetWriteDeadline(t time.Time) error {
return s.conn.conn.SetWriteDeadline(t)
}
func (s *Stream) closeRemoteChannels() {
s.closeLock.Lock()
defer s.closeLock.Unlock()
select {
case <-s.closeChan:
default:
close(s.closeChan)
s.dataLock.Lock()
defer s.dataLock.Unlock()
close(s.dataChan)
}
}
| jbenet/spdystream | stream.go | GO | apache-2.0 | 7,420 |
CKEDITOR.plugins.setLang("font","fi",{fontSize:{label:"Koko",voiceLabel:"Kirjaisimen koko",panelTitle:"Koko"},label:"Kirjaisinlaji",panelTitle:"Kirjaisinlaji",voiceLabel:"Kirjaisinlaji"}); | orbiten-pradeep/chesmile | webroot/dashboard/plugins/ckeditor/plugins/font/lang/fi.js | JavaScript | mit | 188 |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* Authors:
* Inki Dae <[email protected]>
* Joonyoung Shim <[email protected]>
* Seung-Woo Kim <[email protected]>
*/
#include <linux/component.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/uaccess.h>
#include <drm/drm_atomic.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_drv.h>
#include <drm/drm_fb_helper.h>
#include <drm/drm_file.h>
#include <drm/drm_fourcc.h>
#include <drm/drm_ioctl.h>
#include <drm/drm_probe_helper.h>
#include <drm/drm_vblank.h>
#include <drm/exynos_drm.h>
#include "exynos_drm_drv.h"
#include "exynos_drm_fb.h"
#include "exynos_drm_fbdev.h"
#include "exynos_drm_g2d.h"
#include "exynos_drm_gem.h"
#include "exynos_drm_ipp.h"
#include "exynos_drm_plane.h"
#include "exynos_drm_vidi.h"
#define DRIVER_NAME "exynos"
#define DRIVER_DESC "Samsung SoC DRM"
#define DRIVER_DATE "20180330"
/*
* Interface history:
*
* 1.0 - Original version
* 1.1 - Upgrade IPP driver to version 2.0
*/
#define DRIVER_MAJOR 1
#define DRIVER_MINOR 1
static int exynos_drm_open(struct drm_device *dev, struct drm_file *file)
{
struct drm_exynos_file_private *file_priv;
int ret;
file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
if (!file_priv)
return -ENOMEM;
file->driver_priv = file_priv;
ret = g2d_open(dev, file);
if (ret)
goto err_file_priv_free;
return ret;
err_file_priv_free:
kfree(file_priv);
file->driver_priv = NULL;
return ret;
}
static void exynos_drm_postclose(struct drm_device *dev, struct drm_file *file)
{
g2d_close(dev, file);
kfree(file->driver_priv);
file->driver_priv = NULL;
}
static const struct drm_ioctl_desc exynos_ioctls[] = {
DRM_IOCTL_DEF_DRV(EXYNOS_GEM_CREATE, exynos_drm_gem_create_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_GEM_MAP, exynos_drm_gem_map_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_GEM_GET, exynos_drm_gem_get_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_VIDI_CONNECTION, vidi_connection_ioctl,
DRM_AUTH),
DRM_IOCTL_DEF_DRV(EXYNOS_G2D_GET_VER, exynos_g2d_get_ver_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_G2D_SET_CMDLIST, exynos_g2d_set_cmdlist_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_G2D_EXEC, exynos_g2d_exec_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_IPP_GET_RESOURCES,
exynos_drm_ipp_get_res_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_IPP_GET_CAPS, exynos_drm_ipp_get_caps_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_IPP_GET_LIMITS,
exynos_drm_ipp_get_limits_ioctl,
DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(EXYNOS_IPP_COMMIT, exynos_drm_ipp_commit_ioctl,
DRM_RENDER_ALLOW),
};
static const struct file_operations exynos_drm_driver_fops = {
.owner = THIS_MODULE,
.open = drm_open,
.mmap = exynos_drm_gem_mmap,
.poll = drm_poll,
.read = drm_read,
.unlocked_ioctl = drm_ioctl,
.compat_ioctl = drm_compat_ioctl,
.release = drm_release,
};
static const struct drm_driver exynos_drm_driver = {
.driver_features = DRIVER_MODESET | DRIVER_GEM
| DRIVER_ATOMIC | DRIVER_RENDER,
.open = exynos_drm_open,
.lastclose = drm_fb_helper_lastclose,
.postclose = exynos_drm_postclose,
.dumb_create = exynos_drm_gem_dumb_create,
.prime_handle_to_fd = drm_gem_prime_handle_to_fd,
.prime_fd_to_handle = drm_gem_prime_fd_to_handle,
.gem_prime_import = exynos_drm_gem_prime_import,
.gem_prime_import_sg_table = exynos_drm_gem_prime_import_sg_table,
.gem_prime_mmap = exynos_drm_gem_prime_mmap,
.ioctls = exynos_ioctls,
.num_ioctls = ARRAY_SIZE(exynos_ioctls),
.fops = &exynos_drm_driver_fops,
.name = DRIVER_NAME,
.desc = DRIVER_DESC,
.date = DRIVER_DATE,
.major = DRIVER_MAJOR,
.minor = DRIVER_MINOR,
};
static int exynos_drm_suspend(struct device *dev)
{
struct drm_device *drm_dev = dev_get_drvdata(dev);
return drm_mode_config_helper_suspend(drm_dev);
}
static void exynos_drm_resume(struct device *dev)
{
struct drm_device *drm_dev = dev_get_drvdata(dev);
drm_mode_config_helper_resume(drm_dev);
}
static const struct dev_pm_ops exynos_drm_pm_ops = {
.prepare = exynos_drm_suspend,
.complete = exynos_drm_resume,
};
/* forward declaration */
static struct platform_driver exynos_drm_platform_driver;
struct exynos_drm_driver_info {
struct platform_driver *driver;
unsigned int flags;
};
#define DRM_COMPONENT_DRIVER BIT(0) /* supports component framework */
#define DRM_VIRTUAL_DEVICE BIT(1) /* create virtual platform device */
#define DRM_FIMC_DEVICE BIT(2) /* devices shared with V4L2 subsystem */
#define DRV_PTR(drv, cond) (IS_ENABLED(cond) ? &drv : NULL)
/*
* Connector drivers should not be placed before associated crtc drivers,
* because connector requires pipe number of its crtc during initialization.
*/
static struct exynos_drm_driver_info exynos_drm_drivers[] = {
{
DRV_PTR(fimd_driver, CONFIG_DRM_EXYNOS_FIMD),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(exynos5433_decon_driver, CONFIG_DRM_EXYNOS5433_DECON),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(decon_driver, CONFIG_DRM_EXYNOS7_DECON),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(mixer_driver, CONFIG_DRM_EXYNOS_MIXER),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(mic_driver, CONFIG_DRM_EXYNOS_MIC),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(dp_driver, CONFIG_DRM_EXYNOS_DP),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(dsi_driver, CONFIG_DRM_EXYNOS_DSI),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(hdmi_driver, CONFIG_DRM_EXYNOS_HDMI),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(vidi_driver, CONFIG_DRM_EXYNOS_VIDI),
DRM_COMPONENT_DRIVER | DRM_VIRTUAL_DEVICE
}, {
DRV_PTR(g2d_driver, CONFIG_DRM_EXYNOS_G2D),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(fimc_driver, CONFIG_DRM_EXYNOS_FIMC),
DRM_COMPONENT_DRIVER | DRM_FIMC_DEVICE,
}, {
DRV_PTR(rotator_driver, CONFIG_DRM_EXYNOS_ROTATOR),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(scaler_driver, CONFIG_DRM_EXYNOS_SCALER),
DRM_COMPONENT_DRIVER
}, {
DRV_PTR(gsc_driver, CONFIG_DRM_EXYNOS_GSC),
DRM_COMPONENT_DRIVER
}, {
&exynos_drm_platform_driver,
DRM_VIRTUAL_DEVICE
}
};
static int compare_dev(struct device *dev, void *data)
{
return dev == (struct device *)data;
}
static struct component_match *exynos_drm_match_add(struct device *dev)
{
struct component_match *match = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(exynos_drm_drivers); ++i) {
struct exynos_drm_driver_info *info = &exynos_drm_drivers[i];
struct device *p = NULL, *d;
if (!info->driver || !(info->flags & DRM_COMPONENT_DRIVER))
continue;
while ((d = platform_find_device_by_driver(p, &info->driver->driver))) {
put_device(p);
if (!(info->flags & DRM_FIMC_DEVICE) ||
exynos_drm_check_fimc_device(d) == 0)
component_match_add(dev, &match,
compare_dev, d);
p = d;
}
put_device(p);
}
return match ?: ERR_PTR(-ENODEV);
}
static int exynos_drm_bind(struct device *dev)
{
struct exynos_drm_private *private;
struct drm_encoder *encoder;
struct drm_device *drm;
unsigned int clone_mask;
int ret;
drm = drm_dev_alloc(&exynos_drm_driver, dev);
if (IS_ERR(drm))
return PTR_ERR(drm);
private = kzalloc(sizeof(struct exynos_drm_private), GFP_KERNEL);
if (!private) {
ret = -ENOMEM;
goto err_free_drm;
}
init_waitqueue_head(&private->wait);
spin_lock_init(&private->lock);
dev_set_drvdata(dev, drm);
drm->dev_private = (void *)private;
drm_mode_config_init(drm);
exynos_drm_mode_config_init(drm);
/* setup possible_clones. */
clone_mask = 0;
list_for_each_entry(encoder, &drm->mode_config.encoder_list, head)
clone_mask |= drm_encoder_mask(encoder);
list_for_each_entry(encoder, &drm->mode_config.encoder_list, head)
encoder->possible_clones = clone_mask;
/* Try to bind all sub drivers. */
ret = component_bind_all(drm->dev, drm);
if (ret)
goto err_mode_config_cleanup;
ret = drm_vblank_init(drm, drm->mode_config.num_crtc);
if (ret)
goto err_unbind_all;
drm_mode_config_reset(drm);
/*
* enable drm irq mode.
* - with irq_enabled = true, we can use the vblank feature.
*
* P.S. note that we wouldn't use drm irq handler but
* just specific driver own one instead because
* drm framework supports only one irq handler.
*/
drm->irq_enabled = true;
/* init kms poll for handling hpd */
drm_kms_helper_poll_init(drm);
ret = exynos_drm_fbdev_init(drm);
if (ret)
goto err_cleanup_poll;
/* register the DRM device */
ret = drm_dev_register(drm, 0);
if (ret < 0)
goto err_cleanup_fbdev;
return 0;
err_cleanup_fbdev:
exynos_drm_fbdev_fini(drm);
err_cleanup_poll:
drm_kms_helper_poll_fini(drm);
err_unbind_all:
component_unbind_all(drm->dev, drm);
err_mode_config_cleanup:
drm_mode_config_cleanup(drm);
exynos_drm_cleanup_dma(drm);
kfree(private);
err_free_drm:
drm_dev_put(drm);
return ret;
}
static void exynos_drm_unbind(struct device *dev)
{
struct drm_device *drm = dev_get_drvdata(dev);
drm_dev_unregister(drm);
exynos_drm_fbdev_fini(drm);
drm_kms_helper_poll_fini(drm);
component_unbind_all(drm->dev, drm);
drm_mode_config_cleanup(drm);
exynos_drm_cleanup_dma(drm);
kfree(drm->dev_private);
drm->dev_private = NULL;
dev_set_drvdata(dev, NULL);
drm_dev_put(drm);
}
static const struct component_master_ops exynos_drm_ops = {
.bind = exynos_drm_bind,
.unbind = exynos_drm_unbind,
};
static int exynos_drm_platform_probe(struct platform_device *pdev)
{
struct component_match *match;
pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32);
match = exynos_drm_match_add(&pdev->dev);
if (IS_ERR(match))
return PTR_ERR(match);
return component_master_add_with_match(&pdev->dev, &exynos_drm_ops,
match);
}
static int exynos_drm_platform_remove(struct platform_device *pdev)
{
component_master_del(&pdev->dev, &exynos_drm_ops);
return 0;
}
static struct platform_driver exynos_drm_platform_driver = {
.probe = exynos_drm_platform_probe,
.remove = exynos_drm_platform_remove,
.driver = {
.name = "exynos-drm",
.pm = &exynos_drm_pm_ops,
},
};
static void exynos_drm_unregister_devices(void)
{
int i;
for (i = ARRAY_SIZE(exynos_drm_drivers) - 1; i >= 0; --i) {
struct exynos_drm_driver_info *info = &exynos_drm_drivers[i];
struct device *dev;
if (!info->driver || !(info->flags & DRM_VIRTUAL_DEVICE))
continue;
while ((dev = platform_find_device_by_driver(NULL,
&info->driver->driver))) {
put_device(dev);
platform_device_unregister(to_platform_device(dev));
}
}
}
static int exynos_drm_register_devices(void)
{
struct platform_device *pdev;
int i;
for (i = 0; i < ARRAY_SIZE(exynos_drm_drivers); ++i) {
struct exynos_drm_driver_info *info = &exynos_drm_drivers[i];
if (!info->driver || !(info->flags & DRM_VIRTUAL_DEVICE))
continue;
pdev = platform_device_register_simple(
info->driver->driver.name, -1, NULL, 0);
if (IS_ERR(pdev))
goto fail;
}
return 0;
fail:
exynos_drm_unregister_devices();
return PTR_ERR(pdev);
}
static void exynos_drm_unregister_drivers(void)
{
int i;
for (i = ARRAY_SIZE(exynos_drm_drivers) - 1; i >= 0; --i) {
struct exynos_drm_driver_info *info = &exynos_drm_drivers[i];
if (!info->driver)
continue;
platform_driver_unregister(info->driver);
}
}
static int exynos_drm_register_drivers(void)
{
int i, ret;
for (i = 0; i < ARRAY_SIZE(exynos_drm_drivers); ++i) {
struct exynos_drm_driver_info *info = &exynos_drm_drivers[i];
if (!info->driver)
continue;
ret = platform_driver_register(info->driver);
if (ret)
goto fail;
}
return 0;
fail:
exynos_drm_unregister_drivers();
return ret;
}
static int exynos_drm_init(void)
{
int ret;
ret = exynos_drm_register_devices();
if (ret)
return ret;
ret = exynos_drm_register_drivers();
if (ret)
goto err_unregister_pdevs;
return 0;
err_unregister_pdevs:
exynos_drm_unregister_devices();
return ret;
}
static void exynos_drm_exit(void)
{
exynos_drm_unregister_drivers();
exynos_drm_unregister_devices();
}
module_init(exynos_drm_init);
module_exit(exynos_drm_exit);
MODULE_AUTHOR("Inki Dae <[email protected]>");
MODULE_AUTHOR("Joonyoung Shim <[email protected]>");
MODULE_AUTHOR("Seung-Woo Kim <[email protected]>");
MODULE_DESCRIPTION("Samsung SoC DRM Driver");
MODULE_LICENSE("GPL");
| Broadcom/linux-rdma-nxt | drivers/gpu/drm/exynos/exynos_drm_drv.c | C | gpl-2.0 | 12,283 |
package com.siyeh.igfixes.numeric.unpredictable_big_decimal;
import java.math.BigDecimal;
class Factory {
void foo(double val) {
BigDecimal bd = BigDecimal.valueOf(val);
}
} | asedunov/intellij-community | plugins/InspectionGadgets/test/com/siyeh/igfixes/numeric/unpredictable_big_decimal/Factory.after.java | Java | apache-2.0 | 183 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
return array(
'code' => '593',
'patterns' => array(
'national' => array(
'general' => '/^1\\d{9,10}|[2-8]\\d{7}|9\\d{8}$/',
'fixed' => '/^[2-7][2-7]\\d{6}$/',
'mobile' => '/^9(?:[2-7]9|[89]\\d)\\d{6}$/',
'tollfree' => '/^1800\\d{6,7}$/',
'voip' => '/^[2-7]890\\d{4}$/',
'emergency' => '/^1(?:0[12]|12)|911$/',
),
'possible' => array(
'general' => '/^\\d{7,11}$/',
'fixed' => '/^\\d{7,8}$/',
'mobile' => '/^\\d{9}$/',
'tollfree' => '/^\\d{10,11}$/',
'voip' => '/^\\d{8}$/',
'emergency' => '/^\\d{3}$/',
),
),
);
| pdhwi/hwi_test | z/ZendFramework-2.4.3/library/Zend/I18n/Validator/PhoneNumber/EC.php | PHP | bsd-3-clause | 1,009 |
/******************************************************************************
*
* (C)Copyright 1998,1999 SysKonnect,
* a business unit of Schneider & Koch & Co. Datensysteme GmbH.
*
* 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.
*
* The information in this file is provided "AS IS" without warranty.
*
******************************************************************************/
/*
* Synchronous Bandwidth Allocation (SBA) structs
*/
#ifndef _SBA_
#define _SBA_
#include "mbuf.h"
#include "sba_def.h"
#ifdef SBA
/* Timer Cell Template */
struct timer_cell {
struct timer_cell *next_ptr ;
struct timer_cell *prev_ptr ;
u_long start_time ;
struct s_sba_node_vars *node_var ;
} ;
/*
* Node variables
*/
struct s_sba_node_vars {
u_char change_resp_flag ;
u_char report_resp_flag ;
u_char change_req_flag ;
u_char report_req_flag ;
long change_amount ;
long node_overhead ;
long node_payload ;
u_long node_status ;
u_char deallocate_status ;
u_char timer_state ;
u_short report_cnt ;
long lastrep_req_tranid ;
struct fddi_addr mac_address ;
struct s_sba_sessions *node_sessions ;
struct timer_cell timer ;
} ;
/*
* Session variables
*/
struct s_sba_sessions {
u_long deallocate_status ;
long session_overhead ;
u_long min_segment_size ;
long session_payload ;
u_long session_status ;
u_long sba_category ;
long lastchg_req_tranid ;
u_short session_id ;
u_char class ;
u_char fddi2 ;
u_long max_t_neg ;
struct s_sba_sessions *next_session ;
} ;
struct s_sba {
struct s_sba_node_vars node[MAX_NODES] ;
struct s_sba_sessions session[MAX_SESSIONS] ;
struct s_sba_sessions *free_session ; /* points to the first */
/* free session */
struct timer_cell *tail_timer ; /* points to the last timer cell */
/*
* variables for allocation actions
*/
long total_payload ; /* Total Payload */
long total_overhead ; /* Total Overhead */
long sba_allocatable ; /* allocatable sync bandwidth */
/*
* RAF message receive parameters
*/
long msg_path_index ; /* Path Type */
long msg_sba_pl_req ; /* Payload Request */
long msg_sba_ov_req ; /* Overhead Request */
long msg_mib_pl ; /* Current Payload for this Path */
long msg_mib_ov ; /* Current Overhead for this Path*/
long msg_category ; /* Category of the Allocation */
u_long msg_max_t_neg ; /* longest T_Neg acceptable */
u_long msg_min_seg_siz ; /* minimum segement size */
struct smt_header *sm ; /* points to the rec message */
struct fddi_addr *msg_alloc_addr ; /* Allocation Address */
/*
* SBA variables
*/
u_long sba_t_neg ; /* holds the last T_NEG */
long sba_max_alloc ; /* the parsed value of SBAAvailable */
/*
* SBA state machine variables
*/
short sba_next_state ; /* the next state of the SBA */
char sba_command ; /* holds the execuded SBA cmd */
u_char sba_available ; /* parsed value after possible check */
} ;
#endif /* SBA */
/*
* variables for the End Station Support
*/
struct s_ess {
/*
* flags and counters
*/
u_char sync_bw_available ; /* is set if sync bw is allocated */
u_char local_sba_active ; /* set when a local sba is available */
char raf_act_timer_poll ; /* activate the timer to send allc req */
char timer_count ; /* counts every timer function call */
SMbuf *sba_reply_pend ; /* local reply for the sba is pending */
/*
* variables for the ess bandwidth control
*/
long sync_bw ; /* holds the allocaed sync bw */
u_long alloc_trans_id ; /* trans id of the last alloc req */
} ;
#endif
| AiJiaZone/linux-4.0 | virt/drivers/net/fddi/skfp/h/sba.h | C | gpl-2.0 | 3,772 |
package org.apache.commons.jrcs.diff;
import org.apache.commons.jrcs.diff.myers.MyersDiff;
public class MyersDiffTests extends DiffTest {
public MyersDiffTests(String name) {
super(name, new MyersDiff());
}
}
| ouit0408/sakai | rwiki/rwiki-util/jrcs/src/completetest/org/apache/commons/jrcs/diff/MyersDiffTests.java | Java | apache-2.0 | 230 |
/*
* Freescale QUICC Engine USB Host Controller Driver
*
* Copyright (c) Freescale Semicondutor, Inc. 2006, 2011.
* Shlomi Gridish <[email protected]>
* Jerry Huang <[email protected]>
* Copyright (c) Logic Product Development, Inc. 2007
* Peter Barada <[email protected]>
* Copyright (c) MontaVista Software, Inc. 2008.
* Anton Vorontsov <[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 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <soc/fsl/qe/qe.h>
#include <asm/fsl_gtm.h>
#include "fhci.h"
static void recycle_frame(struct fhci_usb *usb, struct packet *pkt)
{
pkt->data = NULL;
pkt->len = 0;
pkt->status = USB_TD_OK;
pkt->info = 0;
pkt->priv_data = NULL;
cq_put(&usb->ep0->empty_frame_Q, pkt);
}
/* confirm submitted packet */
void fhci_transaction_confirm(struct fhci_usb *usb, struct packet *pkt)
{
struct td *td;
struct packet *td_pkt;
struct ed *ed;
u32 trans_len;
bool td_done = false;
td = fhci_remove_td_from_frame(usb->actual_frame);
td_pkt = td->pkt;
trans_len = pkt->len;
td->status = pkt->status;
if (td->type == FHCI_TA_IN && td_pkt->info & PKT_DUMMY_PACKET) {
if ((td->data + td->actual_len) && trans_len)
memcpy(td->data + td->actual_len, pkt->data,
trans_len);
cq_put(&usb->ep0->dummy_packets_Q, pkt->data);
}
recycle_frame(usb, pkt);
ed = td->ed;
if (ed->mode == FHCI_TF_ISO) {
if (ed->td_list.next->next != &ed->td_list) {
struct td *td_next =
list_entry(ed->td_list.next->next, struct td,
node);
td_next->start_frame = usb->actual_frame->frame_num;
}
td->actual_len = trans_len;
td_done = true;
} else if ((td->status & USB_TD_ERROR) &&
!(td->status & USB_TD_TX_ER_NAK)) {
/*
* There was an error on the transaction (but not NAK).
* If it is fatal error (data underrun, stall, bad pid or 3
* errors exceeded), mark this TD as done.
*/
if ((td->status & USB_TD_RX_DATA_UNDERUN) ||
(td->status & USB_TD_TX_ER_STALL) ||
(td->status & USB_TD_RX_ER_PID) ||
(++td->error_cnt >= 3)) {
ed->state = FHCI_ED_HALTED;
td_done = true;
if (td->status & USB_TD_RX_DATA_UNDERUN) {
fhci_dbg(usb->fhci, "td err fu\n");
td->toggle = !td->toggle;
td->actual_len += trans_len;
} else {
fhci_dbg(usb->fhci, "td err f!u\n");
}
} else {
fhci_dbg(usb->fhci, "td err !f\n");
/* it is not a fatal error -retry this transaction */
td->nak_cnt = 0;
td->error_cnt++;
td->status = USB_TD_OK;
}
} else if (td->status & USB_TD_TX_ER_NAK) {
/* there was a NAK response */
fhci_vdbg(usb->fhci, "td nack\n");
td->nak_cnt++;
td->error_cnt = 0;
td->status = USB_TD_OK;
} else {
/* there was no error on transaction */
td->error_cnt = 0;
td->nak_cnt = 0;
td->toggle = !td->toggle;
td->actual_len += trans_len;
if (td->len == td->actual_len)
td_done = true;
}
if (td_done)
fhci_move_td_from_ed_to_done_list(usb, ed);
}
/*
* Flush all transmitted packets from BDs
* This routine is called when disabling the USB port to flush all
* transmissions that are already scheduled in the BDs
*/
void fhci_flush_all_transmissions(struct fhci_usb *usb)
{
u8 mode;
struct td *td;
mode = in_8(&usb->fhci->regs->usb_usmod);
clrbits8(&usb->fhci->regs->usb_usmod, USB_MODE_EN);
fhci_flush_bds(usb);
while ((td = fhci_peek_td_from_frame(usb->actual_frame)) != NULL) {
struct packet *pkt = td->pkt;
pkt->status = USB_TD_TX_ER_TIMEOUT;
fhci_transaction_confirm(usb, pkt);
}
usb->actual_frame->frame_status = FRAME_END_TRANSMISSION;
/* reset the event register */
out_be16(&usb->fhci->regs->usb_usber, 0xffff);
/* enable the USB controller */
out_8(&usb->fhci->regs->usb_usmod, mode | USB_MODE_EN);
}
/*
* This function forms the packet and transmit the packet. This function
* will handle all endpoint type:ISO,interrupt,control and bulk
*/
static int add_packet(struct fhci_usb *usb, struct ed *ed, struct td *td)
{
u32 fw_transaction_time, len = 0;
struct packet *pkt;
u8 *data = NULL;
/* calcalate data address,len and toggle and then add the transaction */
if (td->toggle == USB_TD_TOGGLE_CARRY)
td->toggle = ed->toggle_carry;
switch (ed->mode) {
case FHCI_TF_ISO:
len = td->len;
if (td->type != FHCI_TA_IN)
data = td->data;
break;
case FHCI_TF_CTRL:
case FHCI_TF_BULK:
len = min(td->len - td->actual_len, ed->max_pkt_size);
if (!((td->type == FHCI_TA_IN) &&
((len + td->actual_len) == td->len)))
data = td->data + td->actual_len;
break;
case FHCI_TF_INTR:
len = min(td->len, ed->max_pkt_size);
if (!((td->type == FHCI_TA_IN) &&
((td->len + CRC_SIZE) >= ed->max_pkt_size)))
data = td->data;
break;
default:
break;
}
if (usb->port_status == FHCI_PORT_FULL)
fw_transaction_time = (((len + PROTOCOL_OVERHEAD) * 11) >> 4);
else
fw_transaction_time = ((len + PROTOCOL_OVERHEAD) * 6);
/* check if there's enough space in this frame to submit this TD */
if (usb->actual_frame->total_bytes + len + PROTOCOL_OVERHEAD >=
usb->max_bytes_per_frame) {
fhci_vdbg(usb->fhci, "not enough space in this frame: "
"%d %d %d\n", usb->actual_frame->total_bytes, len,
usb->max_bytes_per_frame);
return -1;
}
/* check if there's enough time in this frame to submit this TD */
if (usb->actual_frame->frame_status != FRAME_IS_PREPARED &&
(usb->actual_frame->frame_status & FRAME_END_TRANSMISSION ||
(fw_transaction_time + usb->sw_transaction_time >=
1000 - fhci_get_sof_timer_count(usb)))) {
fhci_dbg(usb->fhci, "not enough time in this frame\n");
return -1;
}
/* update frame object fields before transmitting */
pkt = cq_get(&usb->ep0->empty_frame_Q);
if (!pkt) {
fhci_dbg(usb->fhci, "there is no empty frame\n");
return -1;
}
td->pkt = pkt;
pkt->info = 0;
if (data == NULL) {
data = cq_get(&usb->ep0->dummy_packets_Q);
BUG_ON(!data);
pkt->info = PKT_DUMMY_PACKET;
}
pkt->data = data;
pkt->len = len;
pkt->status = USB_TD_OK;
/* update TD status field before transmitting */
td->status = USB_TD_INPROGRESS;
/* update actual frame time object with the actual transmission */
usb->actual_frame->total_bytes += (len + PROTOCOL_OVERHEAD);
fhci_add_td_to_frame(usb->actual_frame, td);
if (usb->port_status != FHCI_PORT_FULL &&
usb->port_status != FHCI_PORT_LOW) {
pkt->status = USB_TD_TX_ER_TIMEOUT;
pkt->len = 0;
fhci_transaction_confirm(usb, pkt);
} else if (fhci_host_transaction(usb, pkt, td->type, ed->dev_addr,
ed->ep_addr, ed->mode, ed->speed, td->toggle)) {
/* remove TD from actual frame */
list_del_init(&td->frame_lh);
td->status = USB_TD_OK;
if (pkt->info & PKT_DUMMY_PACKET)
cq_put(&usb->ep0->dummy_packets_Q, pkt->data);
recycle_frame(usb, pkt);
usb->actual_frame->total_bytes -= (len + PROTOCOL_OVERHEAD);
fhci_err(usb->fhci, "host transaction failed\n");
return -1;
}
return len;
}
static void move_head_to_tail(struct list_head *list)
{
struct list_head *node = list->next;
if (!list_empty(list)) {
list_move_tail(node, list);
}
}
/*
* This function goes through the endpoint list and schedules the
* transactions within this list
*/
static int scan_ed_list(struct fhci_usb *usb,
struct list_head *list, enum fhci_tf_mode list_type)
{
static const int frame_part[4] = {
[FHCI_TF_CTRL] = MAX_BYTES_PER_FRAME,
[FHCI_TF_ISO] = (MAX_BYTES_PER_FRAME *
MAX_PERIODIC_FRAME_USAGE) / 100,
[FHCI_TF_BULK] = MAX_BYTES_PER_FRAME,
[FHCI_TF_INTR] = (MAX_BYTES_PER_FRAME *
MAX_PERIODIC_FRAME_USAGE) / 100
};
struct ed *ed;
struct td *td;
int ans = 1;
u32 save_transaction_time = usb->sw_transaction_time;
list_for_each_entry(ed, list, node) {
td = ed->td_head;
if (!td || (td && td->status == USB_TD_INPROGRESS))
continue;
if (ed->state != FHCI_ED_OPER) {
if (ed->state == FHCI_ED_URB_DEL) {
td->status = USB_TD_OK;
fhci_move_td_from_ed_to_done_list(usb, ed);
ed->state = FHCI_ED_SKIP;
}
continue;
}
/*
* if it isn't interrupt pipe or it is not iso pipe and the
* interval time passed
*/
if ((list_type == FHCI_TF_INTR || list_type == FHCI_TF_ISO) &&
(((usb->actual_frame->frame_num -
td->start_frame) & 0x7ff) < td->interval))
continue;
if (add_packet(usb, ed, td) < 0)
continue;
/* update time stamps in the TD */
td->start_frame = usb->actual_frame->frame_num;
usb->sw_transaction_time += save_transaction_time;
if (usb->actual_frame->total_bytes >=
usb->max_bytes_per_frame) {
usb->actual_frame->frame_status =
FRAME_DATA_END_TRANSMISSION;
fhci_push_dummy_bd(usb->ep0);
ans = 0;
break;
}
if (usb->actual_frame->total_bytes >= frame_part[list_type])
break;
}
/* be fair to each ED(move list head around) */
move_head_to_tail(list);
usb->sw_transaction_time = save_transaction_time;
return ans;
}
static u32 rotate_frames(struct fhci_usb *usb)
{
struct fhci_hcd *fhci = usb->fhci;
if (!list_empty(&usb->actual_frame->tds_list)) {
if ((((in_be16(&fhci->pram->frame_num) & 0x07ff) -
usb->actual_frame->frame_num) & 0x7ff) > 5)
fhci_flush_actual_frame(usb);
else
return -EINVAL;
}
usb->actual_frame->frame_status = FRAME_IS_PREPARED;
usb->actual_frame->frame_num = in_be16(&fhci->pram->frame_num) & 0x7ff;
usb->actual_frame->total_bytes = 0;
return 0;
}
/*
* This function schedule the USB transaction and will process the
* endpoint in the following order: iso, interrupt, control and bulk.
*/
void fhci_schedule_transactions(struct fhci_usb *usb)
{
int left = 1;
if (usb->actual_frame->frame_status & FRAME_END_TRANSMISSION)
if (rotate_frames(usb) != 0)
return;
if (usb->actual_frame->frame_status & FRAME_END_TRANSMISSION)
return;
if (usb->actual_frame->total_bytes == 0) {
/*
* schedule the next available ISO transfer
*or next stage of the ISO transfer
*/
scan_ed_list(usb, &usb->hc_list->iso_list, FHCI_TF_ISO);
/*
* schedule the next available interrupt transfer or
* the next stage of the interrupt transfer
*/
scan_ed_list(usb, &usb->hc_list->intr_list, FHCI_TF_INTR);
/*
* schedule the next available control transfer
* or the next stage of the control transfer
*/
left = scan_ed_list(usb, &usb->hc_list->ctrl_list,
FHCI_TF_CTRL);
}
/*
* schedule the next available bulk transfer or the next stage of the
* bulk transfer
*/
if (left > 0)
scan_ed_list(usb, &usb->hc_list->bulk_list, FHCI_TF_BULK);
}
/* Handles SOF interrupt */
static void sof_interrupt(struct fhci_hcd *fhci)
{
struct fhci_usb *usb = fhci->usb_lld;
if ((usb->port_status == FHCI_PORT_DISABLED) &&
(usb->vroot_hub->port.wPortStatus & USB_PORT_STAT_CONNECTION) &&
!(usb->vroot_hub->port.wPortChange & USB_PORT_STAT_C_CONNECTION)) {
if (usb->vroot_hub->port.wPortStatus & USB_PORT_STAT_LOW_SPEED)
usb->port_status = FHCI_PORT_LOW;
else
usb->port_status = FHCI_PORT_FULL;
/* Disable IDLE */
usb->saved_msk &= ~USB_E_IDLE_MASK;
out_be16(&usb->fhci->regs->usb_usbmr, usb->saved_msk);
}
gtm_set_exact_timer16(fhci->timer, usb->max_frame_usage, false);
fhci_host_transmit_actual_frame(usb);
usb->actual_frame->frame_status = FRAME_IS_TRANSMITTED;
fhci_schedule_transactions(usb);
}
/* Handles device disconnected interrupt on port */
void fhci_device_disconnected_interrupt(struct fhci_hcd *fhci)
{
struct fhci_usb *usb = fhci->usb_lld;
fhci_dbg(fhci, "-> %s\n", __func__);
fhci_usb_disable_interrupt(usb);
clrbits8(&usb->fhci->regs->usb_usmod, USB_MODE_LSS);
usb->port_status = FHCI_PORT_DISABLED;
fhci_stop_sof_timer(fhci);
/* Enable IDLE since we want to know if something comes along */
usb->saved_msk |= USB_E_IDLE_MASK;
out_be16(&usb->fhci->regs->usb_usbmr, usb->saved_msk);
usb->vroot_hub->port.wPortStatus &= ~USB_PORT_STAT_CONNECTION;
usb->vroot_hub->port.wPortChange |= USB_PORT_STAT_C_CONNECTION;
usb->max_bytes_per_frame = 0;
fhci_usb_enable_interrupt(usb);
fhci_dbg(fhci, "<- %s\n", __func__);
}
/* detect a new device connected on the USB port */
void fhci_device_connected_interrupt(struct fhci_hcd *fhci)
{
struct fhci_usb *usb = fhci->usb_lld;
int state;
int ret;
fhci_dbg(fhci, "-> %s\n", __func__);
fhci_usb_disable_interrupt(usb);
state = fhci_ioports_check_bus_state(fhci);
/* low-speed device was connected to the USB port */
if (state == 1) {
ret = qe_usb_clock_set(fhci->lowspeed_clk, USB_CLOCK >> 3);
if (ret) {
fhci_warn(fhci, "Low-Speed device is not supported, "
"try use BRGx\n");
goto out;
}
usb->port_status = FHCI_PORT_LOW;
setbits8(&usb->fhci->regs->usb_usmod, USB_MODE_LSS);
usb->vroot_hub->port.wPortStatus |=
(USB_PORT_STAT_LOW_SPEED |
USB_PORT_STAT_CONNECTION);
usb->vroot_hub->port.wPortChange |=
USB_PORT_STAT_C_CONNECTION;
usb->max_bytes_per_frame =
(MAX_BYTES_PER_FRAME >> 3) - 7;
fhci_port_enable(usb);
} else if (state == 2) {
ret = qe_usb_clock_set(fhci->fullspeed_clk, USB_CLOCK);
if (ret) {
fhci_warn(fhci, "Full-Speed device is not supported, "
"try use CLKx\n");
goto out;
}
usb->port_status = FHCI_PORT_FULL;
clrbits8(&usb->fhci->regs->usb_usmod, USB_MODE_LSS);
usb->vroot_hub->port.wPortStatus &=
~USB_PORT_STAT_LOW_SPEED;
usb->vroot_hub->port.wPortStatus |=
USB_PORT_STAT_CONNECTION;
usb->vroot_hub->port.wPortChange |=
USB_PORT_STAT_C_CONNECTION;
usb->max_bytes_per_frame = (MAX_BYTES_PER_FRAME - 15);
fhci_port_enable(usb);
}
out:
fhci_usb_enable_interrupt(usb);
fhci_dbg(fhci, "<- %s\n", __func__);
}
irqreturn_t fhci_frame_limit_timer_irq(int irq, void *_hcd)
{
struct usb_hcd *hcd = _hcd;
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
struct fhci_usb *usb = fhci->usb_lld;
spin_lock(&fhci->lock);
gtm_set_exact_timer16(fhci->timer, 1000, false);
if (usb->actual_frame->frame_status == FRAME_IS_TRANSMITTED) {
usb->actual_frame->frame_status = FRAME_TIMER_END_TRANSMISSION;
fhci_push_dummy_bd(usb->ep0);
}
fhci_schedule_transactions(usb);
spin_unlock(&fhci->lock);
return IRQ_HANDLED;
}
/* Cancel transmission on the USB endpoint */
static void abort_transmission(struct fhci_usb *usb)
{
fhci_dbg(usb->fhci, "-> %s\n", __func__);
/* issue stop Tx command */
qe_issue_cmd(QE_USB_STOP_TX, QE_CR_SUBBLOCK_USB, EP_ZERO, 0);
/* flush Tx FIFOs */
out_8(&usb->fhci->regs->usb_uscom, USB_CMD_FLUSH_FIFO | EP_ZERO);
udelay(1000);
/* reset Tx BDs */
fhci_flush_bds(usb);
/* issue restart Tx command */
qe_issue_cmd(QE_USB_RESTART_TX, QE_CR_SUBBLOCK_USB, EP_ZERO, 0);
fhci_dbg(usb->fhci, "<- %s\n", __func__);
}
irqreturn_t fhci_irq(struct usb_hcd *hcd)
{
struct fhci_hcd *fhci = hcd_to_fhci(hcd);
struct fhci_usb *usb;
u16 usb_er = 0;
unsigned long flags;
spin_lock_irqsave(&fhci->lock, flags);
usb = fhci->usb_lld;
usb_er |= in_be16(&usb->fhci->regs->usb_usber) &
in_be16(&usb->fhci->regs->usb_usbmr);
/* clear event bits for next time */
out_be16(&usb->fhci->regs->usb_usber, usb_er);
fhci_dbg_isr(fhci, usb_er);
if (usb_er & USB_E_RESET_MASK) {
if ((usb->port_status == FHCI_PORT_FULL) ||
(usb->port_status == FHCI_PORT_LOW)) {
fhci_device_disconnected_interrupt(fhci);
usb_er &= ~USB_E_IDLE_MASK;
} else if (usb->port_status == FHCI_PORT_WAITING) {
usb->port_status = FHCI_PORT_DISCONNECTING;
/* Turn on IDLE since we want to disconnect */
usb->saved_msk |= USB_E_IDLE_MASK;
out_be16(&usb->fhci->regs->usb_usber,
usb->saved_msk);
} else if (usb->port_status == FHCI_PORT_DISABLED) {
if (fhci_ioports_check_bus_state(fhci) == 1)
fhci_device_connected_interrupt(fhci);
}
usb_er &= ~USB_E_RESET_MASK;
}
if (usb_er & USB_E_MSF_MASK) {
abort_transmission(fhci->usb_lld);
usb_er &= ~USB_E_MSF_MASK;
}
if (usb_er & (USB_E_SOF_MASK | USB_E_SFT_MASK)) {
sof_interrupt(fhci);
usb_er &= ~(USB_E_SOF_MASK | USB_E_SFT_MASK);
}
if (usb_er & USB_E_TXB_MASK) {
fhci_tx_conf_interrupt(fhci->usb_lld);
usb_er &= ~USB_E_TXB_MASK;
}
if (usb_er & USB_E_TXE1_MASK) {
fhci_tx_conf_interrupt(fhci->usb_lld);
usb_er &= ~USB_E_TXE1_MASK;
}
if (usb_er & USB_E_IDLE_MASK) {
if (usb->port_status == FHCI_PORT_DISABLED) {
usb_er &= ~USB_E_RESET_MASK;
fhci_device_connected_interrupt(fhci);
} else if (usb->port_status ==
FHCI_PORT_DISCONNECTING) {
/* XXX usb->port_status = FHCI_PORT_WAITING; */
/* Disable IDLE */
usb->saved_msk &= ~USB_E_IDLE_MASK;
out_be16(&usb->fhci->regs->usb_usbmr,
usb->saved_msk);
} else {
fhci_dbg_isr(fhci, -1);
}
usb_er &= ~USB_E_IDLE_MASK;
}
spin_unlock_irqrestore(&fhci->lock, flags);
return IRQ_HANDLED;
}
/*
* Process normal completions(error or success) and clean the schedule.
*
* This is the main path for handing urbs back to drivers. The only other patth
* is process_del_list(),which unlinks URBs by scanning EDs,instead of scanning
* the (re-reversed) done list as this does.
*/
static void process_done_list(unsigned long data)
{
struct urb *urb;
struct ed *ed;
struct td *td;
struct urb_priv *urb_priv;
struct fhci_hcd *fhci = (struct fhci_hcd *)data;
disable_irq(fhci->timer->irq);
disable_irq(fhci_to_hcd(fhci)->irq);
spin_lock(&fhci->lock);
td = fhci_remove_td_from_done_list(fhci->hc_list);
while (td != NULL) {
urb = td->urb;
urb_priv = urb->hcpriv;
ed = td->ed;
/* update URB's length and status from TD */
fhci_done_td(urb, td);
urb_priv->tds_cnt++;
/*
* if all this urb's TDs are done, call complete()
* Interrupt transfers are the onley special case:
* they are reissued,until "deleted" by usb_unlink_urb
* (real work done in a SOF intr, by process_del_list)
*/
if (urb_priv->tds_cnt == urb_priv->num_of_tds) {
fhci_urb_complete_free(fhci, urb);
} else if (urb_priv->state == URB_DEL &&
ed->state == FHCI_ED_SKIP) {
fhci_del_ed_list(fhci, ed);
ed->state = FHCI_ED_OPER;
} else if (ed->state == FHCI_ED_HALTED) {
urb_priv->state = URB_DEL;
ed->state = FHCI_ED_URB_DEL;
fhci_del_ed_list(fhci, ed);
ed->state = FHCI_ED_OPER;
}
td = fhci_remove_td_from_done_list(fhci->hc_list);
}
spin_unlock(&fhci->lock);
enable_irq(fhci->timer->irq);
enable_irq(fhci_to_hcd(fhci)->irq);
}
DECLARE_TASKLET(fhci_tasklet, process_done_list, 0);
/* transfer complted callback */
u32 fhci_transfer_confirm_callback(struct fhci_hcd *fhci)
{
if (!fhci->process_done_task->state)
tasklet_schedule(fhci->process_done_task);
return 0;
}
/*
* adds urb to the endpoint descriptor list
* arguments:
* fhci data structure for the Low level host controller
* ep USB Host endpoint data structure
* urb USB request block data structure
*/
void fhci_queue_urb(struct fhci_hcd *fhci, struct urb *urb)
{
struct ed *ed = urb->ep->hcpriv;
struct urb_priv *urb_priv = urb->hcpriv;
u32 data_len = urb->transfer_buffer_length;
int urb_state = 0;
int toggle = 0;
struct td *td;
u8 *data;
u16 cnt = 0;
if (ed == NULL) {
ed = fhci_get_empty_ed(fhci);
ed->dev_addr = usb_pipedevice(urb->pipe);
ed->ep_addr = usb_pipeendpoint(urb->pipe);
switch (usb_pipetype(urb->pipe)) {
case PIPE_CONTROL:
ed->mode = FHCI_TF_CTRL;
break;
case PIPE_BULK:
ed->mode = FHCI_TF_BULK;
break;
case PIPE_INTERRUPT:
ed->mode = FHCI_TF_INTR;
break;
case PIPE_ISOCHRONOUS:
ed->mode = FHCI_TF_ISO;
break;
default:
break;
}
ed->speed = (urb->dev->speed == USB_SPEED_LOW) ?
FHCI_LOW_SPEED : FHCI_FULL_SPEED;
ed->max_pkt_size = usb_maxpacket(urb->dev,
urb->pipe, usb_pipeout(urb->pipe));
urb->ep->hcpriv = ed;
fhci_dbg(fhci, "new ep speed=%d max_pkt_size=%d\n",
ed->speed, ed->max_pkt_size);
}
/* for ISO transfer calculate start frame index */
if (ed->mode == FHCI_TF_ISO) {
/* Ignore the possibility of underruns */
urb->start_frame = ed->td_head ? ed->next_iso :
get_frame_num(fhci);
ed->next_iso = (urb->start_frame + urb->interval *
urb->number_of_packets) & 0x07ff;
}
/*
* OHCI handles the DATA toggle itself,we just use the USB
* toggle bits
*/
if (usb_gettoggle(urb->dev, usb_pipeendpoint(urb->pipe),
usb_pipeout(urb->pipe)))
toggle = USB_TD_TOGGLE_CARRY;
else {
toggle = USB_TD_TOGGLE_DATA0;
usb_settoggle(urb->dev, usb_pipeendpoint(urb->pipe),
usb_pipeout(urb->pipe), 1);
}
urb_priv->tds_cnt = 0;
urb_priv->ed = ed;
if (data_len > 0)
data = urb->transfer_buffer;
else
data = NULL;
switch (ed->mode) {
case FHCI_TF_BULK:
if (urb->transfer_flags & URB_ZERO_PACKET &&
urb->transfer_buffer_length > 0 &&
((urb->transfer_buffer_length %
usb_maxpacket(urb->dev, urb->pipe,
usb_pipeout(urb->pipe))) == 0))
urb_state = US_BULK0;
while (data_len > 4096) {
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt,
usb_pipeout(urb->pipe) ? FHCI_TA_OUT :
FHCI_TA_IN,
cnt ? USB_TD_TOGGLE_CARRY :
toggle,
data, 4096, 0, 0, true);
data += 4096;
data_len -= 4096;
cnt++;
}
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt,
usb_pipeout(urb->pipe) ? FHCI_TA_OUT : FHCI_TA_IN,
cnt ? USB_TD_TOGGLE_CARRY : toggle,
data, data_len, 0, 0, true);
cnt++;
if (urb->transfer_flags & URB_ZERO_PACKET &&
cnt < urb_priv->num_of_tds) {
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt,
usb_pipeout(urb->pipe) ? FHCI_TA_OUT :
FHCI_TA_IN,
USB_TD_TOGGLE_CARRY, NULL, 0, 0, 0, true);
cnt++;
}
break;
case FHCI_TF_INTR:
urb->start_frame = get_frame_num(fhci) + 1;
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt++,
usb_pipeout(urb->pipe) ? FHCI_TA_OUT : FHCI_TA_IN,
USB_TD_TOGGLE_DATA0, data, data_len,
urb->interval, urb->start_frame, true);
break;
case FHCI_TF_CTRL:
ed->dev_addr = usb_pipedevice(urb->pipe);
ed->max_pkt_size = usb_maxpacket(urb->dev, urb->pipe,
usb_pipeout(urb->pipe));
/* setup stage */
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt++, FHCI_TA_SETUP,
USB_TD_TOGGLE_DATA0, urb->setup_packet, 8, 0, 0, true);
/* data stage */
if (data_len > 0) {
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt++,
usb_pipeout(urb->pipe) ? FHCI_TA_OUT :
FHCI_TA_IN,
USB_TD_TOGGLE_DATA1, data, data_len, 0, 0,
true);
}
/* status stage */
if (data_len > 0)
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt++,
(usb_pipeout(urb->pipe) ? FHCI_TA_IN :
FHCI_TA_OUT),
USB_TD_TOGGLE_DATA1, data, 0, 0, 0, true);
else
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt++,
FHCI_TA_IN,
USB_TD_TOGGLE_DATA1, data, 0, 0, 0, true);
urb_state = US_CTRL_SETUP;
break;
case FHCI_TF_ISO:
for (cnt = 0; cnt < urb->number_of_packets; cnt++) {
u16 frame = urb->start_frame;
/*
* FIXME scheduling should handle frame counter
* roll-around ... exotic case (and OHCI has
* a 2^16 iso range, vs other HCs max of 2^10)
*/
frame += cnt * urb->interval;
frame &= 0x07ff;
td = fhci_td_fill(fhci, urb, urb_priv, ed, cnt,
usb_pipeout(urb->pipe) ? FHCI_TA_OUT :
FHCI_TA_IN,
USB_TD_TOGGLE_DATA0,
data + urb->iso_frame_desc[cnt].offset,
urb->iso_frame_desc[cnt].length,
urb->interval, frame, true);
}
break;
default:
break;
}
/*
* set the state of URB
* control pipe:3 states -- setup,data,status
* interrupt and bulk pipe:1 state -- data
*/
urb->pipe &= ~0x1f;
urb->pipe |= urb_state & 0x1f;
urb_priv->state = URB_INPROGRESS;
if (!ed->td_head) {
ed->state = FHCI_ED_OPER;
switch (ed->mode) {
case FHCI_TF_CTRL:
list_add(&ed->node, &fhci->hc_list->ctrl_list);
break;
case FHCI_TF_BULK:
list_add(&ed->node, &fhci->hc_list->bulk_list);
break;
case FHCI_TF_INTR:
list_add(&ed->node, &fhci->hc_list->intr_list);
break;
case FHCI_TF_ISO:
list_add(&ed->node, &fhci->hc_list->iso_list);
break;
default:
break;
}
}
fhci_add_tds_to_ed(ed, urb_priv->tds, urb_priv->num_of_tds);
fhci->active_urbs++;
}
| mikedlowis-prototypes/albase | source/kernel/drivers/usb/host/fhci-sched.c | C | bsd-2-clause | 24,382 |
/*
* sdhci-pltfm.c Support for SDHCI platform devices
* Copyright (c) 2009 Intel Corporation
*
* Copyright (c) 2007, 2011 Freescale Semiconductor, Inc.
* Copyright (c) 2009 MontaVista Software, Inc.
*
* Authors: Xiaobo Xie <[email protected]>
* Anton Vorontsov <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Supports:
* SDHCI platform devices
*
* Inspired by sdhci-pci.c, by Pierre Ossman
*/
#include <linux/err.h>
#include <linux/module.h>
#include <linux/of.h>
#ifdef CONFIG_PPC
#include <asm/machdep.h>
#endif
#include "sdhci-pltfm.h"
unsigned int sdhci_pltfm_clk_get_max_clock(struct sdhci_host *host)
{
struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
return clk_get_rate(pltfm_host->clk);
}
EXPORT_SYMBOL_GPL(sdhci_pltfm_clk_get_max_clock);
static const struct sdhci_ops sdhci_pltfm_ops = {
.set_clock = sdhci_set_clock,
.set_bus_width = sdhci_set_bus_width,
.reset = sdhci_reset,
.set_uhs_signaling = sdhci_set_uhs_signaling,
};
#ifdef CONFIG_OF
static bool sdhci_of_wp_inverted(struct device_node *np)
{
if (of_get_property(np, "sdhci,wp-inverted", NULL) ||
of_get_property(np, "wp-inverted", NULL))
return true;
/* Old device trees don't have the wp-inverted property. */
#ifdef CONFIG_PPC
return machine_is(mpc837x_rdb) || machine_is(mpc837x_mds);
#else
return false;
#endif /* CONFIG_PPC */
}
void sdhci_get_of_property(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct sdhci_host *host = platform_get_drvdata(pdev);
struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
u32 bus_width;
if (of_get_property(np, "sdhci,auto-cmd12", NULL))
host->quirks |= SDHCI_QUIRK_MULTIBLOCK_READ_ACMD12;
if (of_get_property(np, "sdhci,1-bit-only", NULL) ||
(of_property_read_u32(np, "bus-width", &bus_width) == 0 &&
bus_width == 1))
host->quirks |= SDHCI_QUIRK_FORCE_1_BIT_DATA;
if (sdhci_of_wp_inverted(np))
host->quirks |= SDHCI_QUIRK_INVERTED_WRITE_PROTECT;
if (of_get_property(np, "broken-cd", NULL))
host->quirks |= SDHCI_QUIRK_BROKEN_CARD_DETECTION;
if (of_get_property(np, "no-1-8-v", NULL))
host->quirks2 |= SDHCI_QUIRK2_NO_1_8_V;
if (of_device_is_compatible(np, "fsl,p2020-rev1-esdhc"))
host->quirks |= SDHCI_QUIRK_BROKEN_DMA;
if (of_device_is_compatible(np, "fsl,p2020-esdhc") ||
of_device_is_compatible(np, "fsl,p1010-esdhc") ||
of_device_is_compatible(np, "fsl,t4240-esdhc") ||
of_device_is_compatible(np, "fsl,mpc8536-esdhc"))
host->quirks |= SDHCI_QUIRK_BROKEN_TIMEOUT_VAL;
of_property_read_u32(np, "clock-frequency", &pltfm_host->clock);
if (of_find_property(np, "keep-power-in-suspend", NULL))
host->mmc->pm_caps |= MMC_PM_KEEP_POWER;
if (of_property_read_bool(np, "wakeup-source") ||
of_property_read_bool(np, "enable-sdio-wakeup")) /* legacy */
host->mmc->pm_caps |= MMC_PM_WAKE_SDIO_IRQ;
}
#else
void sdhci_get_of_property(struct platform_device *pdev) {}
#endif /* CONFIG_OF */
EXPORT_SYMBOL_GPL(sdhci_get_of_property);
struct sdhci_host *sdhci_pltfm_init(struct platform_device *pdev,
const struct sdhci_pltfm_data *pdata,
size_t priv_size)
{
struct sdhci_host *host;
struct resource *iomem;
int ret;
iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!iomem) {
ret = -ENOMEM;
goto err;
}
if (resource_size(iomem) < 0x100)
dev_err(&pdev->dev, "Invalid iomem size!\n");
host = sdhci_alloc_host(&pdev->dev,
sizeof(struct sdhci_pltfm_host) + priv_size);
if (IS_ERR(host)) {
ret = PTR_ERR(host);
goto err;
}
host->hw_name = dev_name(&pdev->dev);
if (pdata && pdata->ops)
host->ops = pdata->ops;
else
host->ops = &sdhci_pltfm_ops;
if (pdata) {
host->quirks = pdata->quirks;
host->quirks2 = pdata->quirks2;
}
host->irq = platform_get_irq(pdev, 0);
if (!request_mem_region(iomem->start, resource_size(iomem),
mmc_hostname(host->mmc))) {
dev_err(&pdev->dev, "cannot request region\n");
ret = -EBUSY;
goto err_request;
}
host->ioaddr = ioremap(iomem->start, resource_size(iomem));
if (!host->ioaddr) {
dev_err(&pdev->dev, "failed to remap registers\n");
ret = -ENOMEM;
goto err_remap;
}
/*
* Some platforms need to probe the controller to be able to
* determine which caps should be used.
*/
if (host->ops && host->ops->platform_init)
host->ops->platform_init(host);
platform_set_drvdata(pdev, host);
return host;
err_remap:
release_mem_region(iomem->start, resource_size(iomem));
err_request:
sdhci_free_host(host);
err:
dev_err(&pdev->dev, "%s failed %d\n", __func__, ret);
return ERR_PTR(ret);
}
EXPORT_SYMBOL_GPL(sdhci_pltfm_init);
void sdhci_pltfm_free(struct platform_device *pdev)
{
struct sdhci_host *host = platform_get_drvdata(pdev);
struct resource *iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
iounmap(host->ioaddr);
release_mem_region(iomem->start, resource_size(iomem));
sdhci_free_host(host);
}
EXPORT_SYMBOL_GPL(sdhci_pltfm_free);
int sdhci_pltfm_register(struct platform_device *pdev,
const struct sdhci_pltfm_data *pdata,
size_t priv_size)
{
struct sdhci_host *host;
int ret = 0;
host = sdhci_pltfm_init(pdev, pdata, priv_size);
if (IS_ERR(host))
return PTR_ERR(host);
sdhci_get_of_property(pdev);
ret = sdhci_add_host(host);
if (ret)
sdhci_pltfm_free(pdev);
return ret;
}
EXPORT_SYMBOL_GPL(sdhci_pltfm_register);
int sdhci_pltfm_unregister(struct platform_device *pdev)
{
struct sdhci_host *host = platform_get_drvdata(pdev);
struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host);
int dead = (readl(host->ioaddr + SDHCI_INT_STATUS) == 0xffffffff);
sdhci_remove_host(host, dead);
clk_disable_unprepare(pltfm_host->clk);
sdhci_pltfm_free(pdev);
return 0;
}
EXPORT_SYMBOL_GPL(sdhci_pltfm_unregister);
#ifdef CONFIG_PM
int sdhci_pltfm_suspend(struct device *dev)
{
struct sdhci_host *host = dev_get_drvdata(dev);
return sdhci_suspend_host(host);
}
EXPORT_SYMBOL_GPL(sdhci_pltfm_suspend);
int sdhci_pltfm_resume(struct device *dev)
{
struct sdhci_host *host = dev_get_drvdata(dev);
return sdhci_resume_host(host);
}
EXPORT_SYMBOL_GPL(sdhci_pltfm_resume);
const struct dev_pm_ops sdhci_pltfm_pmops = {
.suspend = sdhci_pltfm_suspend,
.resume = sdhci_pltfm_resume,
};
EXPORT_SYMBOL_GPL(sdhci_pltfm_pmops);
#endif /* CONFIG_PM */
static int __init sdhci_pltfm_drv_init(void)
{
pr_info("sdhci-pltfm: SDHCI platform and OF driver helper\n");
return 0;
}
module_init(sdhci_pltfm_drv_init);
static void __exit sdhci_pltfm_drv_exit(void)
{
}
module_exit(sdhci_pltfm_drv_exit);
MODULE_DESCRIPTION("SDHCI platform and OF driver helper");
MODULE_AUTHOR("Intel Corporation");
MODULE_LICENSE("GPL v2");
| mikedlowis-prototypes/albase | source/kernel/drivers/mmc/host/sdhci-pltfm.c | C | bsd-2-clause | 7,270 |
<!DOCTYPE html>
<!--
Copyright (c) 2012-2013. Sencha Inc.
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../bootstrap.css">
<script type="text/javascript">
window.__webdriver_javascript_errors = [];
window.onerror = function(errorMsg, url, lineNumber) {
window.__webdriver_javascript_errors.push(
errorMsg +' (found at ' + url + ', line ' + lineNumber + ')');
};
</script>
<script type="text/javascript" src="../bootstrap.js"></script>
</head>
<body></body>
</html>
| applifireAlgo/ZenClubApp | zenws/src/main/webapp/ext/packages/sencha-soap/test/specs/index.html | HTML | gpl-3.0 | 629 |
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
*/
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MyRMI extends java.rmi.Remote {
public boolean classLoaderOk() throws RemoteException;
public void shutdown() throws Exception;
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/MyRMI.java | Java | mit | 1,276 |
"""Tests for tools and arithmetics for monomials of distributed polynomials. """
from sympy.polys.monomials import (
itermonomials, monomial_count,
monomial_mul, monomial_div,
monomial_gcd, monomial_lcm,
monomial_max, monomial_min,
monomial_divides,
Monomial,
)
from sympy.polys.polyerrors import ExactQuotientFailed
from sympy.abc import a, b, c, x, y, z
from sympy.core import S
from sympy.utilities.pytest import raises
def test_monomials():
assert itermonomials([], 0) == set([S(1)])
assert itermonomials([], 1) == set([S(1)])
assert itermonomials([], 2) == set([S(1)])
assert itermonomials([], 3) == set([S(1)])
assert itermonomials([x], 0) == set([S(1)])
assert itermonomials([x], 1) == set([S(1), x])
assert itermonomials([x], 2) == set([S(1), x, x**2])
assert itermonomials([x], 3) == set([S(1), x, x**2, x**3])
assert itermonomials([x, y], 0) == set([S(1)])
assert itermonomials([x, y], 1) == set([S(1), x, y])
assert itermonomials([x, y], 2) == set([S(1), x, y, x**2, y**2, x*y])
assert itermonomials([x, y], 3) == \
set([S(1), x, y, x**2, x**3, y**2, y**3, x*y, x*y**2, y*x**2])
def test_monomial_count():
assert monomial_count(2, 2) == 6
assert monomial_count(2, 3) == 10
def test_monomial_mul():
assert monomial_mul((3, 4, 1), (1, 2, 0)) == (4, 6, 1)
def test_monomial_div():
assert monomial_div((3, 4, 1), (1, 2, 0)) == (2, 2, 1)
def test_monomial_gcd():
assert monomial_gcd((3, 4, 1), (1, 2, 0)) == (1, 2, 0)
def test_monomial_lcm():
assert monomial_lcm((3, 4, 1), (1, 2, 0)) == (3, 4, 1)
def test_monomial_max():
assert monomial_max((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (6, 5, 9)
def test_monomial_min():
assert monomial_min((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (0, 3, 1)
def test_monomial_divides():
assert monomial_divides((1, 2, 3), (4, 5, 6)) is True
assert monomial_divides((1, 2, 3), (0, 5, 6)) is False
def test_Monomial():
m = Monomial((3, 4, 1), (x, y, z))
n = Monomial((1, 2, 0), (x, y, z))
assert m.as_expr() == x**3*y**4*z
assert n.as_expr() == x**1*y**2
assert m.as_expr(a, b, c) == a**3*b**4*c
assert n.as_expr(a, b, c) == a**1*b**2
assert m.exponents == (3, 4, 1)
assert m.gens == (x, y, z)
assert n.exponents == (1, 2, 0)
assert n.gens == (x, y, z)
assert m == (3, 4, 1)
assert n != (3, 4, 1)
assert m != (1, 2, 0)
assert n == (1, 2, 0)
assert m[0] == m[-3] == 3
assert m[1] == m[-2] == 4
assert m[2] == m[-1] == 1
assert n[0] == n[-3] == 1
assert n[1] == n[-2] == 2
assert n[2] == n[-1] == 0
assert m[:2] == (3, 4)
assert n[:2] == (1, 2)
assert m*n == Monomial((4, 6, 1))
assert m/n == Monomial((2, 2, 1))
assert m*(1, 2, 0) == Monomial((4, 6, 1))
assert m/(1, 2, 0) == Monomial((2, 2, 1))
assert m.gcd(n) == Monomial((1, 2, 0))
assert m.lcm(n) == Monomial((3, 4, 1))
assert m.gcd((1, 2, 0)) == Monomial((1, 2, 0))
assert m.lcm((1, 2, 0)) == Monomial((3, 4, 1))
assert m**0 == Monomial((0, 0, 0))
assert m**1 == m
assert m**2 == Monomial((6, 8, 2))
assert m**3 == Monomial((9, 12, 3))
raises(ExactQuotientFailed, lambda: m/Monomial((5, 2, 0)))
| wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/sympy/polys/tests/test_monomials.py | Python | mit | 3,266 |
/*
Copyright 2018 Danny Nguyen <[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 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/>.
*/
#pragma once
#undef RGBLED_NUM
#define RGBLIGHT_ANIMATIONS
#define RGBLED_NUM 12
#define RGBLIGHT_HUE_STEP 8
#define RGBLIGHT_SAT_STEP 8
#define RGBLIGHT_VAL_STEP 8
| chancegrissom/qmk_firmware | keyboards/40percentclub/nano/keymaps/spooka/config.h | C | gpl-2.0 | 830 |
/*
* Copyright (c) 2012-2016 Synaptics Incorporated
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/rmi.h>
#include <linux/input.h>
#include <linux/slab.h>
#include "rmi_driver.h"
#define RMI_F30_QUERY_SIZE 2
/* Defs for Query 0 */
#define RMI_F30_EXTENDED_PATTERNS 0x01
#define RMI_F30_HAS_MAPPABLE_BUTTONS BIT(1)
#define RMI_F30_HAS_LED BIT(2)
#define RMI_F30_HAS_GPIO BIT(3)
#define RMI_F30_HAS_HAPTIC BIT(4)
#define RMI_F30_HAS_GPIO_DRV_CTL BIT(5)
#define RMI_F30_HAS_MECH_MOUSE_BTNS BIT(6)
/* Defs for Query 1 */
#define RMI_F30_GPIO_LED_COUNT 0x1F
/* Defs for Control Registers */
#define RMI_F30_CTRL_1_GPIO_DEBOUNCE 0x01
#define RMI_F30_CTRL_1_HALT BIT(4)
#define RMI_F30_CTRL_1_HALTED BIT(5)
#define RMI_F30_CTRL_10_NUM_MECH_MOUSE_BTNS 0x03
#define RMI_F30_CTRL_MAX_REGS 32
#define RMI_F30_CTRL_MAX_BYTES DIV_ROUND_UP(RMI_F30_CTRL_MAX_REGS, 8)
#define RMI_F30_CTRL_MAX_REG_BLOCKS 11
#define RMI_F30_CTRL_REGS_MAX_SIZE (RMI_F30_CTRL_MAX_BYTES \
+ 1 \
+ RMI_F30_CTRL_MAX_BYTES \
+ RMI_F30_CTRL_MAX_BYTES \
+ RMI_F30_CTRL_MAX_BYTES \
+ 6 \
+ RMI_F30_CTRL_MAX_REGS \
+ RMI_F30_CTRL_MAX_REGS \
+ RMI_F30_CTRL_MAX_BYTES \
+ 1 \
+ 1)
#define TRACKSTICK_RANGE_START 3
#define TRACKSTICK_RANGE_END 6
struct rmi_f30_ctrl_data {
int address;
int length;
u8 *regs;
};
struct f30_data {
/* Query Data */
bool has_extended_pattern;
bool has_mappable_buttons;
bool has_led;
bool has_gpio;
bool has_haptic;
bool has_gpio_driver_control;
bool has_mech_mouse_btns;
u8 gpioled_count;
u8 register_count;
/* Control Register Data */
struct rmi_f30_ctrl_data ctrl[RMI_F30_CTRL_MAX_REG_BLOCKS];
u8 ctrl_regs[RMI_F30_CTRL_REGS_MAX_SIZE];
u32 ctrl_regs_size;
u8 data_regs[RMI_F30_CTRL_MAX_BYTES];
u16 *gpioled_key_map;
struct input_dev *input;
struct rmi_function *f03;
bool trackstick_buttons;
};
static int rmi_f30_read_control_parameters(struct rmi_function *fn,
struct f30_data *f30)
{
int error;
error = rmi_read_block(fn->rmi_dev, fn->fd.control_base_addr,
f30->ctrl_regs, f30->ctrl_regs_size);
if (error) {
dev_err(&fn->dev,
"%s: Could not read control registers at 0x%x: %d\n",
__func__, fn->fd.control_base_addr, error);
return error;
}
return 0;
}
static void rmi_f30_report_button(struct rmi_function *fn,
struct f30_data *f30, unsigned int button)
{
unsigned int reg_num = button >> 3;
unsigned int bit_num = button & 0x07;
u16 key_code = f30->gpioled_key_map[button];
bool key_down = !(f30->data_regs[reg_num] & BIT(bit_num));
if (f30->trackstick_buttons &&
button >= TRACKSTICK_RANGE_START &&
button <= TRACKSTICK_RANGE_END) {
rmi_f03_overwrite_button(f30->f03, key_code, key_down);
} else {
rmi_dbg(RMI_DEBUG_FN, &fn->dev,
"%s: call input report key (0x%04x) value (0x%02x)",
__func__, key_code, key_down);
input_report_key(f30->input, key_code, key_down);
}
}
static int rmi_f30_attention(struct rmi_function *fn, unsigned long *irq_bits)
{
struct f30_data *f30 = dev_get_drvdata(&fn->dev);
struct rmi_driver_data *drvdata = dev_get_drvdata(&fn->rmi_dev->dev);
int error;
int i;
/* Read the gpi led data. */
if (drvdata->attn_data.data) {
if (drvdata->attn_data.size < f30->register_count) {
dev_warn(&fn->dev,
"F30 interrupted, but data is missing\n");
return 0;
}
memcpy(f30->data_regs, drvdata->attn_data.data,
f30->register_count);
drvdata->attn_data.data += f30->register_count;
drvdata->attn_data.size -= f30->register_count;
} else {
error = rmi_read_block(fn->rmi_dev, fn->fd.data_base_addr,
f30->data_regs, f30->register_count);
if (error) {
dev_err(&fn->dev,
"%s: Failed to read F30 data registers: %d\n",
__func__, error);
return error;
}
}
if (f30->has_gpio) {
for (i = 0; i < f30->gpioled_count; i++)
if (f30->gpioled_key_map[i] != KEY_RESERVED)
rmi_f30_report_button(fn, f30, i);
if (f30->trackstick_buttons)
rmi_f03_commit_buttons(f30->f03);
}
return 0;
}
static int rmi_f30_config(struct rmi_function *fn)
{
struct f30_data *f30 = dev_get_drvdata(&fn->dev);
struct rmi_driver *drv = fn->rmi_dev->driver;
const struct rmi_device_platform_data *pdata =
rmi_get_platform_data(fn->rmi_dev);
int error;
/* can happen if f30_data.disable is set */
if (!f30)
return 0;
if (pdata->f30_data.trackstick_buttons) {
/* Try [re-]establish link to F03. */
f30->f03 = rmi_find_function(fn->rmi_dev, 0x03);
f30->trackstick_buttons = f30->f03 != NULL;
}
if (pdata->f30_data.disable) {
drv->clear_irq_bits(fn->rmi_dev, fn->irq_mask);
} else {
/* Write Control Register values back to device */
error = rmi_write_block(fn->rmi_dev, fn->fd.control_base_addr,
f30->ctrl_regs, f30->ctrl_regs_size);
if (error) {
dev_err(&fn->dev,
"%s: Could not write control registers at 0x%x: %d\n",
__func__, fn->fd.control_base_addr, error);
return error;
}
drv->set_irq_bits(fn->rmi_dev, fn->irq_mask);
}
return 0;
}
static void rmi_f30_set_ctrl_data(struct rmi_f30_ctrl_data *ctrl,
int *ctrl_addr, int len, u8 **reg)
{
ctrl->address = *ctrl_addr;
ctrl->length = len;
ctrl->regs = *reg;
*ctrl_addr += len;
*reg += len;
}
static bool rmi_f30_is_valid_button(int button, struct rmi_f30_ctrl_data *ctrl)
{
int byte_position = button >> 3;
int bit_position = button & 0x07;
/*
* ctrl2 -> dir == 0 -> input mode
* ctrl3 -> data == 1 -> actual button
*/
return !(ctrl[2].regs[byte_position] & BIT(bit_position)) &&
(ctrl[3].regs[byte_position] & BIT(bit_position));
}
static int rmi_f30_map_gpios(struct rmi_function *fn,
struct f30_data *f30)
{
const struct rmi_device_platform_data *pdata =
rmi_get_platform_data(fn->rmi_dev);
struct input_dev *input = f30->input;
unsigned int button = BTN_LEFT;
unsigned int trackstick_button = BTN_LEFT;
bool button_mapped = false;
int i;
f30->gpioled_key_map = devm_kcalloc(&fn->dev,
f30->gpioled_count,
sizeof(f30->gpioled_key_map[0]),
GFP_KERNEL);
if (!f30->gpioled_key_map) {
dev_err(&fn->dev, "Failed to allocate gpioled map memory.\n");
return -ENOMEM;
}
for (i = 0; i < f30->gpioled_count; i++) {
if (!rmi_f30_is_valid_button(i, f30->ctrl))
continue;
if (pdata->f30_data.trackstick_buttons &&
i >= TRACKSTICK_RANGE_START && i < TRACKSTICK_RANGE_END) {
f30->gpioled_key_map[i] = trackstick_button++;
} else if (!pdata->f30_data.buttonpad || !button_mapped) {
f30->gpioled_key_map[i] = button;
input_set_capability(input, EV_KEY, button++);
button_mapped = true;
}
}
input->keycode = f30->gpioled_key_map;
input->keycodesize = sizeof(f30->gpioled_key_map[0]);
input->keycodemax = f30->gpioled_count;
/*
* Buttonpad could be also inferred from f30->has_mech_mouse_btns,
* but I am not sure, so use only the pdata info and the number of
* mapped buttons.
*/
if (pdata->f30_data.buttonpad || (button - BTN_LEFT == 1))
__set_bit(INPUT_PROP_BUTTONPAD, input->propbit);
return 0;
}
static int rmi_f30_initialize(struct rmi_function *fn, struct f30_data *f30)
{
u8 *ctrl_reg = f30->ctrl_regs;
int control_address = fn->fd.control_base_addr;
u8 buf[RMI_F30_QUERY_SIZE];
int error;
error = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr,
buf, RMI_F30_QUERY_SIZE);
if (error) {
dev_err(&fn->dev, "Failed to read query register\n");
return error;
}
f30->has_extended_pattern = buf[0] & RMI_F30_EXTENDED_PATTERNS;
f30->has_mappable_buttons = buf[0] & RMI_F30_HAS_MAPPABLE_BUTTONS;
f30->has_led = buf[0] & RMI_F30_HAS_LED;
f30->has_gpio = buf[0] & RMI_F30_HAS_GPIO;
f30->has_haptic = buf[0] & RMI_F30_HAS_HAPTIC;
f30->has_gpio_driver_control = buf[0] & RMI_F30_HAS_GPIO_DRV_CTL;
f30->has_mech_mouse_btns = buf[0] & RMI_F30_HAS_MECH_MOUSE_BTNS;
f30->gpioled_count = buf[1] & RMI_F30_GPIO_LED_COUNT;
f30->register_count = DIV_ROUND_UP(f30->gpioled_count, 8);
if (f30->has_gpio && f30->has_led)
rmi_f30_set_ctrl_data(&f30->ctrl[0], &control_address,
f30->register_count, &ctrl_reg);
rmi_f30_set_ctrl_data(&f30->ctrl[1], &control_address,
sizeof(u8), &ctrl_reg);
if (f30->has_gpio) {
rmi_f30_set_ctrl_data(&f30->ctrl[2], &control_address,
f30->register_count, &ctrl_reg);
rmi_f30_set_ctrl_data(&f30->ctrl[3], &control_address,
f30->register_count, &ctrl_reg);
}
if (f30->has_led) {
rmi_f30_set_ctrl_data(&f30->ctrl[4], &control_address,
f30->register_count, &ctrl_reg);
rmi_f30_set_ctrl_data(&f30->ctrl[5], &control_address,
f30->has_extended_pattern ? 6 : 2,
&ctrl_reg);
}
if (f30->has_led || f30->has_gpio_driver_control) {
/* control 6 uses a byte per gpio/led */
rmi_f30_set_ctrl_data(&f30->ctrl[6], &control_address,
f30->gpioled_count, &ctrl_reg);
}
if (f30->has_mappable_buttons) {
/* control 7 uses a byte per gpio/led */
rmi_f30_set_ctrl_data(&f30->ctrl[7], &control_address,
f30->gpioled_count, &ctrl_reg);
}
if (f30->has_haptic) {
rmi_f30_set_ctrl_data(&f30->ctrl[8], &control_address,
f30->register_count, &ctrl_reg);
rmi_f30_set_ctrl_data(&f30->ctrl[9], &control_address,
sizeof(u8), &ctrl_reg);
}
if (f30->has_mech_mouse_btns)
rmi_f30_set_ctrl_data(&f30->ctrl[10], &control_address,
sizeof(u8), &ctrl_reg);
f30->ctrl_regs_size = ctrl_reg -
f30->ctrl_regs ?: RMI_F30_CTRL_REGS_MAX_SIZE;
error = rmi_f30_read_control_parameters(fn, f30);
if (error) {
dev_err(&fn->dev,
"Failed to initialize F30 control params: %d\n",
error);
return error;
}
if (f30->has_gpio) {
error = rmi_f30_map_gpios(fn, f30);
if (error)
return error;
}
return 0;
}
static int rmi_f30_probe(struct rmi_function *fn)
{
struct rmi_device *rmi_dev = fn->rmi_dev;
const struct rmi_device_platform_data *pdata =
rmi_get_platform_data(rmi_dev);
struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev);
struct f30_data *f30;
int error;
if (pdata->f30_data.disable)
return 0;
if (!drv_data->input) {
dev_info(&fn->dev, "F30: no input device found, ignoring\n");
return -ENXIO;
}
f30 = devm_kzalloc(&fn->dev, sizeof(*f30), GFP_KERNEL);
if (!f30)
return -ENOMEM;
f30->input = drv_data->input;
error = rmi_f30_initialize(fn, f30);
if (error)
return error;
dev_set_drvdata(&fn->dev, f30);
return 0;
}
struct rmi_function_handler rmi_f30_handler = {
.driver = {
.name = "rmi4_f30",
},
.func = 0x30,
.probe = rmi_f30_probe,
.config = rmi_f30_config,
.attention = rmi_f30_attention,
};
| eabatalov/au-linux-kernel-autumn-2017 | linux/drivers/input/rmi4/rmi_f30.c | C | gpl-3.0 | 10,812 |
Linux 内核的测试和调试(1)
================================================================================
### Linux 内核测试哲学 ###
不管是开源还是闭源,所有软件的开发流程中,测试是一个重要的、不可或缺的环节,Linux 内核也不例外。开发人员自测、系统测试、回归测试、压力测试,都有各自不同的目的,但是从更高一个层次上看,这些测试的最终目的又是一样的:保证软件能一直运行下去,当有新功能加进去时,要保证新功能可以正常工作。
在软件释出 release 版之前,不用回归测试就能保证稳定性,并且尽量避免在软件发布后被用户发现 bug。调试被用户发现的 bug 是一项非常浪费时间和精力的工作。因此测试是一项非常重要的工作。不像闭源和专有的操作系统,Linux 内核的开发过程是完全开放的。这种处理方式即是它的优点,也是它的缺点。多个开发者持续增加新功能、修 bug、不断集成与测试 —— 当环境有新的硬件或功能时,这种开发方式能够保证内核能持续工作。在开源项目中,开发者与用户共享测试的结果,这也是开源项目与闭源项目之间的一个很重要的差别。
几乎所有 Linux 内核开发者都是活跃的 Linux 用户。内核测试人员不一定非得是内核开发者,相反,用户和开发者如果对新增的代码不是很熟悉,他们的测试效果会比代码开发人员自己测试的效果要好很多。也就是说,开发者的单元自测能验证软件的功能,但并不能保证在其他代码、其他功能、其他软件、硬件环境下面运行时会出现什么问题。开发者无法预料、也没有机会和资源来测试所有环境。因此,用户在 Linux 内核开发过程中起到非常重要的角色。
现在我们已经了解了持续集成测试的重要性,接下来我们会详细介绍测试的知识。但在此之前,我还是向你介绍一下开发的过程,以便让大家了解它是怎么工作的,以及如何把补丁打进内核主线。
全世界共有3000多个内核开发者为 Linux 内核贡献代码,每天都有新代码添加到内核,结果是大概2个月就能产生一个release ,包括几个稳定版和扩展稳定版。新功能的开发与已发布的稳定版集成测试流程在同时进行。
关于开发流程的详细描述,请参考[Greg Kroah-Hartman 的 Linux 内核开发的介绍][1]。
这份教程适合与初学者以及有经验的内核开发者,如果你想加入到内核开发者行列,那么它也适合你。有经验的开发人员可以跳过那些介绍基础测试和调试的章节。
这份教程介绍如何测试和调试 Linux 内核、工具、脚本以及在回归测试和集成测试中使用的调试机制。另外,本文还会介绍如何使用 git 把针对一个 bug 的补丁分离出来,再介绍把你的补丁提交到内核的邮件列表之前需要做些什么。我将会使用 Linux PM 作为测试它调试的对象。尽管本文讨论的是 Linux 内核,但是介绍的方法也适用于任何其他软件开发项目。
### 配置开发与测试的系统 ###
第一步,找一个满足你需求的开发环境,x86-64 是一个比较理想的选择,除非你必须用特别的架构。
第二步,安装 Linux 发行版,我推荐 Ubuntu,所以本教程会介绍基于 Ubuntu 的配置过程。你可以参考[如何使用 Ubuntu][2] 来安装一个 Ubuntu 系统。
在开发和测试环境,最好要保证你的 boot 分区有足够的空间来存放内核文件。你可以为 boot 分区留下 3GB 空间,或把 boot 分区直接放到根目录下,这样 boot 分区可以使用整个磁盘的空间。
安装好操作系统后,确保 root 用户可用,确保你的用户身份可以使用 sudo 命令。你的系统也许已经安装了 build-essential,它是编译内核必备的软件包,如果没安装,运行下面的命令:
sudo apt-get install build-essential
然后运行下面的命令,保证你的系统能够交叉编译内核。下面的 ncurses-dev 安装包是运行 make menuconfig 命令必须用到的。
sudo apt-get install binutils-multiarch
sudo apt-get install ncurses-dev
sudo apt-get install alien
然后安装一些每个内核开发者都会用到的工具包:
sudo apt-get install git
sudo apt-get install cscope
sudo apt-get install meld
sudo apt-get install gitk
如果你喜欢把内核通过交叉编译以支持非 x86_64 架构的环境,请参考[在 x86_64 上交叉编译 Linux 内核][3]。
### 稳定的内核 ###
使用 git 克隆一个稳定的内核,然后编译安装。你可以参考[Linux 内核结构][4]来找到最新的稳定版和开发主线。
git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
上面的步骤将会创建一个新的目录,名为 linux-stable,并把源码下载到里面。
你也可以直接下载压缩包并解压出源码,无需使用 git:
tar xvf linux-3.x.y.tar.xz
--------------------------------------------------------------------------------
via: http://www.linuxjournal.com/content/linux-kernel-testing-and-debugging?page=0,0
译者:[bazz2](https://github.com/bazz2) 校对:[wxy](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[1]:http://events.linuxfoundation.org/images/stories/pdf/als2012_gregkh.pdf
[2]:http://howtoubuntu.org/
[3]:http://linuxdriverproject.org/mediawiki/index.php/Cross-compiling_Linux_kernel_on_x86_64
[4]:https://www.kernel.org/
| strugglingyouth/TranslateProject | published/201408/20140718 Linux Kernel Testing and Debugging 1.md | Markdown | apache-2.0 | 5,789 |
为什么Flash不支持Linux对开源比较好
================================================================================
> Linux中开源软件Chromium浏览器对Adobe Flash的支持即将结束,这实际上对Linux世界是件好事。

Flash,这个无处不在的网络媒体框架,很快将不能在linux的[Chromium][1]浏览器中使用了。Chromium是开源版的[Google Chrome][2]浏览器。现在我们要为Linux世界恐慌了吗?答案是根本不用。
事情是这样的:Chromium对Flash支持的传统方法是通过使用最初设计用于Netscape浏览器的一个插件实现的,不过很快这个方法将[不能使用了][3]。取而代之的是,Flash支持将通过新的叫做Pepper的API而实现,这是Google为Chrome而制作的。
对于Linux用户,问题是Pepper只能用于Chrome,而不能用于其表兄弟Chromium。虽然在技术上可以使Pepper在Chromium上使用,但需要你比一般Linux用户拥有更多的知识才能搞定。
这对Linux世界来说是个坏消息,根据[一个统计数据][4]称,有近一半的Linux用户在使用Chromium。在Linux上的其他浏览器,对Flash的支持将在Flash 11.2版本结束,现在它仍然能够良好工作,但是将来可能就不能使用了。这就是说,不久,不论Chromium还是Firefox或者他们的分支或其他的开源软件,将不能可靠地显示基于Flash的内容。
但到目前为止,很少有人对此事感到恐慌,事实上他们确实不应该恐慌。从很多方面来说,Flash对Linux不再支持实际上是件好事,因为这将有助于加速Flash的完全消失。毕竟,就如Jim Lynch在IT World上[写的][5],苹果iOS从没有过Flash支持,但这并没有阻碍iPads或iPhones变得的极为流行。尤其是一些技术如HTML5使得在提供网络内容时不必使用Flash。
这件事情里,拒绝支持一个特定的软件包,从长远来看对于Linux社区和更大范畴的IT世界更有好处。这种情况很少见,但当发生在Flash上时,Linux不支持的确是件好事。
--------------------------------------------------------------------------------
via: http://thevarguy.com/open-source-application-software-companies/052814/why-no-flash-support-linux-good-open-source
译者:[linuhap](https://github.com/linuhap) 校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[1]:http://www.chromium.org/
[2]:https://www.google.com/intl/en-US/chrome/browser/
[3]:http://www.techrepublic.com/article/browsers-will-flash-linux-into-the-future-or-drag-it-into-the-past/#.
[4]:http://www.techrepublic.com/article/browsers-will-flash-linux-into-the-future-or-drag-it-into-the-past/#.
[5]:http://www.itworld.com/open-source/420319/adobe-flash-critical-future-linux | geekpi/TranslateProject | published/201406/20140529 Why No Flash Support for Linux Is Good for Open Source.md | Markdown | apache-2.0 | 2,996 |
import numpy
from numpy.distutils.misc_util import Configuration
def configuration(parent_package="", top_path=None):
config = Configuration("ensemble", parent_package, top_path)
config.add_extension("_gradient_boosting",
sources=["_gradient_boosting.c"],
include_dirs=[numpy.get_include()])
config.add_subpackage("tests")
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().todict())
| valexandersaulys/airbnb_kaggle_contest | venv/lib/python3.4/site-packages/sklearn/ensemble/setup.py | Python | gpl-2.0 | 516 |
class Admin::AdminController < ApplicationController
before_filter :ensure_logged_in
before_filter :ensure_staff
def index
render nothing: true
end
protected
# this is not really necessary cause the routes are secure
def ensure_staff
raise Discourse::InvalidAccess.new unless current_user.staff?
end
end
| fs/open-core | spec/dummy/app/controllers/admin/admin_controller.rb | Ruby | gpl-2.0 | 333 |
/*
* Memory pools library, Public interface
*
* API Overview
*
* This package provides a memory allocation subsystem based on pools of
* homogenous objects.
*
* Instrumentation is available for reporting memory utilization both
* on a per-data-structure basis and system wide.
*
* There are two main types defined in this API.
*
* pool manager: A singleton object that acts as a factory for
* pool allocators. It also is used for global
* instrumentation, such as reporting all blocks
* in use across all data structures. The pool manager
* creates and provides individual memory pools
* upon request to application code.
*
* memory pool: An object for allocating homogenous memory blocks.
*
* Global identifiers in this module use the following prefixes:
* bcm_mpm_* Memory pool manager
* bcm_mp_* Memory pool
*
* There are two main types of memory pools:
*
* prealloc: The contiguous memory block of objects can either be supplied
* by the client or malloc'ed by the memory manager. The objects are
* allocated out of a block of memory and freed back to the block.
*
* heap: The memory pool allocator uses the heap (malloc/free) for memory.
* In this case, the pool allocator is just providing statistics
* and instrumentation on top of the heap, without modifying the heap
* allocation implementation.
*
* Copyright (C) 1999-2016, 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: bcm_mpool_pub.h 407097 2013-06-11 18:43:16Z $
*/
#ifndef _BCM_MPOOL_PUB_H
#define _BCM_MPOOL_PUB_H 1
#include <typedefs.h> /* needed for uint16 */
/*
**************************************************************************
*
* Type definitions, handles
*
**************************************************************************
*/
/* Forward declaration of OSL handle. */
struct osl_info;
/* Forward declaration of string buffer. */
struct bcmstrbuf;
/*
* Opaque type definition for the pool manager handle. This object is used for global
* memory pool operations such as obtaining a new pool, deleting a pool, iterating and
* instrumentation/debugging.
*/
struct bcm_mpm_mgr;
typedef struct bcm_mpm_mgr *bcm_mpm_mgr_h;
/*
* Opaque type definition for an instance of a pool. This handle is used for allocating
* and freeing memory through the pool, as well as management/instrumentation on this
* specific pool.
*/
struct bcm_mp_pool;
typedef struct bcm_mp_pool *bcm_mp_pool_h;
/*
* To make instrumentation more readable, every memory
* pool must have a readable name. Pool names are up to
* 8 bytes including '\0' termination. (7 printable characters.)
*/
#define BCM_MP_NAMELEN 8
/*
* Type definition for pool statistics.
*/
typedef struct bcm_mp_stats {
char name[BCM_MP_NAMELEN]; /* Name of this pool. */
unsigned int objsz; /* Object size allocated in this pool */
uint16 nobj; /* Total number of objects in this pool */
uint16 num_alloc; /* Number of objects currently allocated */
uint16 high_water; /* Max number of allocated objects. */
uint16 failed_alloc; /* Failed allocations. */
} bcm_mp_stats_t;
/*
**************************************************************************
*
* API Routines on the pool manager.
*
**************************************************************************
*/
/*
* bcm_mpm_init() - initialize the whole memory pool system.
*
* Parameters:
* osh: INPUT Operating system handle. Needed for heap memory allocation.
* max_pools: INPUT Maximum number of mempools supported.
* mgr: OUTPUT The handle is written with the new pools manager object/handle.
*
* Returns:
* BCME_OK Object initialized successfully. May be used.
* BCME_NOMEM Initialization failed due to no memory. Object must not be used.
*/
int bcm_mpm_init(struct osl_info *osh, int max_pools, bcm_mpm_mgr_h *mgrp);
/*
* bcm_mpm_deinit() - de-initialize the whole memory pool system.
*
* Parameters:
* mgr: INPUT Pointer to pool manager handle.
*
* Returns:
* BCME_OK Memory pool manager successfully de-initialized.
* other Indicated error occured during de-initialization.
*/
int bcm_mpm_deinit(bcm_mpm_mgr_h *mgrp);
/*
* bcm_mpm_create_prealloc_pool() - Create a new pool for fixed size objects. The
* pool uses a contiguous block of pre-alloced
* memory. The memory block may either be provided
* by the client or dynamically allocated by the
* pool manager.
*
* Parameters:
* mgr: INPUT The handle to the pool manager
* obj_sz: INPUT Size of objects that will be allocated by the new pool
* Must be >= sizeof(void *).
* nobj: INPUT Maximum number of concurrently existing objects to support
* memstart INPUT Pointer to the memory to use, or NULL to malloc()
* memsize INPUT Number of bytes referenced from memstart (for error checking).
* Must be 0 if 'memstart' is NULL.
* poolname INPUT For instrumentation, the name of the pool
* newp: OUTPUT The handle for the new pool, if creation is successful
*
* Returns:
* BCME_OK Pool created ok.
* other Pool not created due to indicated error. newpoolp set to NULL.
*
*
*/
int bcm_mpm_create_prealloc_pool(bcm_mpm_mgr_h mgr,
unsigned int obj_sz,
int nobj,
void *memstart,
unsigned int memsize,
const char poolname[BCM_MP_NAMELEN],
bcm_mp_pool_h *newp);
/*
* bcm_mpm_delete_prealloc_pool() - Delete a memory pool. This should only be called after
* all memory objects have been freed back to the pool.
*
* Parameters:
* mgr: INPUT The handle to the pools manager
* pool: INPUT The handle of the pool to delete
*
* Returns:
* BCME_OK Pool deleted ok.
* other Pool not deleted due to indicated error.
*
*/
int bcm_mpm_delete_prealloc_pool(bcm_mpm_mgr_h mgr, bcm_mp_pool_h *poolp);
/*
* bcm_mpm_create_heap_pool() - Create a new pool for fixed size objects. The memory
* pool allocator uses the heap (malloc/free) for memory.
* In this case, the pool allocator is just providing
* statistics and instrumentation on top of the heap,
* without modifying the heap allocation implementation.
*
* Parameters:
* mgr: INPUT The handle to the pool manager
* obj_sz: INPUT Size of objects that will be allocated by the new pool
* poolname INPUT For instrumentation, the name of the pool
* newp: OUTPUT The handle for the new pool, if creation is successful
*
* Returns:
* BCME_OK Pool created ok.
* other Pool not created due to indicated error. newpoolp set to NULL.
*
*
*/
int bcm_mpm_create_heap_pool(bcm_mpm_mgr_h mgr, unsigned int obj_sz,
const char poolname[BCM_MP_NAMELEN],
bcm_mp_pool_h *newp);
/*
* bcm_mpm_delete_heap_pool() - Delete a memory pool. This should only be called after
* all memory objects have been freed back to the pool.
*
* Parameters:
* mgr: INPUT The handle to the pools manager
* pool: INPUT The handle of the pool to delete
*
* Returns:
* BCME_OK Pool deleted ok.
* other Pool not deleted due to indicated error.
*
*/
int bcm_mpm_delete_heap_pool(bcm_mpm_mgr_h mgr, bcm_mp_pool_h *poolp);
/*
* bcm_mpm_stats() - Return stats for all pools
*
* Parameters:
* mgr: INPUT The handle to the pools manager
* stats: OUTPUT Array of pool statistics.
* nentries: MOD Max elements in 'stats' array on INPUT. Actual number
* of array elements copied to 'stats' on OUTPUT.
*
* Returns:
* BCME_OK Ok
* other Error getting stats.
*
*/
int bcm_mpm_stats(bcm_mpm_mgr_h mgr, bcm_mp_stats_t *stats, int *nentries);
/*
* bcm_mpm_dump() - Display statistics on all pools
*
* Parameters:
* mgr: INPUT The handle to the pools manager
* b: OUTPUT Output buffer.
*
* Returns:
* BCME_OK Ok
* other Error during dump.
*
*/
int bcm_mpm_dump(bcm_mpm_mgr_h mgr, struct bcmstrbuf *b);
/*
* bcm_mpm_get_obj_size() - The size of memory objects may need to be padded to
* compensate for alignment requirements of the objects.
* This function provides the padded object size. If clients
* pre-allocate a memory slab for a memory pool, the
* padded object size should be used by the client to allocate
* the memory slab (in order to provide sufficent space for
* the maximum number of objects).
*
* Parameters:
* mgr: INPUT The handle to the pools manager.
* obj_sz: INPUT Input object size.
* padded_obj_sz: OUTPUT Padded object size.
*
* Returns:
* BCME_OK Ok
* BCME_BADARG Bad arguments.
*
*/
int bcm_mpm_get_obj_size(bcm_mpm_mgr_h mgr, unsigned int obj_sz, unsigned int *padded_obj_sz);
/*
***************************************************************************
*
* API Routines on a specific pool.
*
***************************************************************************
*/
/*
* bcm_mp_alloc() - Allocate a memory pool object.
*
* Parameters:
* pool: INPUT The handle to the pool.
*
* Returns:
* A pointer to the new object. NULL on error.
*
*/
void* bcm_mp_alloc(bcm_mp_pool_h pool);
/*
* bcm_mp_free() - Free a memory pool object.
*
* Parameters:
* pool: INPUT The handle to the pool.
* objp: INPUT A pointer to the object to free.
*
* Returns:
* BCME_OK Ok
* other Error during free.
*
*/
int bcm_mp_free(bcm_mp_pool_h pool, void *objp);
/*
* bcm_mp_stats() - Return stats for this pool
*
* Parameters:
* pool: INPUT The handle to the pool
* stats: OUTPUT Pool statistics
*
* Returns:
* BCME_OK Ok
* other Error getting statistics.
*
*/
int bcm_mp_stats(bcm_mp_pool_h pool, bcm_mp_stats_t *stats);
/*
* bcm_mp_dump() - Dump a pool
*
* Parameters:
* pool: INPUT The handle to the pool
* b OUTPUT Output buffer
*
* Returns:
* BCME_OK Ok
* other Error during dump.
*
*/
int bcm_mp_dump(bcm_mp_pool_h pool, struct bcmstrbuf *b);
#endif /* _BCM_MPOOL_PUB_H */
| Exynos7580/android_kernel_samsung_j7elte | drivers/net/wireless/bcmdhd_mm/include/bcm_mpool_pub.h | C | gpl-2.0 | 12,067 |
#ifndef _VB_TABLE_
#define _VB_TABLE_
static struct SiS_MCLKData XGI340New_MCLKData[] = {
{0x16, 0x01, 0x01, 166},
{0x19, 0x02, 0x01, 124},
{0x7C, 0x08, 0x01, 200},
{0x79, 0x06, 0x01, 250},
{0x29, 0x01, 0x81, 301},
{0x5c, 0x23, 0x01, 166},
{0x5c, 0x23, 0x01, 166},
{0x5c, 0x23, 0x01, 166}
};
static struct SiS_MCLKData XGI27New_MCLKData[] = {
{0x5c, 0x23, 0x01, 166},
{0x19, 0x02, 0x01, 124},
{0x7C, 0x08, 0x80, 200},
{0x79, 0x06, 0x80, 250},
{0x29, 0x01, 0x81, 300},
{0x5c, 0x23, 0x01, 166},
{0x5c, 0x23, 0x01, 166},
{0x5c, 0x23, 0x01, 166}
};
static struct XGI_ECLKDataStruct XGI340_ECLKData[] = {
{0x5c, 0x23, 0x01, 166},
{0x55, 0x84, 0x01, 123},
{0x7C, 0x08, 0x01, 200},
{0x79, 0x06, 0x01, 250},
{0x29, 0x01, 0x81, 301},
{0x5c, 0x23, 0x01, 166},
{0x5c, 0x23, 0x01, 166},
{0x5c, 0x23, 0x01, 166}
};
static unsigned char XG27_SR13[4][8] = {
{0x35, 0x45, 0xb1, 0x00, 0x00, 0x00, 0x00, 0x00}, /* SR13 */
{0x41, 0x51, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00}, /* SR14 */
{0x32, 0x32, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00}, /* SR18 */
{0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00} /* SR1B */
};
static unsigned char XGI340_SR13[4][8] = {
{0x35, 0x45, 0xb1, 0x00, 0x00, 0x00, 0x00, 0x00}, /* SR13 */
{0x41, 0x51, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00}, /* SR14 */
{0x31, 0x42, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00}, /* SR18 */
{0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00} /* SR1B */
};
static unsigned char XGI340_cr41[24][8] = {
{0x20, 0x50, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 0 CR41 */
{0xc4, 0x40, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 1 CR8A */
{0xc4, 0x40, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 2 CR8B */
{0xb5, 0xa4, 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xf0, 0xf0, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x90, 0x90, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 5 CR68 */
{0x77, 0x77, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 6 CR69 */
{0x77, 0x77, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 7 CR6A */
{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 8 CR6D */
{0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 9 CR80 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 10 CR81 */
{0x88, 0xa8, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 11 CR82 */
{0x44, 0x44, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 12 CR85 */
{0x48, 0x48, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 13 CR86 */
{0x54, 0x54, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 14 CR90 */
{0x54, 0x54, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 15 CR91 */
{0x0a, 0x0a, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 16 CR92 */
{0x44, 0x44, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 17 CR93 */
{0x10, 0x10, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 18 CR94 */
{0x11, 0x11, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 19 CR95 */
{0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 20 CR96 */
{0xf0, 0xf0, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 21 CRC3 */
{0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 22 CRC4 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /* 23 CRC5 */
};
static unsigned char XGI27_cr41[24][8] = {
{0x20, 0x40, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 0 CR41 */
{0xC4, 0x40, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 1 CR8A */
{0xC4, 0x40, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 2 CR8B */
{0xB3, 0x13, 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 3 CR40[7],
CR99[2:0],
CR45[3:0]*/
{0xf0, 0xf5, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 4 CR59 */
{0x90, 0x90, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 5 CR68 */
{0x77, 0x67, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 6 CR69 */
{0x77, 0x77, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 7 CR6A */
{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 8 CR6D */
{0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 9 CR80 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 10 CR81 */
{0x88, 0xcc, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 11 CR82 */
{0x44, 0x88, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 12 CR85 */
{0x48, 0x88, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 13 CR86 */
{0x54, 0x32, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 14 CR90 */
{0x54, 0x33, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 15 CR91 */
{0x0a, 0x07, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 16 CR92 */
{0x44, 0x63, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 17 CR93 */
{0x10, 0x14, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 18 CR94 */
{0x11, 0x0B, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 19 CR95 */
{0x05, 0x22, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 20 CR96 */
{0xf0, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 21 CRC3 */
{0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}, /* 22 CRC4 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} /* 23 CRC5 */
};
static unsigned char XGI340_CR6B[8][4] = {
{0xaa, 0xaa, 0xaa, 0xaa},
{0xaa, 0xaa, 0xaa, 0xaa},
{0xaa, 0xaa, 0xaa, 0xaa},
{0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00}
};
static unsigned char XGI340_CR6E[8][4];
static unsigned char XGI340_CR6F[8][32];
static unsigned char XGI340_CR89[8][2];
/* CR47,CR48,CR49,CR4A,CR4B,CR4C,CR70,CR71,CR74,CR75,CR76,CR77 */
static unsigned char XGI340_AGPReg[12] = {
0x28, 0x23, 0x00, 0x20, 0x00, 0x20,
0x00, 0x05, 0xd0, 0x10, 0x10, 0x00
};
static unsigned char XGI340_SR16[4] = {0x03, 0x83, 0x03, 0x83};
static struct XGI_ExtStruct XGI330_EModeIDTable[] = {
{0x2e, 0x0a1b, 0x0306, 0x06, 0x05, 0x06},
{0x2f, 0x0a1b, 0x0305, 0x05, 0x05, 0x05},
{0x30, 0x2a1b, 0x0407, 0x07, 0x07, 0x0e},
{0x31, 0x0a1b, 0x030d, 0x0d, 0x06, 0x3d},
{0x32, 0x0a1b, 0x0a0e, 0x0e, 0x06, 0x3e},
{0x33, 0x0a1d, 0x0a0d, 0x0d, 0x06, 0x3d},
{0x34, 0x2a1d, 0x0a0e, 0x0e, 0x06, 0x3e},
{0x35, 0x0a1f, 0x0a0d, 0x0d, 0x06, 0x3d},
{0x36, 0x2a1f, 0x0a0e, 0x0e, 0x06, 0x3e},
{0x38, 0x0a1b, 0x0508, 0x08, 0x00, 0x16},
{0x3a, 0x0e3b, 0x0609, 0x09, 0x00, 0x1e},
{0x3c, 0x0e3b, 0x070a, 0x0a, 0x00, 0x22}, /* mode 1600x1200
add CRT2MODE [2003/10/07] */
{0x3d, 0x0e7d, 0x070a, 0x0a, 0x00, 0x22}, /* mode 1600x1200
add CRT2MODE */
{0x40, 0x9a1c, 0x0000, 0x00, 0x04, 0x00},
{0x41, 0x9a1d, 0x0000, 0x00, 0x04, 0x00},
{0x43, 0x0a1c, 0x0306, 0x06, 0x05, 0x06},
{0x44, 0x0a1d, 0x0306, 0x06, 0x05, 0x06},
{0x46, 0x2a1c, 0x0407, 0x07, 0x07, 0x0e},
{0x47, 0x2a1d, 0x0407, 0x07, 0x07, 0x0e},
{0x49, 0x0a3c, 0x0508, 0x08, 0x00, 0x16},
{0x4a, 0x0a3d, 0x0508, 0x08, 0x00, 0x16},
{0x4c, 0x0e7c, 0x0609, 0x09, 0x00, 0x1e},
{0x4d, 0x0e7d, 0x0609, 0x09, 0x00, 0x1e},
{0x50, 0x9a1b, 0x0001, 0x01, 0x04, 0x02},
{0x51, 0xba1b, 0x0103, 0x03, 0x07, 0x03},
{0x52, 0x9a1b, 0x0204, 0x04, 0x00, 0x04},
{0x56, 0x9a1d, 0x0001, 0x01, 0x04, 0x02},
{0x57, 0xba1d, 0x0103, 0x03, 0x07, 0x03},
{0x58, 0x9a1d, 0x0204, 0x04, 0x00, 0x04},
{0x59, 0x9a1b, 0x0000, 0x00, 0x04, 0x00},
{0x5A, 0x021b, 0x0014, 0x01, 0x04, 0x3f},
{0x5B, 0x0a1d, 0x0014, 0x01, 0x04, 0x3f},
{0x5d, 0x0a1d, 0x0305, 0x05, 0x07, 0x05},
{0x62, 0x0a3f, 0x0306, 0x06, 0x05, 0x06},
{0x63, 0x2a3f, 0x0407, 0x07, 0x07, 0x0e},
{0x64, 0x0a7f, 0x0508, 0x08, 0x00, 0x16},
{0x65, 0x0eff, 0x0609, 0x09, 0x00, 0x1e},
{0x66, 0x0eff, 0x070a, 0x0a, 0x00, 0x22}, /* mode 1600x1200
add CRT2MODE */
{0x68, 0x067b, 0x080b, 0x0b, 0x00, 0x29},
{0x69, 0x06fd, 0x080b, 0x0b, 0x00, 0x29},
{0x6b, 0x07ff, 0x080b, 0x0b, 0x00, 0x29},
{0x6c, 0x067b, 0x090c, 0x0c, 0x00, 0x2f},
{0x6d, 0x06fd, 0x090c, 0x0c, 0x00, 0x2f},
{0x6e, 0x07ff, 0x090c, 0x0c, 0x00, 0x2f},
{0x70, 0x2a1b, 0x0410, 0x10, 0x07, 0x34},
{0x71, 0x0a1b, 0x0511, 0x11, 0x00, 0x37},
{0x74, 0x0a1d, 0x0511, 0x11, 0x00, 0x37},
{0x75, 0x0a3d, 0x0612, 0x12, 0x00, 0x3a},
{0x76, 0x2a1f, 0x0410, 0x10, 0x07, 0x34},
{0x77, 0x0a1f, 0x0511, 0x11, 0x00, 0x37},
{0x78, 0x0a3f, 0x0612, 0x12, 0x00, 0x3a},
{0x79, 0x0a3b, 0x0612, 0x12, 0x00, 0x3a},
{0x7a, 0x2a1d, 0x0410, 0x10, 0x07, 0x34},
{0x7b, 0x0e3b, 0x060f, 0x0f, 0x00, 0x1d},
{0x7c, 0x0e7d, 0x060f, 0x0f, 0x00, 0x1d},
{0x7d, 0x0eff, 0x060f, 0x0f, 0x00, 0x1d},
{0x20, 0x0e3b, 0x0D16, 0x16, 0x00, 0x43},
{0x21, 0x0e7d, 0x0D16, 0x16, 0x00, 0x43},
{0x22, 0x0eff, 0x0D16, 0x16, 0x00, 0x43},
{0x23, 0x0e3b, 0x0614, 0x14, 0x00, 0x41},
{0x24, 0x0e7d, 0x0614, 0x14, 0x00, 0x41},
{0x25, 0x0eff, 0x0614, 0x14, 0x00, 0x41},
{0x26, 0x063b, 0x0c15, 0x15, 0x00, 0x42},
{0x27, 0x067d, 0x0c15, 0x15, 0x00, 0x42},
{0x28, 0x06ff, 0x0c15, 0x15, 0x00, 0x42},
{0xff, 0x0000, 0x0000, 0x00, 0x00, 0x00}
};
static struct SiS_StandTable_S XGI330_StandTable = {
/* ExtVGATable */
0x00, 0x00, 0x00, 0x0000,
{0x01, 0x0f, 0x00, 0x0e},
0x23,
{0x5f, 0x4f, 0x50, 0x82, 0x54, 0x80, 0x0b, 0x3e,
0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xea, 0x8c, 0xdf, 0x28, 0x40, 0xe7, 0x04, 0xa3,
0xff},
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x01, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x05, 0x0f,
0xff}
};
static struct XGI_TimingHStruct XGI_TimingH[1];
static struct XGI_TimingVStruct XGI_TimingV[1];
static struct XGI_XG21CRT1Struct XGI_UpdateCRT1Table[] = {
{0x01, 0x27, 0x91, 0x8f, 0xc0}, /* 00 */
{0x03, 0x4f, 0x83, 0x8f, 0xc0}, /* 01 */
{0x05, 0x27, 0x91, 0x8f, 0xc0}, /* 02 */
{0x06, 0x4f, 0x83, 0x8f, 0xc0}, /* 03 */
{0x07, 0x4f, 0x83, 0x8f, 0xc0}, /* 04 */
{0x0d, 0x27, 0x91, 0x8f, 0xc0}, /* 05 */
{0x0e, 0x4f, 0x83, 0x8f, 0xc0}, /* 06 */
{0x0f, 0x4f, 0x83, 0x5d, 0xc0}, /* 07 */
{0x10, 0x4f, 0x83, 0x5d, 0xc0}, /* 08 */
{0x11, 0x4f, 0x83, 0xdf, 0x0c}, /* 09 */
{0x12, 0x4f, 0x83, 0xdf, 0x0c}, /* 10 */
{0x13, 0x4f, 0x83, 0x8f, 0xc0}, /* 11 */
{0x2e, 0x4f, 0x83, 0xdf, 0x0c}, /* 12 */
{0x2e, 0x4f, 0x87, 0xdf, 0xc0}, /* 13 */
{0x2f, 0x4f, 0x83, 0x8f, 0xc0}, /* 14 */
{0x50, 0x27, 0x91, 0xdf, 0x0c}, /* 15 */
{0x59, 0x27, 0x91, 0x8f, 0xc0} /* 16 */
};
static struct XGI_CRT1TableStruct XGI_CRT1Table[] = {
{ {0x2d, 0x28, 0x90, 0x2c, 0x90, 0x00, 0x04, 0x00,
0xbf, 0x1f, 0x9c, 0x8e, 0x96, 0xb9, 0x30} }, /* 0x0 */
{ {0x2d, 0x28, 0x90, 0x2c, 0x90, 0x00, 0x04, 0x00,
0x0b, 0x3e, 0xe9, 0x8b, 0xe7, 0x04, 0x00} }, /* 0x1 */
{ {0x3D, 0x31, 0x81, 0x37, 0x1F, 0x00, 0x05, 0x00,
0x72, 0xF0, 0x58, 0x8C, 0x57, 0x73, 0xA0} }, /* 0x2 */
{ {0x4F, 0x3F, 0x93, 0x45, 0x0D, 0x00, 0x01, 0x00,
0x24, 0xF5, 0x02, 0x88, 0xFF, 0x25, 0x90} }, /* 0x3 */
{ {0x5F, 0x50, 0x82, 0x55, 0x81, 0x00, 0x05, 0x00,
0xBF, 0x1F, 0x9C, 0x8E, 0x96, 0xB9, 0x30} }, /* 0x4 */
{ {0x5F, 0x50, 0x82, 0x55, 0x81, 0x00, 0x05, 0x00,
0x0B, 0x3E, 0xE9, 0x8B, 0xE7, 0x04, 0x00} }, /* 0x5 */
{ {0x63, 0x50, 0x86, 0x56, 0x9B, 0x00, 0x01, 0x00,
0x06, 0x3E, 0xE8, 0x8B, 0xE7, 0xFF, 0x10} }, /* 0x6 */
{ {0x64, 0x4F, 0x88, 0x55, 0x9D, 0x00, 0x01, 0x00,
0xF2, 0x1F, 0xE0, 0x83, 0xDF, 0xF3, 0x10} }, /* 0x7 */
{ {0x63, 0x4F, 0x87, 0x5A, 0x81, 0x00, 0x05, 0x00,
0xFB, 0x1F, 0xE0, 0x83, 0xDF, 0xFC, 0x10} }, /* 0x8 */
{ {0x65, 0x4F, 0x89, 0x58, 0x80, 0x00, 0x05, 0x60,
0xFB, 0x1F, 0xE0, 0x83, 0xDF, 0xFC, 0x80} }, /* 0x9 */
{ {0x65, 0x4F, 0x89, 0x58, 0x80, 0x00, 0x05, 0x60,
0x01, 0x3E, 0xE0, 0x83, 0xDF, 0x02, 0x80} }, /* 0xa */
{ {0x67, 0x4F, 0x8B, 0x58, 0x81, 0x00, 0x05, 0x60,
0x0D, 0x3E, 0xE0, 0x83, 0xDF, 0x0E, 0x90} }, /* 0xb */
{ {0x65, 0x4F, 0x89, 0x57, 0x9F, 0x00, 0x01, 0x00,
0xFB, 0x1F, 0xE6, 0x8A, 0xDF, 0xFC, 0x10} }, /* 0xc */
{ {0x7B, 0x63, 0x9F, 0x6A, 0x93, 0x00, 0x05, 0x00, /* ;
0D (800x600,56Hz) */
0x6F, 0xF0, 0x58, 0x8A, 0x57, 0x70, 0xA0} }, /* ;
(VCLK 36.0MHz) */
{ {0x7F, 0x63, 0x83, 0x6C, 0x1C, 0x00, 0x06, 0x00, /* ;
0E (800x600,60Hz) */
0x72, 0xF0, 0x58, 0x8C, 0x57, 0x73, 0xA0} }, /* ;
(VCLK 40.0MHz) */
{ {0x7D, 0x63, 0x81, 0x6E, 0x1D, 0x00, 0x06, 0x00, /* ;
0F (800x600,72Hz) */
0x98, 0xF0, 0x7C, 0x82, 0x57, 0x99, 0x80} }, /* ;
(VCLK 50.0MHz) */
{ {0x7F, 0x63, 0x83, 0x69, 0x13, 0x00, 0x06, 0x00, /* ;
10 (800x600,75Hz) */
0x6F, 0xF0, 0x58, 0x8B, 0x57, 0x70, 0xA0} }, /* ;
(VCLK 49.5MHz) */
{ {0x7E, 0x63, 0x82, 0x6B, 0x13, 0x00, 0x06, 0x00, /* ;
11 (800x600,85Hz) */
0x75, 0xF0, 0x58, 0x8B, 0x57, 0x76, 0xA0} }, /* ;
(VCLK 56.25MHz) */
{ {0x81, 0x63, 0x85, 0x6D, 0x18, 0x00, 0x06, 0x60, /* ;
12 (800x600,100Hz) */
0x7A, 0xF0, 0x58, 0x8B, 0x57, 0x7B, 0xA0} }, /* ;
(VCLK 75.8MHz) */
{ {0x83, 0x63, 0x87, 0x6E, 0x19, 0x00, 0x06, 0x60, /* ;
13 (800x600,120Hz) */
0x81, 0xF0, 0x58, 0x8B, 0x57, 0x82, 0xA0} }, /* ;
(VCLK 79.411MHz) */
{ {0x85, 0x63, 0x89, 0x6F, 0x1A, 0x00, 0x06, 0x60, /* ;
14 (800x600,160Hz) */
0x91, 0xF0, 0x58, 0x8B, 0x57, 0x92, 0xA0} }, /* ;
(VCLK 105.822MHz) */
{ {0x99, 0x7F, 0x9D, 0x84, 0x1A, 0x00, 0x02, 0x00,
0x96, 0x1F, 0x7F, 0x83, 0x7F, 0x97, 0x10} }, /* 0x15 */
{ {0xA3, 0x7F, 0x87, 0x86, 0x97, 0x00, 0x02, 0x00,
0x24, 0xF5, 0x02, 0x88, 0xFF, 0x25, 0x90} }, /* 0x16 */
{ {0xA1, 0x7F, 0x85, 0x86, 0x97, 0x00, 0x02, 0x00,
0x24, 0xF5, 0x02, 0x88, 0xFF, 0x25, 0x90} }, /* 0x17 */
{ {0x9F, 0x7F, 0x83, 0x85, 0x91, 0x00, 0x02, 0x00,
0x1E, 0xF5, 0x00, 0x83, 0xFF, 0x1F, 0x90} }, /* 0x18 */
{ {0xA7, 0x7F, 0x8B, 0x89, 0x95, 0x00, 0x02, 0x00,
0x26, 0xF5, 0x00, 0x83, 0xFF, 0x27, 0x90} }, /* 0x19 */
{ {0xA9, 0x7F, 0x8D, 0x8C, 0x9A, 0x00, 0x02, 0x62,
0x2C, 0xF5, 0x00, 0x83, 0xFF, 0x2D, 0x14} }, /* 0x1a */
{ {0xAB, 0x7F, 0x8F, 0x8D, 0x9B, 0x00, 0x02, 0x62,
0x35, 0xF5, 0x00, 0x83, 0xFF, 0x36, 0x14} }, /* 0x1b */
{ {0xCF, 0x9F, 0x93, 0xB2, 0x01, 0x00, 0x03, 0x00,
0x14, 0xBA, 0x00, 0x83, 0xFF, 0x15, 0x00} }, /* 0x1c */
{ {0xCE, 0x9F, 0x92, 0xA9, 0x17, 0x00, 0x07, 0x00,
0x28, 0x5A, 0x00, 0x83, 0xFF, 0x29, 0x89} }, /* 0x1d */
{ {0xCE, 0x9F, 0x92, 0xA5, 0x17, 0x00, 0x07, 0x00,
0x28, 0x5A, 0x00, 0x83, 0xFF, 0x29, 0x89} }, /* 0x1e */
{ {0xD3, 0x9F, 0x97, 0xAB, 0x1F, 0x00, 0x07, 0x00,
0x2E, 0x5A, 0x00, 0x83, 0xFF, 0x2F, 0x89} }, /* 0x1f */
{ {0x09, 0xC7, 0x8D, 0xD3, 0x0B, 0x01, 0x04, 0x00,
0xE0, 0x10, 0xB0, 0x83, 0xAF, 0xE1, 0x2F} }, /* 0x20 */
{ {0x09, 0xC7, 0x8D, 0xD3, 0x0B, 0x01, 0x04, 0x00,
0xE0, 0x10, 0xB0, 0x83, 0xAF, 0xE1, 0x2F} }, /* 0x21 */
{ {0x09, 0xC7, 0x8D, 0xD3, 0x0B, 0x01, 0x04, 0x00,
0xE0, 0x10, 0xB0, 0x83, 0xAF, 0xE1, 0x2F} }, /* 0x22 */
{ {0x09, 0xC7, 0x8D, 0xD3, 0x0B, 0x01, 0x04, 0x00,
0xE0, 0x10, 0xB0, 0x83, 0xAF, 0xE1, 0x2F} }, /* 0x23 */
{ {0x09, 0xC7, 0x8D, 0xD3, 0x0B, 0x01, 0x04, 0x00,
0xE0, 0x10, 0xB0, 0x83, 0xAF, 0xE1, 0x2F} }, /* 0x24 */
{ {0x09, 0xC7, 0x8D, 0xD3, 0x0B, 0x01, 0x04, 0x00,
0xE0, 0x10, 0xB0, 0x83, 0xAF, 0xE1, 0x2F} }, /* 0x25 */
{ {0x09, 0xC7, 0x8D, 0xD3, 0x0B, 0x01, 0x04, 0x00,
0xE0, 0x10, 0xB0, 0x83, 0xAF, 0xE1, 0x2F} }, /* 0x26 */
{ {0x40, 0xEF, 0x84, 0x03, 0x1D, 0x41, 0x01, 0x00,
0xDA, 0x1F, 0xA0, 0x83, 0x9F, 0xDB, 0x1F} }, /* 0x27 */
{ {0x43, 0xEF, 0x87, 0x06, 0x00, 0x41, 0x05, 0x62,
0xD4, 0x1F, 0xA0, 0x83, 0x9F, 0xD5, 0x9F} }, /* 0x28 */
{ {0x45, 0xEF, 0x89, 0x07, 0x01, 0x41, 0x05, 0x62,
0xD9, 0x1F, 0xA0, 0x83, 0x9F, 0xDA, 0x9F} }, /* 0x29 */
{ {0x40, 0xEF, 0x84, 0x03, 0x1D, 0x41, 0x01, 0x00,
0xDA, 0x1F, 0xA0, 0x83, 0x9F, 0xDB, 0x1F} }, /* 0x2a */
{ {0x40, 0xEF, 0x84, 0x03, 0x1D, 0x41, 0x01, 0x00,
0xDA, 0x1F, 0xA0, 0x83, 0x9F, 0xDB, 0x1F} }, /* 0x2b */
{ {0x40, 0xEF, 0x84, 0x03, 0x1D, 0x41, 0x01, 0x00,
0xDA, 0x1F, 0xA0, 0x83, 0x9F, 0xDB, 0x1F} }, /* 0x2c */
{ {0x59, 0xFF, 0x9D, 0x17, 0x13, 0x41, 0x05, 0x44,
0x33, 0xBA, 0x00, 0x83, 0xFF, 0x34, 0x0F} }, /* 0x2d */
{ {0x5B, 0xFF, 0x9F, 0x18, 0x14, 0x41, 0x05, 0x44,
0x38, 0xBA, 0x00, 0x83, 0xFF, 0x39, 0x0F} }, /* 0x2e */
{ {0x5B, 0xFF, 0x9F, 0x18, 0x14, 0x41, 0x05, 0x44,
0x3D, 0xBA, 0x00, 0x83, 0xFF, 0x3E, 0x0F} }, /* 0x2f */
{ {0x5D, 0xFF, 0x81, 0x19, 0x95, 0x41, 0x05, 0x44,
0x41, 0xBA, 0x00, 0x84, 0xFF, 0x42, 0x0F} }, /* 0x30 */
{ {0x55, 0xFF, 0x99, 0x0D, 0x0C, 0x41, 0x05, 0x00,
0x3E, 0xBA, 0x00, 0x84, 0xFF, 0x3F, 0x0F} }, /* 0x31 */
{ {0x7F, 0x63, 0x83, 0x6C, 0x1C, 0x00, 0x06, 0x00,
0x72, 0xBA, 0x27, 0x8B, 0xDF, 0x73, 0x80} }, /* 0x32 */
{ {0x7F, 0x63, 0x83, 0x69, 0x13, 0x00, 0x06, 0x00,
0x6F, 0xBA, 0x26, 0x89, 0xDF, 0x6F, 0x80} }, /* 0x33 */
{ {0x7F, 0x63, 0x82, 0x6B, 0x13, 0x00, 0x06, 0x00,
0x75, 0xBA, 0x29, 0x8C, 0xDF, 0x75, 0x80} }, /* 0x34 */
{ {0xA3, 0x7F, 0x87, 0x86, 0x97, 0x00, 0x02, 0x00,
0x24, 0xF1, 0xAF, 0x85, 0x3F, 0x25, 0xB0} }, /* 0x35 */
{ {0x9F, 0x7F, 0x83, 0x85, 0x91, 0x00, 0x02, 0x00,
0x1E, 0xF1, 0xAD, 0x81, 0x3F, 0x1F, 0xB0} }, /* 0x36 */
{ {0xA7, 0x7F, 0x88, 0x89, 0x15, 0x00, 0x02, 0x00,
0x26, 0xF1, 0xB1, 0x85, 0x3F, 0x27, 0xB0} }, /* 0x37 */
{ {0xCE, 0x9F, 0x92, 0xA9, 0x17, 0x00, 0x07, 0x00,
0x28, 0xC4, 0x7A, 0x8E, 0xCF, 0x29, 0xA1} }, /* 0x38 */
{ {0xCE, 0x9F, 0x92, 0xA5, 0x17, 0x00, 0x07, 0x00,
0x28, 0xD4, 0x7A, 0x8E, 0xCF, 0x29, 0xA1} }, /* 0x39 */
{ {0xD3, 0x9F, 0x97, 0xAB, 0x1F, 0x00, 0x07, 0x00,
0x2E, 0xD4, 0x7D, 0x81, 0xCF, 0x2F, 0xA1} }, /* 0x3a */
{ {0xDC, 0x9F, 0x00, 0xAB, 0x19, 0x00, 0x07, 0x00,
0xE6, 0xEF, 0xC0, 0xC3, 0xBF, 0xE7, 0x90} }, /* 0x3b */
{ {0x6B, 0x59, 0x8F, 0x5E, 0x8C, 0x00, 0x05, 0x00,
0x0B, 0x3E, 0xE9, 0x8B, 0xE7, 0x04, 0x00} }, /* 0x3c */
{ {0x7B, 0x63, 0x9F, 0x6A, 0x93, 0x00, 0x05, 0x00,
0x6F, 0xF0, 0x58, 0x8A, 0x57, 0x70, 0xA0} }, /* 0x3d */
{ {0x86, 0x6A, 0x8a, 0x74, 0x06, 0x00, 0x02, 0x00,
0x8c, 0x15, 0x4f, 0x83, 0xef, 0x8d, 0x30} }, /* 0x3e */
{ {0x81, 0x6A, 0x85, 0x70, 0x00, 0x00, 0x02, 0x00,
0x0f, 0x3e, 0xeb, 0x8e, 0xdf, 0x10, 0x00} }, /* 0x3f */
{ {0xCE, 0x9F, 0x92, 0xA9, 0x17, 0x00, 0x07, 0x00,
0x20, 0xF5, 0x03, 0x88, 0xFF, 0x21, 0x90} }, /* 0x40 */
{ {0xE6, 0xAE, 0x8A, 0xBD, 0x90, 0x00, 0x03, 0x00,
0x3D, 0x10, 0x1A, 0x8D, 0x19, 0x3E, 0x2F} }, /* 0x41 */
{ {0xB9, 0x8F, 0x9D, 0x9B, 0x8A, 0x00, 0x06, 0x00,
0x7D, 0xFF, 0x60, 0x83, 0x5F, 0x7E, 0x90} }, /* 0x42 */
{ {0xC3, 0x8F, 0x87, 0x9B, 0x0B, 0x00, 0x07, 0x00,
0x82, 0xFF, 0x60, 0x83, 0x5F, 0x83, 0x90} }, /* 0x43 */
{ {0xAD, 0x7F, 0x91, 0x8E, 0x9C, 0x00, 0x02, 0x82,
0x49, 0xF5, 0x00, 0x83, 0xFF, 0x4A, 0x90} }, /* 0x44 */
{ {0xCD, 0x9F, 0x91, 0xA7, 0x19, 0x00, 0x07, 0x60,
0xE6, 0xFF, 0xC0, 0x83, 0xBF, 0xE7, 0x90} }, /* 0x45 */
{ {0xD3, 0x9F, 0x97, 0xAB, 0x1F, 0x00, 0x07, 0x60,
0xF1, 0xFF, 0xC0, 0x83, 0xBF, 0xF2, 0x90} }, /* 0x46 */
{ {0xD7, 0x9F, 0x9B, 0xAC, 0x1E, 0x00, 0x07, 0x00,
0x03, 0xDE, 0xC0, 0x84, 0xBF, 0x04, 0x90} } /* 0x47 */
};
static unsigned char XGI_CH7017LV1024x768[] = {
0x60, 0x02, 0x00, 0x07, 0x40, 0xED,
0xA3, 0xC8, 0xC7, 0xAC, 0xE0, 0x02};
static unsigned char XGI_CH7017LV1400x1050[] = {
0x60, 0x03, 0x11, 0x00, 0x40, 0xE3,
0xAD, 0xDB, 0xF6, 0xAC, 0xE0, 0x02};
/*add for new UNIVGABIOS*/
static struct SiS_LCDData XGI_StLCD1024x768Data[] = {
{62, 25, 800, 546, 1344, 806},
{32, 15, 930, 546, 1344, 806},
{62, 25, 800, 546, 1344, 806}, /*chiawenfordot9->dot8*/
{104, 45, 945, 496, 1344, 806},
{62, 25, 800, 546, 1344, 806},
{31, 18, 1008, 624, 1344, 806},
{1, 1, 1344, 806, 1344, 806}
};
static struct SiS_LCDData XGI_ExtLCD1024x768Data[] = {
{42, 25, 1536, 419, 1344, 806},
{48, 25, 1536, 369, 1344, 806},
{42, 25, 1536, 419, 1344, 806},
{48, 25, 1536, 369, 1344, 806},
{12, 5, 896, 500, 1344, 806},
{42, 25, 1024, 625, 1344, 806},
{1, 1, 1344, 806, 1344, 806},
{12, 5, 896, 500, 1344, 806},
{42, 25, 1024, 625, 1344, 806},
{1, 1, 1344, 806, 1344, 806},
{12, 5, 896, 500, 1344, 806},
{42, 25, 1024, 625, 1344, 806},
{1, 1, 1344, 806, 1344, 806}
};
static struct SiS_LCDData XGI_CetLCD1024x768Data[] = {
{1, 1, 1344, 806, 1344, 806}, /* ; 00 (320x200,320x400,
640x200,640x400) */
{1, 1, 1344, 806, 1344, 806}, /* 01 (320x350,640x350) */
{1, 1, 1344, 806, 1344, 806}, /* 02 (360x400,720x400) */
{1, 1, 1344, 806, 1344, 806}, /* 03 (720x350) */
{1, 1, 1344, 806, 1344, 806}, /* 04 (640x480x60Hz) */
{1, 1, 1344, 806, 1344, 806}, /* 05 (800x600x60Hz) */
{1, 1, 1344, 806, 1344, 806} /* 06 (1024x768x60Hz) */
};
static struct SiS_LCDData XGI_StLCD1280x1024Data[] = {
{22, 5, 800, 510, 1650, 1088},
{22, 5, 800, 510, 1650, 1088},
{176, 45, 900, 510, 1650, 1088},
{176, 45, 900, 510, 1650, 1088},
{22, 5, 800, 510, 1650, 1088},
{13, 5, 1024, 675, 1560, 1152},
{16, 9, 1266, 804, 1688, 1072},
{1, 1, 1688, 1066, 1688, 1066}
};
static struct SiS_LCDData XGI_ExtLCD1280x1024Data[] = {
{211, 60, 1024, 501, 1688, 1066},
{211, 60, 1024, 508, 1688, 1066},
{211, 60, 1024, 501, 1688, 1066},
{211, 60, 1024, 508, 1688, 1066},
{211, 60, 1024, 500, 1688, 1066},
{211, 75, 1024, 625, 1688, 1066},
{211, 120, 1280, 798, 1688, 1066},
{1, 1, 1688, 1066, 1688, 1066}
};
static struct SiS_LCDData XGI_CetLCD1280x1024Data[] = {
{1, 1, 1688, 1066, 1688, 1066}, /* 00 (320x200,320x400,
640x200,640x400) */
{1, 1, 1688, 1066, 1688, 1066}, /* 01 (320x350,640x350) */
{1, 1, 1688, 1066, 1688, 1066}, /* 02 (360x400,720x400) */
{1, 1, 1688, 1066, 1688, 1066}, /* 03 (720x350) */
{1, 1, 1688, 1066, 1688, 1066}, /* 04 (640x480x60Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* 05 (800x600x60Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* 06 (1024x768x60Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* 07 (1280x1024x60Hz) */
{1, 1, 1688, 1066, 1688, 1066} /* 08 (1400x1050x60Hz) */
};
static struct SiS_LCDData xgifb_lcd_1400x1050[] = {
{211, 100, 2100, 408, 1688, 1066}, /* 00 (320x200,320x400,
640x200,640x400) */
{211, 64, 1536, 358, 1688, 1066}, /* 01 (320x350,640x350) */
{211, 100, 2100, 408, 1688, 1066}, /* 02 (360x400,720x400) */
{211, 64, 1536, 358, 1688, 1066}, /* 03 (720x350) */
{211, 48, 840, 488, 1688, 1066}, /* 04 (640x480x60Hz) */
{211, 72, 1008, 609, 1688, 1066}, /* 05 (800x600x60Hz) */
{211, 128, 1400, 776, 1688, 1066}, /* 06 (1024x768x60Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* 07 (1280x1024x60Hz
w/o Scaling) */
{1, 1, 1688, 1066, 1688, 1066} /* 08 (1400x1050x60Hz) */
};
static struct SiS_LCDData XGI_ExtLCD1600x1200Data[] = {
{4, 1, 1620, 420, 2160, 1250}, /* 00 (320x200,320x400,
640x200,640x400)*/
{27, 7, 1920, 375, 2160, 1250}, /* 01 (320x350,640x350) */
{4, 1, 1620, 420, 2160, 1250}, /* 02 (360x400,720x400)*/
{27, 7, 1920, 375, 2160, 1250}, /* 03 (720x350) */
{27, 4, 800, 500, 2160, 1250}, /* 04 (640x480x60Hz) */
{4, 1, 1080, 625, 2160, 1250}, /* 05 (800x600x60Hz) */
{5, 2, 1350, 800, 2160, 1250}, /* 06 (1024x768x60Hz) */
{27, 16, 1500, 1064, 2160, 1250}, /* 07 (1280x1024x60Hz) */
{9, 7, 1920, 1106, 2160, 1250}, /* 08 (1400x1050x60Hz) */
{1, 1, 2160, 1250, 2160, 1250} /* 09 (1600x1200x60Hz) ;302lv */
};
static struct SiS_LCDData XGI_StLCD1600x1200Data[] = {
{27, 4, 800, 500, 2160, 1250}, /* 00 (320x200,320x400,
640x200,640x400) */
{27, 4, 800, 500, 2160, 1250}, /* 01 (320x350,640x350) */
{27, 4, 800, 500, 2160, 1250}, /* 02 (360x400,720x400) */
{27, 4, 800, 500, 2160, 1250}, /* 03 (720x350) */
{27, 4, 800, 500, 2160, 1250}, /* 04 (320x240,640x480) */
{4, 1, 1080, 625, 2160, 1250}, /* 05 (400x300,800x600) */
{5, 2, 1350, 800, 2160, 1250}, /* 06 (512x384,1024x768) */
{135, 88, 1600, 1100, 2160, 1250}, /* 07 (1280x1024) */
{1, 1, 1800, 1500, 2160, 1250}, /* 08 (1400x1050) */
{1, 1, 2160, 1250, 2160, 1250} /* 09 (1600x1200) */
};
static struct SiS_LCDData XGI_CetLCD1400x1050Data[] = {
{1, 1, 1688, 1066, 1688, 1066}, /* 00 (320x200,320x400,
640x200,640x400) */
{1, 1, 1688, 1066, 1688, 1066}, /* 01 (320x350,640x350) */
{1, 1, 1688, 1066, 1688, 1066}, /* 02 (360x400,720x400) */
{1, 1, 1688, 1066, 1688, 1066}, /* 03 (720x350) */
{1, 1, 1688, 1066, 1688, 1066}, /* 04 (640x480x60Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* 05 (800x600x60Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* 06 (1024x768x60Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* 07 (1280x1024x60Hz) */
{1, 1, 1688, 1066, 1688, 1066} /* 08 (1400x1050x60Hz) */
};
static struct SiS_LCDData XGI_NoScalingData[] = {
{1, 1, 800, 449, 800, 449},
{1, 1, 800, 449, 800, 449},
{1, 1, 900, 449, 900, 449},
{1, 1, 900, 449, 900, 449},
{1, 1, 800, 525, 800, 525},
{1, 1, 1056, 628, 1056, 628},
{1, 1, 1344, 806, 1344, 806},
{1, 1, 1688, 1066, 1688, 1066}
};
static struct SiS_LCDData XGI_ExtLCD1024x768x75Data[] = {
{42, 25, 1536, 419, 1344, 806}, /* ; 00 (320x200,320x400,
640x200,640x400) */
{48, 25, 1536, 369, 1344, 806}, /* ; 01 (320x350,640x350) */
{42, 25, 1536, 419, 1344, 806}, /* ; 02 (360x400,720x400) */
{48, 25, 1536, 369, 1344, 806}, /* ; 03 (720x350) */
{8, 5, 1312, 500, 1312, 800}, /* ; 04 (640x480x75Hz) */
{41, 25, 1024, 625, 1312, 800}, /* ; 05 (800x600x75Hz) */
{1, 1, 1312, 800, 1312, 800} /* ; 06 (1024x768x75Hz) */
};
static struct SiS_LCDData XGI_CetLCD1024x768x75Data[] = {
{1, 1, 1312, 800, 1312, 800}, /* ; 00 (320x200,320x400,
640x200,640x400) */
{1, 1, 1312, 800, 1312, 800}, /* ; 01 (320x350,640x350) */
{1, 1, 1312, 800, 1312, 800}, /* ; 02 (360x400,720x400) */
{1, 1, 1312, 800, 1312, 800}, /* ; 03 (720x350) */
{1, 1, 1312, 800, 1312, 800}, /* ; 04 (640x480x75Hz) */
{1, 1, 1312, 800, 1312, 800}, /* ; 05 (800x600x75Hz) */
{1, 1, 1312, 800, 1312, 800} /* ; 06 (1024x768x75Hz) */
};
static struct SiS_LCDData xgifb_lcd_1280x1024x75[] = {
{211, 60, 1024, 501, 1688, 1066}, /* ; 00 (320x200,320x400,
640x200,640x400) */
{211, 60, 1024, 508, 1688, 1066}, /* ; 01 (320x350,640x350) */
{211, 60, 1024, 501, 1688, 1066}, /* ; 02 (360x400,720x400) */
{211, 60, 1024, 508, 1688, 1066}, /* ; 03 (720x350) */
{211, 45, 768, 498, 1688, 1066}, /* ; 04 (640x480x75Hz) */
{211, 75, 1024, 625, 1688, 1066}, /* ; 05 (800x600x75Hz) */
{211, 120, 1280, 798, 1688, 1066}, /* ; 06 (1024x768x75Hz) */
{1, 1, 1688, 1066, 1688, 1066} /* ; 07 (1280x1024x75Hz) */
};
static struct SiS_LCDData XGI_CetLCD1280x1024x75Data[] = {
{1, 1, 1688, 1066, 1688, 1066}, /* ; 00 (320x200,320x400,
640x200,640x400) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 01 (320x350,640x350) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 02 (360x400,720x400) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 03 (720x350) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 04 (640x480x75Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 05 (800x600x75Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 06 (1024x768x75Hz) */
{1, 1, 1688, 1066, 1688, 1066} /* ; 07 (1280x1024x75Hz) */
};
static struct SiS_LCDData XGI_NoScalingDatax75[] = {
{1, 1, 800, 449, 800, 449}, /* ; 00 (320x200, 320x400,
640x200, 640x400) */
{1, 1, 800, 449, 800, 449}, /* ; 01 (320x350, 640x350) */
{1, 1, 900, 449, 900, 449}, /* ; 02 (360x400, 720x400) */
{1, 1, 900, 449, 900, 449}, /* ; 03 (720x350) */
{1, 1, 840, 500, 840, 500}, /* ; 04 (640x480x75Hz) */
{1, 1, 1056, 625, 1056, 625}, /* ; 05 (800x600x75Hz) */
{1, 1, 1312, 800, 1312, 800}, /* ; 06 (1024x768x75Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 07 (1280x1024x75Hz) */
{1, 1, 1688, 1066, 1688, 1066}, /* ; 08 (1400x1050x75Hz)*/
{1, 1, 2160, 1250, 2160, 1250}, /* ; 09 (1600x1200x75Hz) */
{1, 1, 1688, 806, 1688, 806} /* ; 0A (1280x768x75Hz) */
};
static struct XGI_LCDDesStruct XGI_ExtLCDDes1024x768Data[] = {
{9, 1057, 0, 771}, /* ; 00 (320x200,320x400,640x200,640x400) */
{9, 1057, 0, 771}, /* ; 01 (320x350,640x350) */
{9, 1057, 0, 771}, /* ; 02 (360x400,720x400) */
{9, 1057, 0, 771}, /* ; 03 (720x350) */
{9, 1057, 0, 771}, /* ; 04 (640x480x60Hz) */
{9, 1057, 0, 771}, /* ; 05 (800x600x60Hz) */
{9, 1057, 805, 770} /* ; 06 (1024x768x60Hz) */
};
static struct XGI_LCDDesStruct XGI_StLCDDes1024x768Data[] = {
{9, 1057, 737, 703}, /* ; 00 (320x200,320x400,640x200,640x400) */
{9, 1057, 686, 651}, /* ; 01 (320x350,640x350) */
{9, 1057, 737, 703}, /* ; 02 (360x400,720x400) */
{9, 1057, 686, 651}, /* ; 03 (720x350) */
{9, 1057, 776, 741}, /* ; 04 (640x480x60Hz) */
{9, 1057, 0, 771}, /* ; 05 (800x600x60Hz) */
{9, 1057, 805, 770} /* ; 06 (1024x768x60Hz) */
};
static struct XGI_LCDDesStruct XGI_CetLCDDes1024x768Data[] = {
{1152, 856, 622, 587}, /* ; 00 (320x200,320x400,640x200,640x400) */
{1152, 856, 597, 562}, /* ; 01 (320x350,640x350) */
{1152, 856, 622, 587}, /* ; 02 (360x400,720x400) */
{1152, 856, 597, 562}, /* ; 03 (720x350) */
{1152, 856, 662, 627}, /* ; 04 (640x480x60Hz) */
{1232, 936, 722, 687}, /* ; 05 (800x600x60Hz) */
{0, 1048, 805, 770} /* ; 06 (1024x768x60Hz) */
};
static struct XGI_LCDDesStruct XGI_ExtLCDDLDes1280x1024Data[] = {
{18, 1346, 981, 940}, /* 00 (320x200,320x400,640x200,640x400) */
{18, 1346, 926, 865}, /* 01 (320x350,640x350) */
{18, 1346, 981, 940}, /* 02 (360x400,720x400) */
{18, 1346, 926, 865}, /* 03 (720x350) */
{18, 1346, 0, 1025}, /* 04 (640x480x60Hz) */
{18, 1346, 0, 1025}, /* 05 (800x600x60Hz) */
{18, 1346, 1065, 1024}, /* 06 (1024x768x60Hz) */
{18, 1346, 1065, 1024} /* 07 (1280x1024x60Hz) */
};
static struct XGI_LCDDesStruct XGI_StLCDDLDes1280x1024Data[] = {
{18, 1346, 970, 907}, /* 00 (320x200,320x400,640x200,640x400) */
{18, 1346, 917, 854}, /* 01 (320x350,640x350) */
{18, 1346, 970, 907}, /* 02 (360x400,720x400) */
{18, 1346, 917, 854}, /* 03 (720x350) */
{18, 1346, 0, 1025}, /* 04 (640x480x60Hz) */
{18, 1346, 0, 1025}, /* 05 (800x600x60Hz) */
{18, 1346, 1065, 1024}, /* 06 (1024x768x60Hz) */
{18, 1346, 1065, 1024} /* 07 (1280x1024x60Hz) */
};
static struct XGI_LCDDesStruct XGI_CetLCDDLDes1280x1024Data[] = {
{1368, 1008, 752, 711}, /* 00 (320x200,320x400,640x200,640x400) */
{1368, 1008, 729, 688}, /* 01 (320x350,640x350) */
{1368, 1008, 752, 711}, /* 02 (360x400,720x400) */
{1368, 1008, 729, 688}, /* 03 (720x350) */
{1368, 1008, 794, 753}, /* 04 (640x480x60Hz) */
{1448, 1068, 854, 813}, /* 05 (800x600x60Hz) */
{1560, 1200, 938, 897}, /* 06 (1024x768x60Hz) */
{18, 1346, 1065, 1024} /* 07 (1280x1024x60Hz) */
};
static struct XGI_LCDDesStruct XGI_ExtLCDDes1280x1024Data[] = {
{9, 1337, 981, 940}, /* ; 00 (320x200,320x400,640x200,640x400) */
{9, 1337, 926, 884}, /* ; 01 (320x350,640x350) alan, 2003/09/30 */
{9, 1337, 981, 940}, /* ; 02 (360x400,720x400) */
{9, 1337, 926, 884}, /* ; 03 (720x350) alan, 2003/09/30 */
{9, 1337, 0, 1025}, /* ; 04 (640x480x60Hz) */
{9, 1337, 0, 1025}, /* ; 05 (800x600x60Hz) */
{9, 1337, 1065, 1024}, /* ; 06 (1024x768x60Hz) */
{9, 1337, 1065, 1024} /* ; 07 (1280x1024x60Hz) */
};
static struct XGI_LCDDesStruct XGI_StLCDDes1280x1024Data[] = {
{9, 1337, 970, 907}, /* ; 00 (320x200,320x400,640x200,640x400) */
{9, 1337, 917, 854}, /* ; 01 (320x350,640x350) */
{9, 1337, 970, 907}, /* ; 02 (360x400,720x400) */
{9, 1337, 917, 854}, /* ; 03 (720x350) */
{9, 1337, 0, 1025}, /* ; 04 (640x480x60Hz) */
{9, 1337, 0, 1025}, /* ; 05 (800x600x60Hz) */
{9, 1337, 1065, 1024}, /* ; 06 (1024x768x60Hz) */
{9, 1337, 1065, 1024} /* ; 07 (1280x1024x60Hz) */
};
static struct XGI_LCDDesStruct XGI_CetLCDDes1280x1024Data[] = {
{1368, 1008, 752, 711}, /* 00 (320x200,320x400,640x200,640x400) */
{1368, 1008, 729, 688}, /* 01 (320x350,640x350) */
{1368, 1008, 752, 711}, /* 02 (360x400,720x400) */
{1368, 1008, 729, 688}, /* 03 (720x350) */
{1368, 1008, 794, 753}, /* 04 (640x480x60Hz) */
{1448, 1068, 854, 813}, /* 05 (800x600x60Hz) */
{1560, 1200, 938, 897}, /* 06 (1024x768x60Hz) */
{9, 1337, 1065, 1024} /* 07 (1280x1024x60Hz) */
};
static struct XGI_LCDDesStruct xgifb_lcddldes_1400x1050[] = {
{18, 1464, 0, 1051}, /* 00 (320x200,320x400,640x200,640x400) */
{18, 1464, 0, 1051}, /* 01 (320x350,640x350) */
{18, 1464, 0, 1051}, /* 02 (360x400,720x400) */
{18, 1464, 0, 1051}, /* 03 (720x350) */
{18, 1464, 0, 1051}, /* 04 (640x480x60Hz) */
{18, 1464, 0, 1051}, /* 05 (800x600x60Hz) */
{18, 1464, 0, 1051}, /* 06 (1024x768x60Hz) */
{1646, 1406, 1053, 1038}, /* 07 (1280x1024x60Hz) */
{18, 1464, 0, 1051} /* 08 (1400x1050x60Hz) */
};
static struct XGI_LCDDesStruct xgifb_lcddes_1400x1050[] = {
{9, 1455, 0, 1051}, /* 00 (320x200,320x400,640x200,640x400) */
{9, 1455, 0, 1051}, /* 01 (320x350,640x350) */
{9, 1455, 0, 1051}, /* 02 (360x400,720x400) */
{9, 1455, 0, 1051}, /* 03 (720x350) */
{9, 1455, 0, 1051}, /* 04 (640x480x60Hz) */
{9, 1455, 0, 1051}, /* 05 (800x600x60Hz) */
{9, 1455, 0, 1051}, /* 06 (1024x768x60Hz) */
{1637, 1397, 1053, 1038}, /* 07 (1280x1024x60Hz) */
{9, 1455, 0, 1051} /* 08 (1400x1050x60Hz) */
};
static struct XGI_LCDDesStruct XGI_CetLCDDes1400x1050Data[] = {
{1308, 1068, 781, 766}, /* 00 (320x200,320x400,640x200,640x400) */
{1308, 1068, 781, 766}, /* 01 (320x350,640x350) */
{1308, 1068, 781, 766}, /* 02 (360x400,720x400) */
{1308, 1068, 781, 766}, /* 03 (720x350) */
{1308, 1068, 781, 766}, /* 04 (640x480x60Hz) */
{1388, 1148, 841, 826}, /* 05 (800x600x60Hz) */
{1490, 1250, 925, 910}, /* 06 (1024x768x60Hz) */
{1646, 1406, 1053, 1038}, /* 07 (1280x1024x60Hz) */
{18, 1464, 0, 1051} /* 08 (1400x1050x60Hz) */
};
static struct XGI_LCDDesStruct XGI_CetLCDDes1400x1050Data2[] = {
{0, 1448, 0, 1051}, /* 00 (320x200,320x400,640x200,640x400) */
{0, 1448, 0, 1051}, /* 01 (320x350,640x350) */
{0, 1448, 0, 1051}, /* 02 (360x400,720x400) */
{0, 1448, 0, 1051}, /* 03 (720x350) */
{0, 1448, 0, 1051} /* 04 (640x480x60Hz) */
};
static struct XGI_LCDDesStruct XGI_ExtLCDDLDes1600x1200Data[] = {
{18, 1682, 0, 1201}, /* 00 (320x200,320x400,640x200,640x400) */
{18, 1682, 0, 1201}, /* 01 (320x350,640x350) */
{18, 1682, 0, 1201}, /* 02 (360x400,720x400) */
{18, 1682, 0, 1201}, /* 03 (720x350) */
{18, 1682, 0, 1201}, /* 04 (640x480x60Hz) */
{18, 1682, 0, 1201}, /* 05 (800x600x60Hz) */
{18, 1682, 0, 1201}, /* 06 (1024x768x60Hz) */
{18, 1682, 0, 1201}, /* 07 (1280x1024x60Hz) */
{18, 1682, 0, 1201}, /* 08 (1400x1050x60Hz) */
{18, 1682, 0, 1201} /* 09 (1600x1200x60Hz) */
};
static struct XGI_LCDDesStruct XGI_StLCDDLDes1600x1200Data[] = {
{18, 1682, 1150, 1101}, /* 00 (320x200,320x400,640x200,640x400) */
{18, 1682, 1083, 1034}, /* 01 (320x350,640x350) */
{18, 1682, 1150, 1101}, /* 02 (360x400,720x400) */
{18, 1682, 1083, 1034}, /* 03 (720x350) */
{18, 1682, 0, 1201}, /* 04 (640x480x60Hz) */
{18, 1682, 0, 1201}, /* 05 (800x600x60Hz) */
{18, 1682, 0, 1201}, /* 06 (1024x768x60Hz) */
{18, 1682, 1232, 1183}, /* 07 (1280x1024x60Hz) */
{18, 1682, 0, 1201}, /* 08 (1400x1050x60Hz) */
{18, 1682, 0, 1201} /* 09 (1600x1200x60Hz) */
};
static struct XGI_LCDDesStruct XGI_ExtLCDDes1600x1200Data[] = {
{9, 1673, 0, 1201}, /* 00 (320x200,320x400,640x200,640x400) */
{9, 1673, 0, 1201}, /* 01 (320x350,640x350) */
{9, 1673, 0, 1201}, /* 02 (360x400,720x400) */
{9, 1673, 0, 1201}, /* 03 (720x350) */
{9, 1673, 0, 1201}, /* 04 (640x480x60Hz) */
{9, 1673, 0, 1201}, /* 05 (800x600x60Hz) */
{9, 1673, 0, 1201}, /* 06 (1024x768x60Hz) */
{9, 1673, 0, 1201}, /* 07 (1280x1024x60Hz) */
{9, 1673, 0, 1201}, /* 08 (1400x1050x60Hz) */
{9, 1673, 0, 1201} /* 09 (1600x1200x60Hz) */
};
static struct XGI_LCDDesStruct XGI_StLCDDes1600x1200Data[] = {
{9, 1673, 1150, 1101}, /* 00 (320x200,320x400,640x200,640x400) */
{9, 1673, 1083, 1034}, /* 01 (320x350,640x350) */
{9, 1673, 1150, 1101}, /* 02 (360x400,720x400) */
{9, 1673, 1083, 1034}, /* 03 (720x350) */
{9, 1673, 0, 1201}, /* 04 (640x480x60Hz) */
{9, 1673, 0, 1201}, /* 05 (800x600x60Hz) */
{9, 1673, 0, 1201}, /* 06 (1024x768x60Hz) */
{9, 1673, 1232, 1183}, /* 07 (1280x1024x60Hz) */
{9, 1673, 0, 1201}, /* 08 (1400x1050x60Hz) */
{9, 1673, 0, 1201} /* 09 (1600x1200x60Hz) */
};
static struct XGI330_LCDDataDesStruct2 XGI_NoScalingDesData[] = {
{9, 657, 448, 405, 96, 2}, /* 00 (320x200,320x400,
640x200,640x400) */
{9, 657, 448, 355, 96, 2}, /* 01 (320x350,640x350) */
{9, 657, 448, 405, 96, 2}, /* 02 (360x400,720x400) */
{9, 657, 448, 355, 96, 2}, /* 03 (720x350) */
{9, 657, 1, 483, 96, 2}, /* 04 (640x480x60Hz) */
{9, 849, 627, 600, 128, 4}, /* 05 (800x600x60Hz) */
{9, 1057, 805, 770, 0136, 6}, /* 06 (1024x768x60Hz) */
{9, 1337, 0, 1025, 112, 3}, /* 07 (1280x1024x60Hz) */
{9, 1457, 0, 1051, 112, 3}, /* 08 (1400x1050x60Hz)*/
{9, 1673, 0, 1201, 192, 3}, /* 09 (1600x1200x60Hz) */
{9, 1337, 0, 771, 112, 6} /* 0A (1280x768x60Hz) */
};
/* ;;1024x768x75Hz */
static struct XGI_LCDDesStruct xgifb_lcddes_1024x768x75[] = {
{9, 1049, 0, 769}, /* ; 00 (320x200,320x400,640x200,640x400) */
{9, 1049, 0, 769}, /* ; 01 (320x350,640x350) */
{9, 1049, 0, 769}, /* ; 02 (360x400,720x400) */
{9, 1049, 0, 769}, /* ; 03 (720x350) */
{9, 1049, 0, 769}, /* ; 04 (640x480x75Hz) */
{9, 1049, 0, 769}, /* ; 05 (800x600x75Hz) */
{9, 1049, 0, 769} /* ; 06 (1024x768x75Hz) */
};
/* ;;1024x768x75Hz */
static struct XGI_LCDDesStruct XGI_CetLCDDes1024x768x75Data[] = {
{1152, 856, 622, 587}, /* ; 00 (320x200,320x400,640x200,640x400) */
{1152, 856, 597, 562}, /* ; 01 (320x350,640x350) */
{1192, 896, 622, 587}, /* ; 02 (360x400,720x400) */
{1192, 896, 597, 562}, /* ; 03 (720x350) */
{1129, 857, 656, 625}, /* ; 04 (640x480x75Hz) */
{1209, 937, 716, 685}, /* ; 05 (800x600x75Hz) */
{9, 1049, 0, 769} /* ; 06 (1024x768x75Hz) */
};
/* ;;1280x1024x75Hz */
static struct XGI_LCDDesStruct xgifb_lcddldes_1280x1024x75[] = {
{18, 1314, 0, 1025}, /* ; 00 (320x200,320x400,640x200,640x400) */
{18, 1314, 0, 1025}, /* ; 01 (320x350,640x350) */
{18, 1314, 0, 1025}, /* ; 02 (360x400,720x400) */
{18, 1314, 0, 1025}, /* ; 03 (720x350) */
{18, 1314, 0, 1025}, /* ; 04 (640x480x60Hz) */
{18, 1314, 0, 1025}, /* ; 05 (800x600x60Hz) */
{18, 1314, 0, 1025}, /* ; 06 (1024x768x60Hz) */
{18, 1314, 0, 1025} /* ; 07 (1280x1024x60Hz) */
};
/* 1280x1024x75Hz */
static struct XGI_LCDDesStruct XGI_CetLCDDLDes1280x1024x75Data[] = {
{1368, 1008, 752, 711}, /* ; 00 (320x200,320x400,640x200,640x400) */
{1368, 1008, 729, 688}, /* ; 01 (320x350,640x350) */
{1408, 1048, 752, 711}, /* ; 02 (360x400,720x400) */
{1408, 1048, 729, 688}, /* ; 03 (720x350) */
{1377, 985, 794, 753}, /* ; 04 (640x480x75Hz) */
{1457, 1065, 854, 813}, /* ; 05 (800x600x75Hz) */
{1569, 1177, 938, 897}, /* ; 06 (1024x768x75Hz) */
{18, 1314, 0, 1025} /* ; 07 (1280x1024x75Hz) */
};
/* ;;1280x1024x75Hz */
static struct XGI_LCDDesStruct xgifb_lcddes_1280x1024x75[] = {
{9, 1305, 0, 1025}, /* ; 00 (320x200,320x400,640x200,640x400) */
{9, 1305, 0, 1025}, /* ; 01 (320x350,640x350) */
{9, 1305, 0, 1025}, /* ; 02 (360x400,720x400) */
{9, 1305, 0, 1025}, /* ; 03 (720x350) */
{9, 1305, 0, 1025}, /* ; 04 (640x480x60Hz) */
{9, 1305, 0, 1025}, /* ; 05 (800x600x60Hz) */
{9, 1305, 0, 1025}, /* ; 06 (1024x768x60Hz) */
{9, 1305, 0, 1025} /* ; 07 (1280x1024x60Hz) */
};
/* 1280x1024x75Hz */
static struct XGI_LCDDesStruct XGI_CetLCDDes1280x1024x75Data[] = {
{1368, 1008, 752, 711}, /* ; 00 (320x200,320x400,640x200,640x400) */
{1368, 1008, 729, 688}, /* ; 01 (320x350,640x350) */
{1408, 1048, 752, 711}, /* ; 02 (360x400,720x400) */
{1408, 1048, 729, 688}, /* ; 03 (720x350) */
{1377, 985, 794, 753}, /* ; 04 (640x480x75Hz) */
{1457, 1065, 854, 813}, /* ; 05 (800x600x75Hz) */
{1569, 1177, 938, 897}, /* ; 06 (1024x768x75Hz) */
{9, 1305, 0, 1025} /* ; 07 (1280x1024x75Hz) */
};
/* Scaling LCD 75Hz */
static struct XGI330_LCDDataDesStruct2 XGI_NoScalingDesDatax75[] = {
{9, 657, 448, 405, 96, 2}, /* ; 00 (320x200,320x400,
640x200,640x400) */
{9, 657, 448, 355, 96, 2}, /* ; 01 (320x350,640x350) */
{9, 738, 448, 405, 108, 2}, /* ; 02 (360x400,720x400) */
{9, 738, 448, 355, 108, 2}, /* ; 03 (720x350) */
{9, 665, 0, 481, 64, 3}, /* ; 04 (640x480x75Hz) */
{9, 825, 0, 601, 80, 3}, /* ; 05 (800x600x75Hz) */
{9, 1049, 0, 769, 96, 3}, /* ; 06 (1024x768x75Hz) */
{9, 1305, 0, 1025, 144, 3}, /* ; 07 (1280x1024x75Hz) */
{9, 1457, 0, 1051, 112, 3}, /* ; 08 (1400x1050x60Hz)*/
{9, 1673, 0, 1201, 192, 3}, /* ; 09 (1600x1200x75Hz) */
{9, 1337, 0, 771, 112, 6} /* ; 0A (1280x768x60Hz) */
};
static struct XGI330_TVDataStruct XGI_StPALData[] = {
{1, 1, 864, 525, 1270, 400, 100, 0, 760},
{1, 1, 864, 525, 1270, 350, 100, 0, 760},
{1, 1, 864, 525, 1270, 400, 0, 0, 720},
{1, 1, 864, 525, 1270, 350, 0, 0, 720},
{1, 1, 864, 525, 1270, 480, 50, 0, 760},
{1, 1, 864, 525, 1270, 600, 50, 0, 0}
};
static struct XGI330_TVDataStruct XGI_ExtPALData[] = {
{2, 1, 1080, 463, 1270, 500, 50, 0, 50},
{15, 7, 1152, 413, 1270, 500, 50, 0, 50},
{2, 1, 1080, 463, 1270, 500, 50, 0, 50},
{15, 7, 1152, 413, 1270, 500, 50, 0, 50},
{2, 1, 900, 543, 1270, 500, 0, 0, 50},
{4, 3, 1080, 663, 1270, 500, 438, 0, 438},
{1, 1, 1125, 831, 1270, 500, 686, 0, 686}, /*301b*/
{3, 2, 1080, 619, 1270, 540, 438, 0, 438}
};
static struct XGI330_TVDataStruct XGI_StNTSCData[] = {
{1, 1, 858, 525, 1270, 400, 50, 0, 760},
{1, 1, 858, 525, 1270, 350, 50, 0, 640},
{1, 1, 858, 525, 1270, 400, 0, 0, 720},
{1, 1, 858, 525, 1270, 350, 0, 0, 720},
{1, 1, 858, 525, 1270, 480, 0, 0, 760}
};
static struct XGI330_TVDataStruct XGI_ExtNTSCData[] = {
{9, 5, 1001, 453, 1270, 420, 171, 0, 171},
{12, 5, 858, 403, 1270, 420, 171, 0, 171},
{9, 5, 1001, 453, 1270, 420, 171, 0, 171},
{12, 5, 858, 403, 1270, 420, 171, 0, 171},
{143, 80, 836, 523, 1270, 420, 224, 0, 0},
{143, 120, 1008, 643, 1270, 420, 0, 1, 0},
{1, 1, 1120, 821, 1516, 420, 0, 1, 0}, /*301b*/
{2, 1, 858, 503, 1584, 480, 0, 1, 0},
{3, 2, 1001, 533, 1270, 420, 0, 0, 0}
};
static struct XGI330_TVDataStruct XGI_St1HiTVData[] = {
{1, 1, 892, 563, 690, 800, 0, 0, 0}, /* 00 (320x200,320x400,
640x200,640x400) */
{1, 1, 892, 563, 690, 700, 0, 0, 0}, /* 01 (320x350,640x350) */
{1, 1, 1000, 563, 785, 800, 0, 0, 0}, /* 02 (360x400,720x400) */
{1, 1, 1000, 563, 785, 700, 0, 0, 0}, /* 03 (720x350) */
{1, 1, 892, 563, 690, 960, 0, 0, 0}, /* 04 (320x240,640x480) */
{8, 5, 1050, 683, 1648, 960, 0x150, 1, 0} /* 05 (400x300,800x600) */
};
static struct XGI330_TVDataStruct XGI_St2HiTVData[] = {
{3, 1, 840, 483, 1648, 960, 0x032, 0, 0}, /* 00 (320x200,320x400,
640x200,640x400) */
{1, 1, 892, 563, 690, 700, 0, 0, 0}, /* 01 (320x350,640x350) */
{3, 1, 840, 483, 1648, 960, 0x032, 0, 0}, /* 02 (360x400,720x400) */
{1, 1, 1000, 563, 785, 700, 0, 0, 0}, /* 03 (720x350) */
{5, 2, 840, 563, 1648, 960, 0x08D, 1, 0}, /* 04 (320x240,640x480) */
{8, 5, 1050, 683, 1648, 960, 0x17C, 1, 0} /* 05 (400x300,800x600) */
};
static struct XGI330_TVDataStruct XGI_ExtHiTVData[] = {
{6, 1, 840, 563, 1632, 960, 0, 0, 0}, /* 00 (320x200,320x400,
640x200,640x400) */
{3, 1, 960, 563, 1632, 960, 0, 0, 0}, /* 01 (320x350,640x350) */
{3, 1, 840, 483, 1632, 960, 0, 0, 0}, /* 02 (360x400,720x400) */
{3, 1, 960, 563, 1632, 960, 0, 0, 0}, /* 03 (720x350) */
{5, 1, 840, 563, 1648, 960, 0x166, 1, 0}, /* 04 (320x240,640x480) */
{16, 5, 1050, 683, 1648, 960, 0x143, 1, 0}, /* 05 (400x300,800x600) */
{25, 12, 1260, 851, 1648, 960, 0x032, 0, 0}, /* 06 (512x384,1024x768)*/
{5, 4, 1575, 1124, 1648, 960, 0x128, 0, 0}, /* 07 (1280x1024) */
{4, 1, 1050, 563, 1548, 960, 0x143, 1, 0}, /* 08 (800x480) */
{5, 2, 1400, 659, 1648, 960, 0x032, 0, 0}, /* 09 (1024x576) */
{8, 5, 1750, 803, 1648, 960, 0x128, 0, 0} /* 0A (1280x720) */
};
static struct XGI330_TVDataStruct XGI_ExtYPbPr525iData[] = {
{ 9, 5, 1001, 453, 1270, 420, 171, 0, 171},
{ 12, 5, 858, 403, 1270, 420, 171, 0, 171},
{ 9, 5, 1001, 453, 1270, 420, 171, 0, 171},
{ 12, 5, 858, 403, 1270, 420, 171, 0, 171},
{143, 80, 836, 523, 1250, 420, 224, 0, 0},
{143, 120, 1008, 643, 1250, 420, 0, 1, 0},
{ 1, 1, 1120, 821, 1516, 420, 0, 1, 0}, /*301b*/
{ 2, 1, 858, 503, 1584, 480, 0, 1, 0},
{ 3, 2, 1001, 533, 1250, 420, 0, 0, 0}
};
static struct XGI330_TVDataStruct XGI_StYPbPr525iData[] = {
{1, 1, 858, 525, 1270, 400, 50, 0, 760},
{1, 1, 858, 525, 1270, 350, 50, 0, 640},
{1, 1, 858, 525, 1270, 400, 0, 0, 720},
{1, 1, 858, 525, 1270, 350, 0, 0, 720},
{1, 1, 858, 525, 1270, 480, 0, 0, 760},
};
static struct XGI330_TVDataStruct XGI_ExtYPbPr525pData[] = {
{ 9, 5, 1001, 453, 1270, 420, 171, 0, 171},
{ 12, 5, 858, 403, 1270, 420, 171, 0, 171},
{ 9, 5, 1001, 453, 1270, 420, 171, 0, 171},
{ 12, 5, 858, 403, 1270, 420, 171, 0, 171},
{143, 80, 836, 523, 1270, 420, 224, 0, 0},
{143, 120, 1008, 643, 1270, 420, 0, 1, 0},
{ 1, 1, 1120, 821, 1516, 420, 0, 1, 0}, /*301b*/
{ 2, 1, 858, 503, 1584, 480, 0, 1, 0},
{ 3, 2, 1001, 533, 1270, 420, 0, 0, 0}
};
static struct XGI330_TVDataStruct XGI_StYPbPr525pData[] = {
{1, 1, 1716, 525, 1270, 400, 50, 0, 760},
{1, 1, 1716, 525, 1270, 350, 50, 0, 640},
{1, 1, 1716, 525, 1270, 400, 0, 0, 720},
{1, 1, 1716, 525, 1270, 350, 0, 0, 720},
{1, 1, 1716, 525, 1270, 480, 0, 0, 760},
};
static struct XGI330_TVDataStruct XGI_ExtYPbPr750pData[] = {
{ 3, 1, 935, 470, 1130, 680, 50, 0, 0}, /* 00 (320x200,320x400,
640x200,640x400) */
{24, 7, 935, 420, 1130, 680, 50, 0, 0}, /* 01 (320x350,640x350) */
{ 3, 1, 935, 470, 1130, 680, 50, 0, 0}, /* 02 (360x400,720x400) */
{24, 7, 935, 420, 1130, 680, 50, 0, 0}, /* 03 (720x350) */
{ 2, 1, 1100, 590, 1130, 640, 50, 0, 0}, /* 04 (320x240,640x480) */
{ 3, 2, 1210, 690, 1130, 660, 50, 0, 0}, /* 05 (400x300,800x600) */
{ 1, 1, 1375, 878, 1130, 640, 638, 0, 0}, /* 06 (1024x768) */
{ 2, 1, 858, 503, 1130, 480, 0, 1, 0}, /* 07 (720x480) */
{ 5, 4, 1815, 570, 1130, 660, 50, 0, 0},
{ 5, 3, 1100, 686, 1130, 640, 50, 1, 0},
{10, 9, 1320, 830, 1130, 640, 50, 0, 0}
};
static struct XGI330_TVDataStruct XGI_StYPbPr750pData[] = {
{1, 1, 1650, 750, 1280, 400, 50, 0, 760},
{1, 1, 1650, 750, 1280, 350, 50, 0, 640},
{1, 1, 1650, 750, 1280, 400, 0, 0, 720},
{1, 1, 1650, 750, 1280, 350, 0, 0, 720},
{1, 1, 1650, 750, 1280, 480, 0, 0, 760},
};
static unsigned char XGI330_NTSCTiming[] = {
0x17, 0x1d, 0x03, 0x09, 0x05, 0x06, 0x0c, 0x0c,
0x94, 0x49, 0x01, 0x0a, 0x06, 0x0d, 0x04, 0x0a,
0x06, 0x14, 0x0d, 0x04, 0x0a, 0x00, 0x85, 0x1b,
0x0c, 0x50, 0x00, 0x97, 0x00, 0xda, 0x4a, 0x17,
0x7d, 0x05, 0x4b, 0x00, 0x00, 0xe2, 0x00, 0x02,
0x03, 0x0a, 0x65, 0x9d, 0x08, 0x92, 0x8f, 0x40,
0x60, 0x80, 0x14, 0x90, 0x8c, 0x60, 0x14, 0x50,
0x00, 0x40, 0x44, 0x00, 0xdb, 0x02, 0x3b, 0x00
};
static unsigned char XGI330_PALTiming[] = {
0x21, 0x5A, 0x35, 0x6e, 0x04, 0x38, 0x3d, 0x70,
0x94, 0x49, 0x01, 0x12, 0x06, 0x3e, 0x35, 0x6d,
0x06, 0x14, 0x3e, 0x35, 0x6d, 0x00, 0x45, 0x2b,
0x70, 0x50, 0x00, 0x9b, 0x00, 0xd9, 0x5d, 0x17,
0x7d, 0x05, 0x45, 0x00, 0x00, 0xe8, 0x00, 0x02,
0x0d, 0x00, 0x68, 0xb0, 0x0b, 0x92, 0x8f, 0x40,
0x60, 0x80, 0x14, 0x90, 0x8c, 0x60, 0x14, 0x63,
0x00, 0x40, 0x3e, 0x00, 0xe1, 0x02, 0x28, 0x00
};
static unsigned char XGI330_HiTVExtTiming[] = {
0x2D, 0x60, 0x2C, 0x5F, 0x08, 0x31, 0x3A, 0x64,
0x28, 0x02, 0x01, 0x3D, 0x06, 0x3E, 0x35, 0x6D,
0x06, 0x14, 0x3E, 0x35, 0x6D, 0x00, 0xC5, 0x3F,
0x64, 0x90, 0x33, 0x8C, 0x18, 0x36, 0x3E, 0x13,
0x2A, 0xDE, 0x2A, 0x44, 0x40, 0x2A, 0x44, 0x40,
0x8E, 0x8E, 0x82, 0x07, 0x0B,
0x92, 0x0F, 0x40, 0x60, 0x80, 0x14, 0x90, 0x8C,
0x60, 0x14, 0x3D, 0x63, 0x4F,
0x27, 0x00, 0xfc, 0xff, 0x6a, 0x00
};
static unsigned char XGI330_HiTVSt1Timing[] = {
0x32, 0x65, 0x2C, 0x5F, 0x08, 0x31, 0x3A, 0x65,
0x28, 0x02, 0x01, 0x3D, 0x06, 0x3E, 0x35, 0x6D,
0x06, 0x14, 0x3E, 0x35, 0x6D, 0x00, 0xC5, 0x3F,
0x65, 0x90, 0x7B, 0xA8, 0x03, 0xF0, 0x87, 0x03,
0x11, 0x15, 0x11, 0xCF, 0x10, 0x11, 0xCF, 0x10,
0x35, 0x35, 0x3B, 0x69, 0x1D,
0x92, 0x0F, 0x40, 0x60, 0x80, 0x14, 0x90, 0x8C,
0x60, 0x04, 0x86, 0xAF, 0x5D,
0x0E, 0x00, 0xfc, 0xff, 0x2d, 0x00
};
static unsigned char XGI330_HiTVSt2Timing[] = {
0x32, 0x65, 0x2C, 0x5F, 0x08, 0x31, 0x3A, 0x64,
0x28, 0x02, 0x01, 0x3D, 0x06, 0x3E, 0x35, 0x6D,
0x06, 0x14, 0x3E, 0x35, 0x6D, 0x00, 0xC5, 0x3F,
0x64, 0x90, 0x33, 0x8C, 0x18, 0x36, 0x3E, 0x13,
0x2A, 0xDE, 0x2A, 0x44, 0x40, 0x2A, 0x44, 0x40,
0x8E, 0x8E, 0x82, 0x07, 0x0B,
0x92, 0x0F, 0x40, 0x60, 0x80, 0x14, 0x90, 0x8C,
0x60, 0x14, 0x3D, 0x63, 0x4F,
0x27, 0x00, 0xFC, 0xff, 0x6a, 0x00
};
static unsigned char XGI330_HiTVTextTiming[] = {
0x32, 0x65, 0x2C, 0x5F, 0x08, 0x31, 0x3A, 0x65,
0x28, 0x02, 0x01, 0x3D, 0x06, 0x3E, 0x35, 0x6D,
0x06, 0x14, 0x3E, 0x35, 0x6D, 0x00, 0xC5, 0x3F,
0x65, 0x90, 0xE7, 0xBC, 0x03, 0x0C, 0x97, 0x03,
0x14, 0x78, 0x14, 0x08, 0x20, 0x14, 0x08, 0x20,
0xC8, 0xC8, 0x3B, 0xD2, 0x26,
0x92, 0x0F, 0x40, 0x60, 0x80, 0x14, 0x90, 0x8C,
0x60, 0x04, 0x96, 0x72, 0x5C,
0x11, 0x00, 0xFC, 0xFF, 0x32, 0x00
};
static unsigned char XGI330_YPbPr750pTiming[] = {
0x30, 0x1d, 0xe8, 0x09, 0x09, 0xed, 0x0c, 0x0c,
0x98, 0x0a, 0x01, 0x0c, 0x06, 0x0d, 0x04, 0x0a,
0x06, 0x14, 0x0d, 0x04, 0x0a, 0x00, 0x85, 0x3f,
0xed, 0x50, 0x70, 0x9f, 0x16, 0x59, 0x60, 0x13,
0x27, 0x0b, 0x27, 0xfc, 0x30, 0x27, 0x1c, 0xb0,
0x4b, 0x4b, 0x6f, 0x2f, 0x63,
0x92, 0x0F, 0x40, 0x60, 0x80, 0x14, 0x90, 0x8C,
0x60, 0x14, 0x73, 0x00, 0x40,
0x11, 0x00, 0xfc, 0xff, 0x32, 0x00
};
static unsigned char XGI330_YPbPr525pTiming[] = {
0x3E, 0x11, 0x06, 0x09, 0x0b, 0x0c, 0x0c, 0x0c,
0x98, 0x0a, 0x01, 0x0d, 0x06, 0x0d, 0x04, 0x0a,
0x06, 0x14, 0x0d, 0x04, 0x0a, 0x00, 0x85, 0x3f,
0x0c, 0x50, 0xb2, 0x9f, 0x16, 0x59, 0x4f, 0x13,
0xad, 0x11, 0xad, 0x1d, 0x40, 0x8a, 0x3d, 0xb8,
0x51, 0x5e, 0x60, 0x49, 0x7d,
0x92, 0x0F, 0x40, 0x60, 0x80, 0x14, 0x90, 0x8C,
0x60, 0x14, 0x4B, 0x43, 0x41,
0x11, 0x00, 0xFC, 0xFF, 0x32, 0x00
};
static unsigned char XGI330_YPbPr525iTiming[] = {
0x1B, 0x21, 0x03, 0x09, 0x05, 0x06, 0x0C, 0x0C,
0x94, 0x49, 0x01, 0x0A, 0x06, 0x0D, 0x04, 0x0A,
0x06, 0x14, 0x0D, 0x04, 0x0A, 0x00, 0x85, 0x1B,
0x0C, 0x50, 0x00, 0x97, 0x00, 0xDA, 0x4A, 0x17,
0x7D, 0x05, 0x4B, 0x00, 0x00, 0xE2, 0x00, 0x02,
0x03, 0x0A, 0x65, 0x9D, 0x08,
0x92, 0x8F, 0x40, 0x60, 0x80, 0x14, 0x90, 0x8C,
0x60, 0x14, 0x4B, 0x00, 0x40,
0x44, 0x00, 0xDB, 0x02, 0x3B, 0x00
};
static unsigned char XGI330_HiTVGroup3Data[] = {
0x00, 0x1A, 0x22, 0x63, 0x62, 0x22, 0x08, 0x5F,
0x05, 0x21, 0xB2, 0xB2, 0x55, 0x77, 0x2A, 0xA6,
0x25, 0x2F, 0x47, 0xFA, 0xC8, 0xFF, 0x8E, 0x20,
0x8C, 0x6E, 0x60, 0x2E, 0x58, 0x48, 0x72, 0x44,
0x56, 0x36, 0x4F, 0x6E, 0x3F, 0x80, 0x00, 0x80,
0x4F, 0x7F, 0x03, 0xA8, 0x7D, 0x20, 0x1A, 0xA9,
0x14, 0x05, 0x03, 0x7E, 0x64, 0x31, 0x14, 0x75,
0x18, 0x05, 0x18, 0x05, 0x4C, 0xA8, 0x01
};
static unsigned char XGI330_HiTVGroup3Simu[] = {
0x00, 0x1A, 0x22, 0x63, 0x62, 0x22, 0x08, 0x95,
0xDB, 0x20, 0xB8, 0xB8, 0x55, 0x47, 0x2A, 0xA6,
0x25, 0x2F, 0x47, 0xFA, 0xC8, 0xFF, 0x8E, 0x20,
0x8C, 0x6E, 0x60, 0x15, 0x26, 0xD3, 0xE4, 0x11,
0x56, 0x36, 0x4F, 0x6E, 0x3F, 0x80, 0x00, 0x80,
0x67, 0x36, 0x01, 0x47, 0x0E, 0x10, 0xBE, 0xB4,
0x01, 0x05, 0x03, 0x7E, 0x65, 0x31, 0x14, 0x75,
0x18, 0x05, 0x18, 0x05, 0x4C, 0xA8, 0x01
};
static unsigned char XGI330_HiTVGroup3Text[] = {
0x00, 0x1A, 0x22, 0x63, 0x62, 0x22, 0x08, 0xA7,
0xF5, 0x20, 0xCE, 0xCE, 0x55, 0x47, 0x2A, 0xA6,
0x25, 0x2F, 0x47, 0xFA, 0xC8, 0xFF, 0x8E, 0x20,
0x8C, 0x6E, 0x60, 0x18, 0x2C, 0x0C, 0x20, 0x22,
0x56, 0x36, 0x4F, 0x6E, 0x3F, 0x80, 0x00, 0x80,
0x93, 0x3C, 0x01, 0x50, 0x2F, 0x10, 0xF4, 0xCA,
0x01, 0x05, 0x03, 0x7E, 0x65, 0x31, 0x14, 0x75,
0x18, 0x05, 0x18, 0x05, 0x4C, 0xA8, 0x01
};
static unsigned char XGI330_Ren525pGroup3[] = {
0x00, 0x14, 0x15, 0x25, 0x55, 0x15, 0x0b, 0x13,
0xB1, 0x41, 0x62, 0x62, 0xFF, 0xF4, 0x45, 0xa6,
0x25, 0x2F, 0x67, 0xF6, 0xbf, 0xFF, 0x8E, 0x20,
0xAC, 0xDA, 0x60, 0xFe, 0x6A, 0x9A, 0x06, 0x10,
0xd1, 0x04, 0x18, 0x0a, 0xFF, 0x80, 0x00, 0x80,
0x3c, 0x77, 0x00, 0xEF, 0xE0, 0x10, 0xB0, 0xE0,
0x10, 0x4F, 0x0F, 0x0F, 0x05, 0x0F, 0x08, 0x6E,
0x1a, 0x1F, 0x25, 0x2a, 0x4C, 0xAA, 0x01
};
static unsigned char XGI330_Ren750pGroup3[] = {
0x00, 0x14, 0x15, 0x25, 0x55, 0x15, 0x0b, 0x7a,
0x54, 0x41, 0xE7, 0xE7, 0xFF, 0xF4, 0x45, 0xa6,
0x25, 0x2F, 0x67, 0xF6, 0xbf, 0xFF, 0x8E, 0x20,
0xAC, 0x6A, 0x60, 0x2b, 0x52, 0xCD, 0x61, 0x10,
0x51, 0x04, 0x18, 0x0a, 0x1F, 0x80, 0x00, 0x80,
0xFF, 0xA4, 0x04, 0x2B, 0x94, 0x21, 0x72, 0x94,
0x26, 0x05, 0x01, 0x0F, 0xed, 0x0F, 0x0A, 0x64,
0x18, 0x1D, 0x23, 0x28, 0x4C, 0xAA, 0x01
};
static struct SiS_LVDSData XGI_LVDS1024x768Data_1[] = {
{ 960, 438, 1344, 806}, /* 00 (320x200,320x400,640x200,640x400) */
{ 960, 388, 1344, 806}, /* 01 (320x350,640x350) */
{1040, 438, 1344, 806}, /* 02 (360x400,720x400) */
{1040, 388, 1344, 806}, /* 03 (720x350) */
{ 960, 518, 1344, 806}, /* 04 (320x240,640x480) */
{1120, 638, 1344, 806}, /* 05 (400x300,800x600) */
{1344, 806, 1344, 806} /* 06 (512x384,1024x768) */
};
static struct SiS_LVDSData XGI_LVDS1024x768Data_2[] = {
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{800, 449, 1280, 801},
{800, 525, 1280, 813}
};
static struct SiS_LVDSData XGI_LVDS1280x1024Data_1[] = {
{1048, 442, 1688, 1066},
{1048, 392, 1688, 1066},
{1048, 442, 1688, 1066},
{1048, 392, 1688, 1066},
{1048, 522, 1688, 1066},
{1208, 642, 1688, 1066},
{1432, 810, 1688, 1066},
{1688, 1066, 1688, 1066}
};
static struct SiS_LVDSData XGI_LVDS1280x1024Data_2[] = {
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{1344, 806, 1344, 806},
{800, 449, 1280, 801},
{800, 525, 1280, 813}
};
static struct SiS_LVDSData XGI_LVDS1400x1050Data_1[] = {
{928, 416, 1688, 1066},
{928, 366, 1688, 1066},
{928, 416, 1688, 1066},
{928, 366, 1688, 1066},
{928, 496, 1688, 1066},
{1088, 616, 1688, 1066},
{1312, 784, 1688, 1066},
{1568, 1040, 1688, 1066},
{1688, 1066, 1688, 1066}
};
static struct SiS_LVDSData XGI_LVDS1400x1050Data_2[] = {
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066},
{1688, 1066, 1688, 1066}
};
/* ;;[ycchen] 12/05/02 LCDHTxLCDVT=2048x1320 */
static struct SiS_LVDSData XGI_LVDS1600x1200Data_1[] = {
{1088, 520, 2048, 1320}, /* 00 (320x200,320x400,640x200,640x400) */
{1088, 470, 2048, 1320}, /* 01 (320x350,640x350) */
{1088, 520, 2048, 1320}, /* 02 (360x400,720x400) */
{1088, 470, 2048, 1320}, /* 03 (720x350) */
{1088, 600, 2048, 1320}, /* 04 (320x240,640x480) */
{1248, 720, 2048, 1320}, /* 05 (400x300,800x600) */
{1472, 888, 2048, 1320}, /* 06 (512x384,1024x768) */
{1728, 1144, 2048, 1320}, /* 07 (640x512,1280x1024) */
{1848, 1170, 2048, 1320}, /* 08 (1400x1050) */
{2048, 1320, 2048, 1320} /* 09 (1600x1200) */
};
static struct SiS_LVDSData XGI_LVDSNoScalingData[] = {
{ 800, 449, 800, 449}, /* 00 (320x200,320x400,640x200,640x400) */
{ 800, 449, 800, 449}, /* 01 (320x350,640x350) */
{ 800, 449, 800, 449}, /* 02 (360x400,720x400) */
{ 800, 449, 800, 449}, /* 03 (720x350) */
{ 800, 525, 800, 525}, /* 04 (640x480x60Hz) */
{1056, 628, 1056, 628}, /* 05 (800x600x60Hz) */
{1344, 806, 1344, 806}, /* 06 (1024x768x60Hz) */
{1688, 1066, 1688, 1066}, /* 07 (1280x1024x60Hz) */
{1688, 1066, 1688, 1066}, /* 08 (1400x1050x60Hz) */
{2160, 1250, 2160, 1250}, /* 09 (1600x1200x60Hz) */
{1688, 806, 1688, 806} /* 0A (1280x768x60Hz) */
};
static struct SiS_LVDSData XGI_LVDS1024x768Data_1x75[] = {
{ 960, 438, 1312, 800}, /* 00 (320x200,320x400,640x200,640x400) */
{ 960, 388, 1312, 800}, /* 01 (320x350,640x350) */
{1040, 438, 1312, 800}, /* 02 (360x400,720x400) */
{1040, 388, 1312, 800}, /* 03 (720x350) */
{ 928, 512, 1312, 800}, /* 04 (320x240,640x480) */
{1088, 632, 1312, 800}, /* 05 (400x300,800x600) */
{1312, 800, 1312, 800}, /* 06 (512x384,1024x768) */
};
static struct SiS_LVDSData XGI_LVDS1024x768Data_2x75[] = {
{1312, 800, 1312, 800}, /* ; 00 (320x200,320x400,640x200,640x400) */
{1312, 800, 1312, 800}, /* ; 01 (320x350,640x350) */
{1312, 800, 1312, 800}, /* ; 02 (360x400,720x400) */
{1312, 800, 1312, 800}, /* ; 03 (720x350) */
{1312, 800, 1312, 800}, /* ; 04 (320x240,640x480) */
{1312, 800, 1312, 800}, /* ; 05 (400x300,800x600) */
{1312, 800, 1312, 800}, /* ; 06 (512x384,1024x768) */
};
static struct SiS_LVDSData XGI_LVDS1280x1024Data_1x75[] = {
{1048, 442, 1688, 1066 }, /* ; 00 (320x200,320x400,640x200,640x400) */
{1048, 392, 1688, 1066 }, /* ; 01 (320x350,640x350) */
{1128, 442, 1688, 1066 }, /* ; 02 (360x400,720x400) */
{1128, 392, 1688, 1066 }, /* ; 03 (720x350) */
{1048, 522, 1688, 1066 }, /* ; 04 (320x240,640x480) */
{1208, 642, 1688, 1066 }, /* ; 05 (400x300,800x600) */
{1432, 810, 1688, 1066 }, /* ; 06 (512x384,1024x768) */
{1688, 1066, 1688, 1066 }, /* ; 06; 07 (640x512,1280x1024) */
};
static struct SiS_LVDSData XGI_LVDS1280x1024Data_2x75[] = {
{1688, 1066, 1688, 1066 }, /* ; 00 (320x200,320x400,640x200,640x400) */
{1688, 1066, 1688, 1066 }, /* ; 01 (320x350,640x350) */
{1688, 1066, 1688, 1066 }, /* ; 02 (360x400,720x400) */
{1688, 1066, 1688, 1066 }, /* ; 03 (720x350) */
{1688, 1066, 1688, 1066 }, /* ; 04 (320x240,640x480) */
{1688, 1066, 1688, 1066 }, /* ; 05 (400x300,800x600) */
{1688, 1066, 1688, 1066 }, /* ; 06 (512x384,1024x768) */
{1688, 1066, 1688, 1066 }, /* ; 06; 07 (640x512,1280x1024) */
};
static struct SiS_LVDSData XGI_LVDSNoScalingDatax75[] = {
{ 800, 449, 800, 449}, /* ; 00 (320x200,320x400,640x200,640x400) */
{ 800, 449, 800, 449}, /* ; 01 (320x350,640x350) */
{ 900, 449, 900, 449}, /* ; 02 (360x400,720x400) */
{ 900, 449, 900, 449}, /* ; 03 (720x350) */
{ 800, 500, 800, 500}, /* ; 04 (640x480x75Hz) */
{1056, 625, 1056, 625}, /* ; 05 (800x600x75Hz) */
{1312, 800, 1312, 800}, /* ; 06 (1024x768x75Hz) */
{1688, 1066, 1688, 1066}, /* ; 07 (1280x1024x75Hz) */
{1688, 1066, 1688, 1066}, /* ; 08 (1400x1050x75Hz)
;;[ycchen] 12/19/02 */
{2160, 1250, 2160, 1250}, /* ; 09 (1600x1200x75Hz) */
{1688, 806, 1688, 806}, /* ; 0A (1280x768x75Hz) */
};
static struct SiS_LVDSData XGI_LVDS1024x768Des_1[] = {
{0, 1048, 0, 771}, /* 00 (320x200,320x400,640x200,640x400) */
{0, 1048, 0, 771}, /* 01 (320x350,640x350) */
{0, 1048, 0, 771}, /* 02 (360x400,720x400) */
{0, 1048, 0, 771}, /* 03 (720x350) */
{0, 1048, 0, 771}, /* 04 (640x480x60Hz) */
{0, 1048, 0, 771}, /* 05 (800x600x60Hz) */
{0, 1048, 805, 770} /* 06 (1024x768x60Hz) */
} ;
static struct SiS_LVDSData XGI_LVDS1024x768Des_2[] = {
{1142, 856, 622, 587}, /* 00 (320x200,320x400,640x200,640x400) */
{1142, 856, 597, 562}, /* 01 (320x350,640x350) */
{1142, 856, 622, 587}, /* 02 (360x400,720x400) */
{1142, 856, 597, 562}, /* 03 (720x350) */
{1142, 1048, 722, 687}, /* 04 (640x480x60Hz) */
{1232, 936, 722, 687}, /* 05 (800x600x60Hz) */
{ 0, 1048, 805, 771} /* 06 (1024x768x60Hz) */
};
static struct SiS_LVDSData XGI_LVDS1024x768Des_3[] = {
{320, 24, 622, 587}, /* 00 (320x200,320x400,640x200,640x400) */
{320, 24, 597, 562}, /* 01 (320x350,640x350) */
{320, 24, 622, 587}, /* 02 (360x400,720x400) */
{320, 24, 597, 562}, /* 03 (720x350) */
{320, 24, 722, 687} /* 04 (640x480x60Hz) */
};
static struct SiS_LVDSData XGI_LVDS1280x1024Des_1[] = {
{0, 1328, 0, 1025}, /* 00 (320x200,320x400,640x200,640x400) */
{0, 1328, 0, 1025}, /* 01 (320x350,640x350) */
{0, 1328, 0, 1025}, /* 02 (360x400,720x400) */
{0, 1328, 0, 1025}, /* 03 (720x350) */
{0, 1328, 0, 1025}, /* 04 (640x480x60Hz) */
{0, 1328, 0, 1025}, /* 05 (800x600x60Hz) */
{0, 1328, 0, 1025}, /* 06 (1024x768x60Hz) */
{0, 1328, 1065, 1024} /* 07 (1280x1024x60Hz) */
};
/* The Display setting for DE Mode Panel */
static struct SiS_LVDSData XGI_LVDS1280x1024Des_2[] = {
{1368, 1008, 752, 711}, /* 00 (320x200,320x400,640x200,640x400) */
{1368, 1008, 729, 688}, /* 01 (320x350,640x350) */
{1408, 1048, 752, 711}, /* 02 (360x400,720x400) */
{1408, 1048, 729, 688}, /* 03 (720x350) */
{1368, 1008, 794, 753}, /* 04 (640x480x60Hz) */
{1448, 1068, 854, 813}, /* 05 (800x600x60Hz) */
{1560, 1200, 938, 897}, /* 06 (1024x768x60Hz) */
{0000, 1328, 0, 1025} /* 07 (1280x1024x60Hz) */
};
static struct SiS_LVDSData XGI_LVDS1400x1050Des_1[] = {
{0, 1448, 0, 1051}, /* 00 (320x200,320x400,640x200,640x400) */
{0, 1448, 0, 1051}, /* 01 (320x350,640x350) */
{0, 1448, 0, 1051}, /* 02 (360x400,720x400) */
{0, 1448, 0, 1051}, /* 03 (720x350) */
{0, 1448, 0, 1051}, /* 04 (640x480x60Hz) */
{0, 1448, 0, 1051}, /* 05 (800x600x60Hz) */
{0, 1448, 0, 1051}, /* 06 (1024x768x60Hz) */
{0, 1448, 0, 1051}, /* 07 (1280x1024x60Hz) */
{0, 1448, 0, 1051} /* 08 (1400x1050x60Hz) */
};
static struct SiS_LVDSData XGI_LVDS1400x1050Des_2[] = {
{1308, 1068, 781, 766}, /* 00 (320x200,320x400,640x200,640x400) */
{1308, 1068, 781, 766}, /* 01 (320x350,640x350) */
{1308, 1068, 781, 766}, /* 02 (360x400,720x400) */
{1308, 1068, 781, 766}, /* 03 (720x350) */
{1308, 1068, 781, 766}, /* 04 (640x480x60Hz) */
{1388, 1148, 841, 826}, /* 05 (800x600x60Hz) */
{1490, 1250, 925, 910}, /* 06 (1024x768x60Hz) */
{1608, 1368, 1053, 1038}, /* 07 (1280x1024x60Hz) */
{ 0, 1448, 0, 1051} /* 08 (1400x1050x60Hz) */
};
static struct SiS_LVDSData XGI_LVDS1600x1200Des_1[] = {
{0, 1664, 0, 1201}, /* 00 (320x200,320x400,640x200,640x400) */
{0, 1664, 0, 1201}, /* 01 (320x350,640x350) */
{0, 1664, 0, 1201}, /* 02 (360x400,720x400) */
{0, 1664, 0, 1201}, /* 03 (720x350) */
{0, 1664, 0, 1201}, /* 04 (640x480x60Hz) */
{0, 1664, 0, 1201}, /* 05 (800x600x60Hz) */
{0, 1664, 0, 1201}, /* 06 (1024x768x60Hz) */
{0, 1664, 0, 1201}, /* 07 (1280x1024x60Hz) */
{0, 1664, 0, 1201}, /* 08 (1400x1050x60Hz) */
{0, 1664, 0, 1201} /* 09 (1600x1200x60Hz) */
};
static struct XGI330_LCDDataDesStruct2 XGI_LVDSNoScalingDesData[] = {
{0, 648, 448, 405, 96, 2}, /* 00 (320x200,320x400,
640x200,640x400) */
{0, 648, 448, 355, 96, 2}, /* 01 (320x350,640x350) */
{0, 648, 448, 405, 96, 2}, /* 02 (360x400,720x400) */
{0, 648, 448, 355, 96, 2}, /* 03 (720x350) */
{0, 648, 1, 483, 96, 2}, /* 04 (640x480x60Hz) */
{0, 840, 627, 600, 128, 4}, /* 05 (800x600x60Hz) */
{0, 1048, 805, 770, 136, 6}, /* 06 (1024x768x60Hz) */
{0, 1328, 0, 1025, 112, 3}, /* 07 (1280x1024x60Hz) */
{0, 1438, 0, 1051, 112, 3}, /* 08 (1400x1050x60Hz)*/
{0, 1664, 0, 1201, 192, 3}, /* 09 (1600x1200x60Hz) */
{0, 1328, 0, 0771, 112, 6} /* 0A (1280x768x60Hz) */
};
/* ; 1024x768 Full-screen */
static struct SiS_LVDSData XGI_LVDS1024x768Des_1x75[] = {
{0, 1040, 0, 769}, /* ; 00 (320x200,320x400,640x200,640x400) */
{0, 1040, 0, 769}, /* ; 01 (320x350,640x350) */
{0, 1040, 0, 769}, /* ; 02 (360x400,720x400) */
{0, 1040, 0, 769}, /* ; 03 (720x350) */
{0, 1040, 0, 769}, /* ; 04 (640x480x75Hz) */
{0, 1040, 0, 769}, /* ; 05 (800x600x75Hz) */
{0, 1040, 0, 769} /* ; 06 (1024x768x75Hz) */
};
/* ; 1024x768 center-screen (Enh. Mode) */
static struct SiS_LVDSData XGI_LVDS1024x768Des_2x75[] = {
{1142, 856, 622, 587}, /* 00 (320x200,320x400,640x200,640x400) */
{1142, 856, 597, 562}, /* 01 (320x350,640x350) */
{1142, 856, 622, 587}, /* 02 (360x400,720x400) */
{1142, 856, 597, 562}, /* 03 (720x350) */
{1142, 1048, 722, 687}, /* 04 (640x480x60Hz) */
{1232, 936, 722, 687}, /* 05 (800x600x60Hz) */
{ 0, 1048, 805, 771} /* 06 (1024x768x60Hz) */
};
/* ; 1024x768 center-screen (St.Mode) */
static struct SiS_LVDSData XGI_LVDS1024x768Des_3x75[] = {
{320, 24, 622, 587}, /* ; 00 (320x200,320x400,640x200,640x400) */
{320, 24, 597, 562}, /* ; 01 (320x350,640x350) */
{320, 24, 622, 587}, /* ; 02 (360x400,720x400) */
{320, 24, 597, 562}, /* ; 03 (720x350) */
{320, 24, 722, 687} /* ; 04 (640x480x60Hz) */
};
static struct SiS_LVDSData XGI_LVDS1280x1024Des_1x75[] = {
{0, 1296, 0, 1025}, /* ; 00 (320x200,320x400,640x200,640x400) */
{0, 1296, 0, 1025}, /* ; 01 (320x350,640x350) */
{0, 1296, 0, 1025}, /* ; 02 (360x400,720x400) */
{0, 1296, 0, 1025}, /* ; 03 (720x350) */
{0, 1296, 0, 1025}, /* ; 04 (640x480x75Hz) */
{0, 1296, 0, 1025}, /* ; 05 (800x600x75Hz) */
{0, 1296, 0, 1025}, /* ; 06 (1024x768x75Hz) */
{0, 1296, 0, 1025} /* ; 07 (1280x1024x75Hz) */
};
/* The Display setting for DE Mode Panel */
/* Set DE as default */
static struct SiS_LVDSData XGI_LVDS1280x1024Des_2x75[] = {
{1368, 976, 752, 711}, /* ; 00 (320x200,320x400,640x200,640x400) */
{1368, 976, 729, 688}, /* ; 01 (320x350,640x350) */
{1408, 976, 752, 711}, /* ; 02 (360x400,720x400) */
{1408, 976, 729, 688}, /* ; 03 (720x350) */
{1368, 976, 794, 753}, /* ; 04 (640x480x75Hz) */
{1448, 1036, 854, 813}, /* ; 05 (800x600x75Hz) */
{1560, 1168, 938, 897}, /* ; 06 (1024x768x75Hz) */
{ 0, 1296, 0, 1025} /* ; 07 (1280x1024x75Hz) */
};
/* Scaling LCD 75Hz */
static struct XGI330_LCDDataDesStruct2 XGI_LVDSNoScalingDesDatax75[] = {
{0, 648, 448, 405, 96, 2}, /* ; 00 (320x200,320x400,
640x200,640x400) */
{0, 648, 448, 355, 96, 2}, /* ; 01 (320x350,640x350) */
{0, 729, 448, 405, 108, 2}, /* ; 02 (360x400,720x400) */
{0, 729, 448, 355, 108, 2}, /* ; 03 (720x350) */
{0, 656, 0, 481, 64, 3}, /* ; 04 (640x480x75Hz) */
{0, 816, 0, 601, 80, 3}, /* ; 05 (800x600x75Hz) */
{0, 1040, 0, 769, 96, 3}, /* ; 06 (1024x768x75Hz) */
{0, 1296, 0, 1025, 144, 3}, /* ; 07 (1280x1024x75Hz) */
{0, 1448, 0, 1051, 112, 3}, /* ; 08 (1400x1050x75Hz) */
{0, 1664, 0, 1201, 192, 3}, /* ; 09 (1600x1200x75Hz) */
{0, 1328, 0, 771, 112, 6} /* ; 0A (1280x768x75Hz) */
};
static struct SiS_LVDSData XGI_CHTVUNTSCData[] = {
{ 840, 600, 840, 600},
{ 840, 600, 840, 600},
{ 840, 600, 840, 600},
{ 840, 600, 840, 600},
{ 784, 600, 784, 600},
{1064, 750, 1064, 750}
};
static struct SiS_LVDSData XGI_CHTVONTSCData[] = {
{ 840, 525, 840, 525},
{ 840, 525, 840, 525},
{ 840, 525, 840, 525},
{ 840, 525, 840, 525},
{ 784, 525, 784, 525},
{1040, 700, 1040, 700}
};
static struct SiS_LVDSData XGI_CHTVUPALData[] = {
{1008, 625, 1008, 625},
{1008, 625, 1008, 625},
{1008, 625, 1008, 625},
{1008, 625, 1008, 625},
{ 840, 750, 840, 750},
{ 936, 836, 936, 836}
};
static struct SiS_LVDSData XGI_CHTVOPALData[] = {
{1008, 625, 1008, 625},
{1008, 625, 1008, 625},
{1008, 625, 1008, 625},
{1008, 625, 1008, 625},
{840, 625, 840, 625},
{960, 750, 960, 750}
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11024x768_1_H[] = {
{ {0x4B, 0x27, 0x8F, 0x32, 0x1B, 0x00, 0x45, 0x00} }, /* 00 (320x) */
{ {0x4B, 0x27, 0x8F, 0x2B, 0x03, 0x00, 0x44, 0x00} }, /* 01 (360x) */
{ {0x55, 0x31, 0x99, 0x46, 0x1D, 0x00, 0x55, 0x00} }, /* 02 (400x) */
{ {0x63, 0x3F, 0x87, 0x4A, 0x93, 0x00, 0x01, 0x00} }, /* 03 (512x) */
{ {0x73, 0x4F, 0x97, 0x55, 0x86, 0x00, 0x05, 0x00} }, /* 04 (640x) */
{ {0x73, 0x4F, 0x97, 0x55, 0x86, 0x00, 0x05, 0x00} }, /* 05 (720x) */
{ {0x87, 0x63, 0x8B, 0x69, 0x1A, 0x00, 0x26, 0x00} }, /* 06 (800x) */
{ {0xA3, 0x7F, 0x87, 0x86, 0x97, 0x00, 0x02, 0x00} } /* 07 (1024x) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11280x1024_1_H[] = {
{ {0x56, 0x27, 0x9A, 0x30, 0x1E, 0x00, 0x05, 0x00 } }, /* 00 (320x) */
{ {0x56, 0x27, 0x9A, 0x30, 0x1E, 0x00, 0x05, 0x00 } }, /* 01 (360x) */
{ {0x60, 0x31, 0x84, 0x3A, 0x88, 0x00, 0x01, 0x00 } }, /* 02 (400x) */
{ {0x6E, 0x3F, 0x92, 0x48, 0x96, 0x00, 0x01, 0x00 } }, /* 03 (512x) */
{ {0x7E, 0x4F, 0x82, 0x58, 0x06, 0x00, 0x06, 0x00 } }, /* 04 (640x) */
{ {0x7E, 0x4F, 0x82, 0x58, 0x06, 0x00, 0x06, 0x00 } }, /* 05 (720x) */
{ {0x92, 0x63, 0x96, 0x6C, 0x1A, 0x00, 0x06, 0x00 } }, /* 06 (800x) */
{ {0xAE, 0x7F, 0x92, 0x88, 0x96, 0x00, 0x02, 0x00 } }, /* 07 (1024x) */
{ {0xCE, 0x9F, 0x92, 0xA8, 0x16, 0x00, 0x07, 0x00 } } /* 08 (1280x) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11024x768_2_H[] = {
{ {0x63, 0x27, 0x87, 0x3B, 0x8C, 0x00, 0x01, 0x00} }, /* 00 (320x) */
{ {0x63, 0x27, 0x87, 0x3B, 0x8C, 0x00, 0x01, 0x00} }, /* 01 (360x) */
{ {0x63, 0x31, 0x87, 0x3D, 0x8E, 0x00, 0x01, 0x00} }, /* 02 (400x) */
{ {0x63, 0x3F, 0x87, 0x45, 0x96, 0x00, 0x01, 0x00} }, /* 03 (512x) */
{ {0xA3, 0x4F, 0x87, 0x6E, 0x9F, 0x00, 0x06, 0x00} }, /* 04 (640x) */
{ {0xA3, 0x4F, 0x87, 0x6E, 0x9F, 0x00, 0x06, 0x00} }, /* 05 (720x) */
{ {0xA3, 0x63, 0x87, 0x78, 0x89, 0x00, 0x02, 0x00} }, /* 06 (800x) */
{ {0xA3, 0x7F, 0x87, 0x86, 0x97, 0x00, 0x02, 0x00} } /* 07 (1024x) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11280x1024_2_H[] = {
{ {0x7E, 0x3B, 0x9A, 0x44, 0x12, 0x00, 0x01, 0x00} }, /* 00 (320x) */
{ {0x7E, 0x3B, 0x9A, 0x44, 0x12, 0x00, 0x01, 0x00} }, /* 01 (360x) */
{ {0x7E, 0x40, 0x84, 0x49, 0x91, 0x00, 0x01, 0x00} }, /* 02 (400x) */
{ {0x7E, 0x47, 0x93, 0x50, 0x9E, 0x00, 0x01, 0x00} }, /* 03 (512x) */
{ {0xCE, 0x77, 0x8A, 0x80, 0x8E, 0x00, 0x02, 0x00} }, /* 04 (640x) */
{ {0xCE, 0x77, 0x8A, 0x80, 0x8E, 0x00, 0x02, 0x00} }, /* 05 (720x) */
{ {0xCE, 0x81, 0x94, 0x8A, 0x98, 0x00, 0x02, 0x00} }, /* 06 (800x) */
{ {0xCE, 0x8F, 0x82, 0x98, 0x06, 0x00, 0x07, 0x00} }, /* 07 (1024x) */
{ {0xCE, 0x9F, 0x92, 0xA8, 0x16, 0x00, 0x07, 0x00} } /* 08 (1280x) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11400x1050_1_H[] = {
{ {0x47, 0x27, 0x8B, 0x2C, 0x1A, 0x00, 0x05, 0x00} }, /* 00 (320x) */
{ {0x47, 0x27, 0x8B, 0x30, 0x1E, 0x00, 0x05, 0x00} }, /* 01 (360x) */
{ {0x51, 0x31, 0x95, 0x36, 0x04, 0x00, 0x01, 0x00} }, /* 02 (400x) */
{ {0x5F, 0x3F, 0x83, 0x44, 0x92, 0x00, 0x01, 0x00} }, /* 03 (512x) */
{ {0x6F, 0x4F, 0x93, 0x54, 0x82, 0x00, 0x05, 0x00} }, /* 04 (640x) */
{ {0x6F, 0x4F, 0x93, 0x54, 0x82, 0x00, 0x05, 0x00} }, /* 05 (720x) */
{ {0x83, 0x63, 0x87, 0x68, 0x16, 0x00, 0x06, 0x00} }, /* 06 (800x) */
{ {0x9F, 0x7F, 0x83, 0x84, 0x92, 0x00, 0x02, 0x00} }, /* 07 (1024x) */
{ {0xBF, 0x9F, 0x83, 0xA4, 0x12, 0x00, 0x07, 0x00} }, /* 08 (1280x) */
{ {0xCE, 0xAE, 0x92, 0xB3, 0x01, 0x00, 0x03, 0x00} } /* 09 (1400x) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11400x1050_2_H[] = {
{ {0x76, 0x3F, 0x83, 0x45, 0x8C, 0x00, 0x41, 0x00} }, /* 00 (320x) */
{ {0x76, 0x3F, 0x83, 0x45, 0x8C, 0x00, 0x41, 0x00} }, /* 01 (360x) */
{ {0x76, 0x31, 0x9A, 0x48, 0x9F, 0x00, 0x41, 0x00} }, /* 02 (400x) */
{ {0x76, 0x3F, 0x9A, 0x4F, 0x96, 0x00, 0x41, 0x00} }, /* 03 (512x) */
{ {0xCE, 0x7E, 0x82, 0x87, 0x9E, 0x00, 0x02, 0x00} }, /* 04 (640x) */
{ {0xCE, 0x7E, 0x82, 0x87, 0x9E, 0x00, 0x02, 0x00} }, /* 05 (720x) */
{ {0xCE, 0x63, 0x92, 0x96, 0x04, 0x00, 0x07, 0x00} }, /* 06 (800x) */
{ {0xCE, 0x7F, 0x92, 0xA4, 0x12, 0x00, 0x07, 0x00} }, /* 07 (1024x) */
{ {0xCE, 0x9F, 0x92, 0xB4, 0x02, 0x00, 0x03, 0x00} }, /* 08 (1280x) */
{ {0xCE, 0xAE, 0x92, 0xBC, 0x0A, 0x00, 0x03, 0x00} } /* 09 (1400x) */
};
/* ;302lv channelA [ycchen] 12/05/02 LCDHT=2048 */
/* ; CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11600x1200_1_H[] = {
{ {0x5B, 0x27, 0x9F, 0x32, 0x0A, 0x00, 0x01, 0x00} }, /* 00 (320x) */
{ {0x5B, 0x27, 0x9F, 0x32, 0x0A, 0x00, 0x01, 0x00} }, /* 01 (360x) */
{ {0x65, 0x31, 0x89, 0x3C, 0x94, 0x00, 0x01, 0x00} }, /* 02 (400x) */
{ {0x73, 0x3F, 0x97, 0x4A, 0x82, 0x00, 0x05, 0x00} }, /* 03 (512x) */
{ {0x83, 0x4F, 0x87, 0x51, 0x09, 0x00, 0x06, 0x00} }, /* 04 (640x) */
{ {0x83, 0x4F, 0x87, 0x51, 0x09, 0x00, 0x06, 0x00} }, /* 05 (720x) */
{ {0x97, 0x63, 0x9B, 0x65, 0x1D, 0x00, 0x06, 0xF0} }, /* 06 (800x) */
{ {0xB3, 0x7F, 0x97, 0x81, 0x99, 0x00, 0x02, 0x00} }, /* 07 (1024x) */
{ {0xD3, 0x9F, 0x97, 0xA1, 0x19, 0x00, 0x07, 0x00} }, /* 08 (1280x) */
{ {0xE2, 0xAE, 0x86, 0xB9, 0x91, 0x00, 0x03, 0x00} }, /* 09 (1400x) */
{ {0xFB, 0xC7, 0x9F, 0xC9, 0x81, 0x00, 0x07, 0x00} } /* 0A (1600x) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A+CR09(5->7) */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11024x768_1_V[] = {
{ {0x97, 0x1F, 0x60, 0x87, 0x5D, 0x83, 0x10} }, /* 00 (x350) */
{ {0xB4, 0x1F, 0x92, 0x89, 0x8F, 0xB5, 0x30} }, /* 01 (x400) */
{ {0x04, 0x3E, 0xE2, 0x89, 0xDF, 0x05, 0x00} }, /* 02 (x480) */
{ {0x7C, 0xF0, 0x5A, 0x8F, 0x57, 0x7D, 0xA0} }, /* 03 (x600) */
{ {0x24, 0xF5, 0x02, 0x88, 0xFF, 0x25, 0x90} } /* 04 (x768) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11024x768_2_V[] = {
{ {0x24, 0xBB, 0x31, 0x87, 0x5D, 0x25, 0x30} }, /* 00 (x350) */
{ {0x24, 0xBB, 0x4A, 0x80, 0x8F, 0x25, 0x30} }, /* 01 (x400) */
{ {0x24, 0xBB, 0x72, 0x88, 0xDF, 0x25, 0x30} }, /* 02 (x480) */
{ {0x24, 0xF1, 0xAE, 0x84, 0x57, 0x25, 0xB0} }, /* 03 (x600) */
{ {0x24, 0xF5, 0x02, 0x88, 0xFF, 0x25, 0x90} } /* 04 (x768) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11280x1024_1_V[] = {
{ {0x86, 0x1F, 0x5E, 0x82, 0x5D, 0x87, 0x00} }, /* 00 (x350) */
{ {0xB8, 0x1F, 0x90, 0x84, 0x8F, 0xB9, 0x30} }, /* 01 (x400) */
{ {0x08, 0x3E, 0xE0, 0x84, 0xDF, 0x09, 0x00} }, /* 02 (x480) */
{ {0x80, 0xF0, 0x58, 0x8C, 0x57, 0x81, 0xA0} }, /* 03 (x600) */
{ {0x28, 0xF5, 0x00, 0x84, 0xFF, 0x29, 0x90} }, /* 04 (x768) */
{ {0x28, 0x5A, 0x13, 0x87, 0xFF, 0x29, 0xA9} } /* 05 (x1024) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11280x1024_2_V[] = {
{ {0x28, 0xD2, 0xAF, 0x83, 0xAE, 0xD8, 0xA1} }, /* 00 (x350) */
{ {0x28, 0xD2, 0xC8, 0x8C, 0xC7, 0xF2, 0x81} }, /* 01 (x400) */
{ {0x28, 0xD2, 0xF0, 0x84, 0xEF, 0x1A, 0xB1} }, /* 02 (x480) */
{ {0x28, 0xDE, 0x2C, 0x8F, 0x2B, 0x56, 0x91} }, /* 03 (x600) */
{ {0x28, 0xDE, 0x80, 0x83, 0x7F, 0xAA, 0x91} }, /* 04 (x768) */
{ {0x28, 0x5A, 0x13, 0x87, 0xFF, 0x29, 0xA9} } /* 05 (x1024) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11400x1050_1_V[] = {
{ {0x6C, 0x1F, 0x60, 0x84, 0x5D, 0x6D, 0x10} }, /* 00 (x350) */
{ {0x9E, 0x1F, 0x93, 0x86, 0x8F, 0x9F, 0x30} }, /* 01 (x400) */
{ {0xEE, 0x1F, 0xE2, 0x86, 0xDF, 0xEF, 0x10} }, /* 02 (x480) */
{ {0x66, 0xF0, 0x5A, 0x8e, 0x57, 0x67, 0xA0} }, /* 03 (x600) */
{ {0x0E, 0xF5, 0x02, 0x86, 0xFF, 0x0F, 0x90} }, /* 04 (x768) */
{ {0x0E, 0x5A, 0x02, 0x86, 0xFF, 0x0F, 0x89} }, /* 05 (x1024) */
{ {0x28, 0x10, 0x1A, 0x80, 0x19, 0x29, 0x0F} } /* 06 (x1050) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11400x1050_2_V[] = {
{ {0x28, 0x92, 0xB6, 0x83, 0xB5, 0xCF, 0x81} }, /* 00 (x350) */
{ {0x28, 0x92, 0xD5, 0x82, 0xD4, 0xEE, 0x81} }, /* 01 (x400) */
{ {0x28, 0x92, 0xFD, 0x8A, 0xFC, 0x16, 0xB1} }, /* 02 (x480) */
{ {0x28, 0xD4, 0x39, 0x86, 0x57, 0x29, 0x81} }, /* 03 (x600) */
{ {0x28, 0xD4, 0x8D, 0x9A, 0xFF, 0x29, 0xA1} }, /* 04 (x768) */
{ {0x28, 0x5A, 0x0D, 0x9A, 0xFF, 0x29, 0xA9} }, /* 05 (x1024) */
{ {0x28, 0x10, 0x1A, 0x87, 0x19, 0x29, 0x8F} } /* 06 (x1050) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A+CR09(5->7) */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11600x1200_1_V[] = {
{ {0xd4, 0x1F, 0x81, 0x84, 0x5D, 0xd5, 0x10} }, /* 00 (x350) */
{ {0x06, 0x3e, 0xb3, 0x86, 0x8F, 0x07, 0x20} }, /* 01 (x400) */
{ {0x56, 0xba, 0x03, 0x86, 0xDF, 0x57, 0x00} }, /* 02 (x480) */
{ {0xce, 0xF0, 0x7b, 0x8e, 0x57, 0xcf, 0xa0} }, /* 03 (x600) */
{ {0x76, 0xF5, 0x23, 0x86, 0xFF, 0x77, 0x90} }, /* 04 (x768) */
{ {0x76, 0x5A, 0x23, 0x86, 0xFF, 0x77, 0x89} }, /* 05 (x1024) */
{ {0x90, 0x10, 0x1A, 0x8E, 0x19, 0x91, 0x2F} }, /* 06 (x1050) */
{ {0x26, 0x11, 0xd3, 0x86, 0xaF, 0x27, 0x3f} } /* 07 (x1200) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11024x768_1_Hx75[] = {
{ {0x4B, 0x27, 0x8F, 0x32, 0x1B, 0x00, 0x45, 0x00} },/* ; 00 (320x) */
{ {0x4B, 0x27, 0x8F, 0x2B, 0x03, 0x00, 0x44, 0x00} },/* ; 01 (360x) */
{ {0x55, 0x31, 0x99, 0x46, 0x1D, 0x00, 0x55, 0x00} },/* ; 02 (400x) */
{ {0x63, 0x3F, 0x87, 0x4A, 0x93, 0x00, 0x01, 0x00} },/* ; 03 (512x) */
{ {0x6F, 0x4F, 0x93, 0x54, 0x80, 0x00, 0x05, 0x00} },/* ; 04 (640x) */
{ {0x6F, 0x4F, 0x93, 0x54, 0x80, 0x00, 0x05, 0x00} },/* ; 05 (720x) */
{ {0x83, 0x63, 0x87, 0x68, 0x14, 0x00, 0x26, 0x00} },/* ; 06 (800x) */
{ {0x9F, 0x7F, 0x83, 0x85, 0x91, 0x00, 0x02, 0x00} } /* ; 07 (1024x) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A+CR09(5->7) */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11024x768_1_Vx75[] = {
{ {0x97, 0x1F, 0x60, 0x87, 0x5D, 0x83, 0x10} },/* ; 00 (x350) */
{ {0xB4, 0x1F, 0x92, 0x89, 0x8F, 0xB5, 0x30} },/* ; 01 (x400) */
{ {0xFE, 0x1F, 0xE0, 0x84, 0xDF, 0xFF, 0x10} },/* ; 02 (x480) */
{ {0x76, 0xF0, 0x58, 0x8C, 0x57, 0x77, 0xA0} },/* ; 03 (x600) */
{ {0x1E, 0xF5, 0x00, 0x83, 0xFF, 0x1F, 0x90} } /* ; 04 (x768) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11024x768_2_Hx75[] = {
{ {0x63, 0x27, 0x87, 0x3B, 0x8C, 0x00, 0x01, 0x00} },/* ; 00 (320x) */
{ {0x63, 0x27, 0x87, 0x3B, 0x8C, 0x00, 0x01, 0x00} },/* ; 01 (360x) */
{ {0x63, 0x31, 0x87, 0x3D, 0x8E, 0x00, 0x01, 0x00} },/* ; 02 (400x) */
{ {0x63, 0x3F, 0x87, 0x45, 0x96, 0x00, 0x01, 0x00} },/* ; 03 (512x) */
{ {0xA3, 0x4F, 0x87, 0x6E, 0x9F, 0x00, 0x06, 0x00} },/* ; 04 (640x) */
{ {0xA3, 0x4F, 0x87, 0x6E, 0x9F, 0x00, 0x06, 0x00} },/* ; 05 (720x) */
{ {0xA3, 0x63, 0x87, 0x78, 0x89, 0x00, 0x02, 0x00} },/* ; 06 (800x) */
{ {0xA3, 0x7F, 0x87, 0x86, 0x97, 0x00, 0x02, 0x00} } /* ; 07 (1024x) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11024x768_2_Vx75[] = {
{ {0x24, 0xBB, 0x31, 0x87, 0x5D, 0x25, 0x30} },/* ; 00 (x350) */
{ {0x24, 0xBB, 0x4A, 0x80, 0x8F, 0x25, 0x30} },/* ; 01 (x400) */
{ {0x24, 0xBB, 0x72, 0x88, 0xDF, 0x25, 0x30} },/* ; 02 (x480) */
{ {0x24, 0xF1, 0xAE, 0x84, 0x57, 0x25, 0xB0} },/* ; 03 (x600) */
{ {0x24, 0xF5, 0x02, 0x88, 0xFF, 0x25, 0x90} } /* ; 04 (x768) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11280x1024_1_Hx75[] = {
{ {0x56, 0x27, 0x9A, 0x30, 0x1E, 0x00, 0x05, 0x00} },/* ; 00 (320x) */
{ {0x56, 0x27, 0x9A, 0x30, 0x1E, 0x00, 0x05, 0x00} },/* ; 01 (360x) */
{ {0x60, 0x31, 0x84, 0x3A, 0x88, 0x00, 0x01, 0x00} },/* ; 02 (400x) */
{ {0x6E, 0x3F, 0x92, 0x48, 0x96, 0x00, 0x01, 0x00} },/* ; 03 (512x) */
{ {0x7E, 0x4F, 0x82, 0x54, 0x06, 0x00, 0x06, 0x00} },/* ; 04 (640x) */
{ {0x7E, 0x4F, 0x82, 0x54, 0x06, 0x00, 0x06, 0x00} },/* ; 05 (720x) */
{ {0x92, 0x63, 0x96, 0x68, 0x1A, 0x00, 0x06, 0x00} },/* ; 06 (800x) */
{ {0xAE, 0x7F, 0x92, 0x84, 0x96, 0x00, 0x02, 0x00} },/* ; 07 (1024x) */
{ {0xCE, 0x9F, 0x92, 0xA5, 0x17, 0x00, 0x07, 0x00} } /* ; 08 (1280x) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11280x1024_1_Vx75[] = {
{ {0x86, 0xD1, 0xBC, 0x80, 0xBB, 0xE5, 0x00} },/* ; 00 (x350) */
{ {0xB8, 0x1F, 0x90, 0x84, 0x8F, 0xB9, 0x30} },/* ; 01 (x400) */
{ {0x08, 0x3E, 0xE0, 0x84, 0xDF, 0x09, 0x00} },/* ; 02 (x480) */
{ {0x80, 0xF0, 0x58, 0x8C, 0x57, 0x81, 0xA0} },/* ; 03 (x600) */
{ {0x28, 0xF5, 0x00, 0x84, 0xFF, 0x29, 0x90} },/* ; 04 (x768) */
{ {0x28, 0x5A, 0x13, 0x87, 0xFF, 0x29, 0xA9} } /* ; 05 (x1024) */
};
/* CR00,CR02,CR03,CR04,CR05,SR0B,SR0C,SR0E */
static struct XGI_LVDSCRT1HDataStruct XGI_LVDSCRT11280x1024_2_Hx75[] = {
{ {0x7E, 0x3B, 0x9A, 0x44, 0x12, 0x00, 0x01, 0x00} },/* ; 00 (320x) */
{ {0x7E, 0x3B, 0x9A, 0x44, 0x12, 0x00, 0x01, 0x00} },/* ; 01 (360x) */
{ {0x7E, 0x40, 0x84, 0x49, 0x91, 0x00, 0x01, 0x00} },/* ; 02 (400x) */
{ {0x7E, 0x47, 0x93, 0x50, 0x9E, 0x00, 0x01, 0x00} },/* ; 03 (512x) */
{ {0xCE, 0x77, 0x8A, 0x80, 0x8E, 0x00, 0x02, 0x00} },/* ; 04 (640x) */
{ {0xCE, 0x77, 0x8A, 0x80, 0x8E, 0x00, 0x02, 0x00} },/* ; 05 (720x) */
{ {0xCE, 0x81, 0x94, 0x8A, 0x98, 0x00, 0x02, 0x00} },/* ; 06 (800x) */
{ {0xCE, 0x8F, 0x82, 0x98, 0x06, 0x00, 0x07, 0x00} },/* ; 07 (1024x) */
{ {0xCE, 0x9F, 0x92, 0xA8, 0x16, 0x00, 0x07, 0x00} } /* ; 08 (1280x) */
};
/* CR06,CR07,CR10,CR11,CR15,CR16,SR0A */
static struct XGI_LVDSCRT1VDataStruct XGI_LVDSCRT11280x1024_2_Vx75[] = {
{ {0x28, 0xD2, 0xAF, 0x83, 0xAE, 0xD8, 0xA1} },/* ; 00 (x350) */
{ {0x28, 0xD2, 0xC8, 0x8C, 0xC7, 0xF2, 0x81} },/* ; 01 (x400) */
{ {0x28, 0xD2, 0xF0, 0x84, 0xEF, 0x1A, 0xB1} },/* ; 02 (x480) */
{ {0x28, 0xDE, 0x2C, 0x8F, 0x2B, 0x56, 0x91} },/* ; 03 (x600) */
{ {0x28, 0xDE, 0x80, 0x83, 0x7F, 0xAA, 0x91} },/* ; 04 (x768) */
{ {0x28, 0x5A, 0x13, 0x87, 0xFF, 0x29, 0xA9} } /* ; 05 (x1024) */
};
/*add for new UNIVGABIOS*/
static struct XGI330_LCDDataTablStruct XGI_LCDDataTable[] = {
{Panel_1024x768, 0x0019, 0x0001, 0}, /* XGI_ExtLCD1024x768Data */
{Panel_1024x768, 0x0019, 0x0000, 1}, /* XGI_StLCD1024x768Data */
{Panel_1024x768, 0x0018, 0x0010, 2}, /* XGI_CetLCD1024x768Data */
{Panel_1280x1024, 0x0019, 0x0001, 3}, /* XGI_ExtLCD1280x1024Data */
{Panel_1280x1024, 0x0019, 0x0000, 4}, /* XGI_StLCD1280x1024Data */
{Panel_1280x1024, 0x0018, 0x0010, 5}, /* XGI_CetLCD1280x1024Data */
{Panel_1400x1050, 0x0019, 0x0001, 6}, /* XGI_ExtLCD1400x1050Data */
{Panel_1400x1050, 0x0019, 0x0000, 7}, /* XGI_StLCD1400x1050Data */
{Panel_1400x1050, 0x0018, 0x0010, 8}, /* XGI_CetLCD1400x1050Data */
{Panel_1600x1200, 0x0019, 0x0001, 9}, /* XGI_ExtLCD1600x1200Data */
{Panel_1600x1200, 0x0019, 0x0000, 10}, /* XGI_StLCD1600x1200Data */
{PanelRef60Hz, 0x0008, 0x0008, 11}, /* XGI_NoScalingData */
{Panel_1024x768x75, 0x0019, 0x0001, 12}, /* XGI_ExtLCD1024x768x75Data */
{Panel_1024x768x75, 0x0019, 0x0000, 13}, /* XGI_StLCD1024x768x75Data */
{Panel_1024x768x75, 0x0018, 0x0010, 14}, /* XGI_CetLCD1024x768x75Data */
/* XGI_ExtLCD1280x1024x75Data */
{Panel_1280x1024x75, 0x0019, 0x0001, 15},
/* XGI_StLCD1280x1024x75Data */
{Panel_1280x1024x75, 0x0019, 0x0000, 16},
/* XGI_CetLCD1280x1024x75Data */
{Panel_1280x1024x75, 0x0018, 0x0010, 17},
{PanelRef75Hz, 0x0008, 0x0008, 18}, /* XGI_NoScalingDatax75 */
{0xFF, 0x0000, 0x0000, 0} /* End of table */
};
static struct XGI330_LCDDataTablStruct XGI_LCDDesDataTable[] = {
{Panel_1024x768, 0x0019, 0x0001, 0}, /* XGI_ExtLCDDes1024x768Data */
{Panel_1024x768, 0x0019, 0x0000, 1}, /* XGI_StLCDDes1024x768Data */
{Panel_1024x768, 0x0018, 0x0010, 2}, /* XGI_CetLCDDes1024x768Data */
{Panel_1280x1024, 0x0019, 0x0001, 3}, /* XGI_ExtLCDDes1280x1024Data */
{Panel_1280x1024, 0x0019, 0x0000, 4}, /* XGI_StLCDDes1280x1024Data */
{Panel_1280x1024, 0x0018, 0x0010, 5}, /* XGI_CetLCDDes1280x1024Data */
{Panel_1400x1050, 0x0019, 0x0001, 6}, /* XGI_ExtLCDDes1400x1050Data */
{Panel_1400x1050, 0x0019, 0x0000, 7}, /* XGI_StLCDDes1400x1050Data */
{Panel_1400x1050, 0x0418, 0x0010, 8}, /* XGI_CetLCDDes1400x1050Data */
{Panel_1400x1050, 0x0418, 0x0410, 9}, /* XGI_CetLCDDes1400x1050Data2 */
{Panel_1600x1200, 0x0019, 0x0001, 10}, /* XGI_ExtLCDDes1600x1200Data */
{Panel_1600x1200, 0x0019, 0x0000, 11}, /* XGI_StLCDDes1600x1200Data */
{PanelRef60Hz, 0x0008, 0x0008, 12}, /* XGI_NoScalingDesData */
/* XGI_ExtLCDDes1024x768x75Data */
{Panel_1024x768x75, 0x0019, 0x0001, 13},
/* XGI_StLCDDes1024x768x75Data */
{Panel_1024x768x75, 0x0019, 0x0000, 14},
/* XGI_CetLCDDes1024x768x75Data */
{Panel_1024x768x75, 0x0018, 0x0010, 15},
/* XGI_ExtLCDDes1280x1024x75Data */
{Panel_1280x1024x75, 0x0019, 0x0001, 16},
/* XGI_StLCDDes1280x1024x75Data */
{Panel_1280x1024x75, 0x0019, 0x0000, 17},
/* XGI_CetLCDDes1280x1024x75Data */
{Panel_1280x1024x75, 0x0018, 0x0010, 18},
{PanelRef75Hz, 0x0008, 0x0008, 19}, /* XGI_NoScalingDesDatax75 */
{0xFF, 0x0000, 0x0000, 0}
};
static struct XGI330_LCDDataTablStruct xgifb_epllcd_crt1[] = {
{Panel_1024x768, 0x0018, 0x0000, 0}, /* XGI_LVDSCRT11024x768_1 */
{Panel_1024x768, 0x0018, 0x0010, 1}, /* XGI_LVDSCRT11024x768_2 */
{Panel_1280x1024, 0x0018, 0x0000, 2}, /* XGI_LVDSCRT11280x1024_1 */
{Panel_1280x1024, 0x0018, 0x0010, 3}, /* XGI_LVDSCRT11280x1024_2 */
{Panel_1400x1050, 0x0018, 0x0000, 4}, /* XGI_LVDSCRT11400x1050_1 */
{Panel_1400x1050, 0x0018, 0x0010, 5}, /* XGI_LVDSCRT11400x1050_2 */
{Panel_1600x1200, 0x0018, 0x0000, 6}, /* XGI_LVDSCRT11600x1200_1 */
{Panel_1024x768x75, 0x0018, 0x0000, 7}, /* XGI_LVDSCRT11024x768_1x75 */
{Panel_1024x768x75, 0x0018, 0x0010, 8}, /* XGI_LVDSCRT11024x768_2x75 */
{Panel_1280x1024x75, 0x0018, 0x0000, 9}, /*XGI_LVDSCRT11280x1024_1x75*/
{Panel_1280x1024x75, 0x0018, 0x0010, 10},/*XGI_LVDSCRT11280x1024_2x75*/
{0xFF, 0x0000, 0x0000, 0}
};
static struct XGI330_LCDDataTablStruct XGI_EPLLCDDataPtr[] = {
{Panel_1024x768, 0x0018, 0x0000, 0}, /* XGI_LVDS1024x768Data_1 */
{Panel_1024x768, 0x0018, 0x0010, 1}, /* XGI_LVDS1024x768Data_2 */
{Panel_1280x1024, 0x0018, 0x0000, 2}, /* XGI_LVDS1280x1024Data_1 */
{Panel_1280x1024, 0x0018, 0x0010, 3}, /* XGI_LVDS1280x1024Data_2 */
{Panel_1400x1050, 0x0018, 0x0000, 4}, /* XGI_LVDS1400x1050Data_1 */
{Panel_1400x1050, 0x0018, 0x0010, 5}, /* XGI_LVDS1400x1050Data_2 */
{Panel_1600x1200, 0x0018, 0x0000, 6}, /* XGI_LVDS1600x1200Data_1 */
{PanelRef60Hz, 0x0008, 0x0008, 7}, /* XGI_LVDSNoScalingData */
{Panel_1024x768x75, 0x0018, 0x0000, 8}, /* XGI_LVDS1024x768Data_1x75 */
{Panel_1024x768x75, 0x0018, 0x0010, 9}, /* XGI_LVDS1024x768Data_2x75 */
/* XGI_LVDS1280x1024Data_1x75 */
{Panel_1280x1024x75, 0x0018, 0x0000, 10},
/* XGI_LVDS1280x1024Data_2x75 */
{Panel_1280x1024x75, 0x0018, 0x0010, 11},
{PanelRef75Hz, 0x0008, 0x0008, 12}, /* XGI_LVDSNoScalingDatax75 */
{0xFF, 0x0000, 0x0000, 0}
};
static struct XGI330_LCDDataTablStruct XGI_EPLLCDDesDataPtr[] = {
{Panel_1024x768, 0x0018, 0x0000, 0}, /* XGI_LVDS1024x768Des_1 */
{Panel_1024x768, 0x0618, 0x0410, 1}, /* XGI_LVDS1024x768Des_3 */
{Panel_1024x768, 0x0018, 0x0010, 2}, /* XGI_LVDS1024x768Des_2 */
{Panel_1280x1024, 0x0018, 0x0000, 3}, /* XGI_LVDS1280x1024Des_1 */
{Panel_1280x1024, 0x0018, 0x0010, 4}, /* XGI_LVDS1280x1024Des_2 */
{Panel_1400x1050, 0x0018, 0x0000, 5}, /* XGI_LVDS1400x1050Des_1 */
{Panel_1400x1050, 0x0018, 0x0010, 6}, /* XGI_LVDS1400x1050Des_2 */
{Panel_1600x1200, 0x0018, 0x0000, 7}, /* XGI_LVDS1600x1200Des_1 */
{PanelRef60Hz, 0x0008, 0x0008, 8}, /* XGI_LVDSNoScalingDesData */
{Panel_1024x768x75, 0x0018, 0x0000, 9}, /* XGI_LVDS1024x768Des_1x75 */
{Panel_1024x768x75, 0x0618, 0x0410, 10}, /* XGI_LVDS1024x768Des_3x75 */
{Panel_1024x768x75, 0x0018, 0x0010, 11}, /* XGI_LVDS1024x768Des_2x75 */
/* XGI_LVDS1280x1024Des_1x75 */
{Panel_1280x1024x75, 0x0018, 0x0000, 12},
/* XGI_LVDS1280x1024Des_2x75 */
{Panel_1280x1024x75, 0x0018, 0x0010, 13},
{PanelRef75Hz, 0x0008, 0x0008, 14}, /* XGI_LVDSNoScalingDesDatax75 */
{0xFF, 0x0000, 0x0000, 0}
};
static struct XGI330_LCDDataTablStruct XGI_EPLCHLCDRegPtr[] = {
{Panel_1024x768, 0x0000, 0x0000, 0}, /* XGI_CH7017LV1024x768 */
{Panel_1400x1050, 0x0000, 0x0000, 1}, /* XGI_CH7017LV1400x1050 */
{0xFF, 0x0000, 0x0000, 0}
};
static struct XGI330_TVDataTablStruct XGI_TVDataTable[] = {
{0x09E1, 0x0001, 0}, /* XGI_ExtPALData */
{0x09E1, 0x0000, 1}, /* XGI_ExtNTSCData */
{0x09E1, 0x0801, 2}, /* XGI_StPALData */
{0x09E1, 0x0800, 3}, /* XGI_StNTSCData */
{0x49E0, 0x0100, 4}, /* XGI_ExtHiTVData */
{0x49E0, 0x4100, 5}, /* XGI_St2HiTVData */
{0x49E0, 0x4900, 13}, /* XGI_St1HiTVData */
{0x09E0, 0x0020, 6}, /* XGI_ExtYPbPr525iData */
{0x09E0, 0x0040, 7}, /* XGI_ExtYPbPr525pData */
{0x09E0, 0x0080, 8}, /* XGI_ExtYPbPr750pData */
{0x09E0, 0x0820, 9}, /* XGI_StYPbPr525iData */
{0x09E0, 0x0840, 10}, /* XGI_StYPbPr525pData */
{0x09E0, 0x0880, 11}, /* XGI_StYPbPr750pData */
{0xffff, 0x0000, 12} /* END */
};
/* Chrontel 7017 TV List */
static struct XGI330_TVDataTablStruct xgifb_chrontel_tv[] = {
{0x0011, 0x0000, 0}, /* UNTSC */
{0x0011, 0x0010, 1}, /* ONTSC */
{0x0011, 0x0001, 2}, /* UPAL */
{0x0011, 0x0011, 3}, /* OPAL */
{0xFFFF, 0x0000, 4}
};
static unsigned short LCDLenList[] = {
LVDSCRT1Len_H,
LVDSCRT1Len_V,
LVDSDataLen,
LCDDesDataLen,
LCDDataLen,
LCDDesDataLen,
0,
LCDDesDataLen,
LCDDesDataLen,
0
};
/* Dual link only */
static struct XGI330_LCDCapStruct XGI_LCDDLCapList[] = {
/* LCDCap1024x768 */
{Panel_1024x768, DefaultLCDCap, 0, 0x88, 0x06, VCLK65_315,
0x6C, 0xC3, 0x35, 0x62, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x28, 0x10},
/* LCDCap1280x1024 */
{Panel_1280x1024, XGI_LCDDualLink+DefaultLCDCap, StLCDBToA,
0x70, 0x03, VCLK108_2_315,
0x70, 0x44, 0xF8, 0x2F, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCap1400x1050 */
{Panel_1400x1050, XGI_LCDDualLink+DefaultLCDCap, StLCDBToA,
0x70, 0x03, VCLK108_2_315,
0x70, 0x44, 0xF8, 0x2F, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCap1600x1200 */
{Panel_1600x1200, XGI_LCDDualLink+DefaultLCDCap, LCDToFull,
0xC0, 0x03, VCLK162,
0x43, 0x22, 0x70, 0x24, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCap1024x768x75 */
{Panel_1024x768x75, DefaultLCDCap, 0, 0x60, 0, VCLK78_75,
0x2B, 0x61, 0x2B, 0x61, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x28, 0x10},
/* LCDCap1280x1024x75 */
{Panel_1280x1024x75, XGI_LCDDualLink+DefaultLCDCap, StLCDBToA,
0x90, 0x03, VCLK135_5,
0x54, 0x42, 0x4A, 0x61, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCapDefault */
{0xFF, DefaultLCDCap, 0, 0x88, 0x06, VCLK65_315,
0x6C, 0xC3, 0x35, 0x62, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x28, 0x10}
};
static struct XGI330_LCDCapStruct XGI_LCDCapList[] = {
/* LCDCap1024x768 */
{Panel_1024x768, DefaultLCDCap, 0, 0x88, 0x06, VCLK65_315,
0x6C, 0xC3, 0x35, 0x62, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x28, 0x10},
/* LCDCap1280x1024 */
{Panel_1280x1024, DefaultLCDCap, StLCDBToA,
0x70, 0x03, VCLK108_2_315,
0x70, 0x44, 0xF8, 0x2F, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCap1400x1050 */
{Panel_1400x1050, DefaultLCDCap, StLCDBToA,
0x70, 0x03, VCLK108_2_315,
0x70, 0x44, 0xF8, 0x2F, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCap1600x1200 */
{Panel_1600x1200, DefaultLCDCap, LCDToFull,
0xC0, 0x03, VCLK162,
0x5A, 0x23, 0x5A, 0x23, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCap1024x768x75 */
{Panel_1024x768x75, DefaultLCDCap, 0, 0x60, 0, VCLK78_75,
0x2B, 0x61, 0x2B, 0x61, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x28, 0x10},
/* LCDCap1280x1024x75 */
{Panel_1280x1024x75, DefaultLCDCap, StLCDBToA,
0x90, 0x03, VCLK135_5,
0x54, 0x42, 0x4A, 0x61, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x30, 0x10},
/* LCDCapDefault */
{0xFF, DefaultLCDCap, 0, 0x88, 0x06, VCLK65_315,
0x6C, 0xC3, 0x35, 0x62, 0x02, 0x14, 0x0A, 0x02, 0x00,
0x30, 0x10, 0x5A, 0x10, 0x10, 0x0A, 0xC0, 0x28, 0x10}
};
static struct XGI_Ext2Struct XGI330_RefIndex[] = {
{Mode32Bpp + SupportAllCRT2 + SyncPN, RES320x200, VCLK25_175,
0x00, 0x10, 0x59, 320, 200},/* 00 */
{Mode32Bpp + SupportAllCRT2 + SyncPN, RES320x200, VCLK25_175,
0x00, 0x10, 0x00, 320, 400},/* 01 */
{Mode32Bpp + SupportAllCRT2 + SyncNN, RES320x240, VCLK25_175,
0x04, 0x20, 0x50, 320, 240},/* 02 */
{Mode32Bpp + SupportAllCRT2 + SyncPP, RES400x300, VCLK40,
0x05, 0x32, 0x51, 400, 300},/* 03 */
{Mode32Bpp + NoSupportTV + SyncNN + SupportTV1024, RES512x384,
VCLK65_315, 0x06, 0x43, 0x52, 512, 384},/* 04 */
{Mode32Bpp + SupportAllCRT2 + SyncPN, RES640x400, VCLK25_175,
0x00, 0x14, 0x2f, 640, 400},/* 05 */
{Mode32Bpp + SupportAllCRT2 + SyncNN, RES640x480x60, VCLK25_175,
0x04, 0x24, 0x2e, 640, 480},/* 06 640x480x60Hz (LCD 640x480x60z) */
{Mode32Bpp + NoSupportHiVisionTV + SyncNN, RES640x480x72, VCLK31_5,
0x04, 0x24, 0x2e, 640, 480},/* 07 640x480x72Hz (LCD 640x480x70Hz) */
{Mode32Bpp + NoSupportHiVisionTV + SyncNN, RES640x480x75, VCLK31_5,
0x47, 0x24, 0x2e, 640, 480},/* 08 640x480x75Hz (LCD 640x480x75Hz) */
{Mode32Bpp + SupportRAMDAC2 + SyncNN, RES640x480x85, VCLK36,
0x8A, 0x24, 0x2e, 640, 480},/* 09 640x480x85Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES640x480x100, VCLK43_163,
0x00, 0x24, 0x2e, 640, 480},/* 0a 640x480x100Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES640x480x120, VCLK52_406,
0x00, 0x24, 0x2e, 640, 480},/* 0b 640x480x120Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES640x480x160, VCLK72_852,
0x00, 0x24, 0x2e, 640, 480},/* 0c 640x480x160Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncNN, RES640x480x200, VCLK86_6,
0x00, 0x24, 0x2e, 640, 480},/* 0d 640x480x200Hz */
{Mode32Bpp + NoSupportLCD + SyncPP, RES800x600x56, VCLK36,
0x05, 0x36, 0x6a, 800, 600},/* 0e 800x600x56Hz */
{Mode32Bpp + NoSupportTV + SyncPP, RES800x600x60, VCLK40,
0x05, 0x36, 0x6a, 800, 600},/* 0f 800x600x60Hz (LCD 800x600x60Hz) */
{Mode32Bpp + NoSupportHiVisionTV + SyncPP, RES800x600x72, VCLK50,
0x48, 0x36, 0x6a, 800, 600},/* 10 800x600x72Hz (LCD 800x600x70Hz) */
{Mode32Bpp + NoSupportHiVisionTV + SyncPP, RES800x600x75, VCLK49_5,
0x8B, 0x36, 0x6a, 800, 600},/* 11 800x600x75Hz (LCD 800x600x75Hz) */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES800x600x85, VCLK56_25,
0x00, 0x36, 0x6a, 800, 600},/* 12 800x600x85Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES800x600x100, VCLK68_179,
0x00, 0x36, 0x6a, 800, 600},/* 13 800x600x100Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES800x600x120, VCLK83_95,
0x00, 0x36, 0x6a, 800, 600},/* 14 800x600x120Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES800x600x160, VCLK116_406,
0x00, 0x36, 0x6a, 800, 600},/* 15 800x600x160Hz */
{Mode32Bpp + InterlaceMode + SyncPP, RES1024x768x43, VCLK44_9,
0x00, 0x47, 0x37, 1024, 768},/* 16 1024x768x43Hz */
/* 17 1024x768x60Hz (LCD 1024x768x60Hz) */
{Mode32Bpp + NoSupportTV + SyncNN + SupportTV1024, RES1024x768x60,
VCLK65_315, 0x06, 0x47, 0x37, 1024, 768},
{Mode32Bpp + NoSupportHiVisionTV + SyncNN, RES1024x768x70, VCLK75,
0x49, 0x47, 0x37, 1024, 768},/* 18 1024x768x70Hz (LCD 1024x768x70Hz) */
{Mode32Bpp + NoSupportHiVisionTV + SyncPP, RES1024x768x75, VCLK78_75,
0x00, 0x47, 0x37, 1024, 768},/* 19 1024x768x75Hz (LCD 1024x768x75Hz) */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES1024x768x85, VCLK94_5,
0x8C, 0x47, 0x37, 1024, 768},/* 1a 1024x768x85Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES1024x768x100, VCLK113_309,
0x00, 0x47, 0x37, 1024, 768},/* 1b 1024x768x100Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES1024x768x120, VCLK139_054,
0x00, 0x47, 0x37, 1024, 768},/* 1c 1024x768x120Hz */
{Mode32Bpp + SupportLCD + SyncPP, RES1280x960x60, VCLK108_2_315,
0x08, 0x58, 0x7b, 1280, 960},/* 1d 1280x960x60Hz */
{Mode32Bpp + InterlaceMode + SyncPP, RES1280x1024x43, VCLK78_75,
0x00, 0x58, 0x3a, 1280, 1024},/* 1e 1280x1024x43Hz */
{Mode32Bpp + NoSupportTV + SyncPP, RES1280x1024x60, VCLK108_2_315,
0x07, 0x58, 0x3a, 1280, 1024},/*1f 1280x1024x60Hz (LCD 1280x1024x60Hz)*/
{Mode32Bpp + NoSupportTV + SyncPP, RES1280x1024x75, VCLK135_5,
0x00, 0x58, 0x3a, 1280, 1024},/*20 1280x1024x75Hz (LCD 1280x1024x75Hz)*/
{Mode32Bpp + SyncPP, RES1280x1024x85, VCLK157_5,
0x00, 0x58, 0x3a, 1280, 1024},/* 21 1280x1024x85Hz */
/* 22 1600x1200x60Hz */
{Mode32Bpp + SupportLCD + SyncPP + SupportCRT2in301C,
RES1600x1200x60, VCLK162, 0x09, 0x7A, 0x3c, 1600, 1200},
{Mode32Bpp + SyncPP + SupportCRT2in301C, RES1600x1200x65, VCLK175,
0x00, 0x69, 0x3c, 1600, 1200},/* 23 1600x1200x65Hz */
{Mode32Bpp + SyncPP + SupportCRT2in301C, RES1600x1200x70, VCLK189,
0x00, 0x69, 0x3c, 1600, 1200},/* 24 1600x1200x70Hz */
{Mode32Bpp + SyncPP + SupportCRT2in301C, RES1600x1200x75, VCLK202_5,
0x00, 0x69, 0x3c, 1600, 1200},/* 25 1600x1200x75Hz */
{Mode32Bpp + SyncPP, RES1600x1200x85, VCLK229_5,
0x00, 0x69, 0x3c, 1600, 1200},/* 26 1600x1200x85Hz */
{Mode32Bpp + SyncPP, RES1600x1200x100, VCLK269_655,
0x00, 0x69, 0x3c, 1600, 1200},/* 27 1600x1200x100Hz */
{Mode32Bpp + SyncPP, RES1600x1200x120, VCLK323_586,
0x00, 0x69, 0x3c, 1600, 1200},/* 28 1600x1200x120Hz */
{Mode32Bpp + SupportLCD + SyncNP, RES1920x1440x60, VCLK234,
0x00, 0x00, 0x68, 1920, 1440},/* 29 1920x1440x60Hz */
{Mode32Bpp + SyncPN, RES1920x1440x65, VCLK254_817,
0x00, 0x00, 0x68, 1920, 1440},/* 2a 1920x1440x65Hz */
{Mode32Bpp + SyncPN, RES1920x1440x70, VCLK277_015,
0x00, 0x00, 0x68, 1920, 1440},/* 2b 1920x1440x70Hz */
{Mode32Bpp + SyncPN, RES1920x1440x75, VCLK291_132,
0x00, 0x00, 0x68, 1920, 1440},/* 2c 1920x1440x75Hz */
{Mode32Bpp + SyncPN, RES1920x1440x85, VCLK330_615,
0x00, 0x00, 0x68, 1920, 1440},/* 2d 1920x1440x85Hz */
{Mode16Bpp + SyncPN, RES1920x1440x100, VCLK388_631,
0x00, 0x00, 0x68, 1920, 1440},/* 2e 1920x1440x100Hz */
{Mode32Bpp + SupportLCD + SyncPN, RES2048x1536x60, VCLK266_952,
0x00, 0x00, 0x6c, 2048, 1536},/* 2f 2048x1536x60Hz */
{Mode32Bpp + SyncPN, RES2048x1536x65, VCLK291_766,
0x00, 0x00, 0x6c, 2048, 1536},/* 30 2048x1536x65Hz */
{Mode32Bpp + SyncPN, RES2048x1536x70, VCLK315_195,
0x00, 0x00, 0x6c, 2048, 1536},/* 31 2048x1536x70Hz */
{Mode32Bpp + SyncPN, RES2048x1536x75, VCLK340_477,
0x00, 0x00, 0x6c, 2048, 1536},/* 32 2048x1536x75Hz */
{Mode16Bpp + SyncPN, RES2048x1536x85, VCLK375_847,
0x00, 0x00, 0x6c, 2048, 1536},/* 33 2048x1536x85Hz */
{Mode32Bpp + SupportHiVision + SupportRAMDAC2 +
SyncPP + SupportYPbPr750p, RES800x480x60, VCLK39_77,
0x08, 0x00, 0x70, 800, 480},/* 34 800x480x60Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES800x480x75, VCLK49_5,
0x08, 0x00, 0x70, 800, 480},/* 35 800x480x75Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES800x480x85, VCLK56_25,
0x08, 0x00, 0x70, 800, 480},/* 36 800x480x85Hz */
{Mode32Bpp + SupportHiVision + SupportRAMDAC2 +
SyncPP + SupportYPbPr750p, RES1024x576x60, VCLK65_315,
0x09, 0x00, 0x71, 1024, 576},/* 37 1024x576x60Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES1024x576x75, VCLK78_75,
0x09, 0x00, 0x71, 1024, 576},/* 38 1024x576x75Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES1024x576x85, VCLK94_5,
0x09, 0x00, 0x71, 1024, 576},/* 39 1024x576x85Hz */
{Mode32Bpp + SupportHiVision + SupportRAMDAC2 +
SyncPP + SupportYPbPr750p, RES1280x720x60, VCLK108_2_315,
0x0A, 0x00, 0x75, 1280, 720},/* 3a 1280x720x60Hz*/
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES1280x720x75, VCLK135_5,
0x0A, 0x00, 0x75, 1280, 720},/* 3b 1280x720x75Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES1280x720x85, VCLK157_5,
0x0A, 0x00, 0x75, 1280, 720},/* 3c 1280x720x85Hz */
{Mode32Bpp + SupportTV + SyncNN, RES720x480x60, VCLK28_322,
0x06, 0x00, 0x31, 720, 480},/* 3d 720x480x60Hz */
{Mode32Bpp + SupportTV + SyncPP, RES720x576x56, VCLK36,
0x06, 0x00, 0x32, 720, 576},/* 3e 720x576x56Hz */
{Mode32Bpp + InterlaceMode + NoSupportLCD + SyncPP, RES856x480x79I,
VCLK35_2, 0x00, 0x00, 0x00, 856, 480},/* 3f 856x480x79I */
{Mode32Bpp + NoSupportLCD + SyncNN, RES856x480x60, VCLK35_2,
0x00, 0x00, 0x00, 856, 480},/* 40 856x480x60Hz */
{Mode32Bpp + NoSupportHiVisionTV + SyncPP, RES1280x768x60,
VCLK79_411, 0x08, 0x48, 0x23, 1280, 768},/* 41 1280x768x60Hz */
{Mode32Bpp + NoSupportHiVisionTV + SyncPP, RES1400x1050x60,
VCLK122_61, 0x08, 0x69, 0x26, 1400, 1050},/* 42 1400x1050x60Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES1152x864x60, VCLK80_350,
0x37, 0x00, 0x20, 1152, 864},/* 43 1152x864x60Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPP, RES1152x864x75, VCLK107_385,
0x37, 0x00, 0x20, 1152, 864},/* 44 1152x864x75Hz */
{Mode32Bpp + SupportLCD + SupportRAMDAC2 + SyncPP, RES1280x960x75,
VCLK125_999, 0x3A, 0x88, 0x7b, 1280, 960},/* 45 1280x960x75Hz */
{Mode32Bpp + SupportLCD + SupportRAMDAC2 + SyncPP, RES1280x960x85,
VCLK148_5, 0x0A, 0x88, 0x7b, 1280, 960},/* 46 1280x960x85Hz */
{Mode32Bpp + SupportLCD + SupportRAMDAC2 + SyncPP, RES1280x960x120,
VCLK217_325, 0x3A, 0x88, 0x7b, 1280, 960},/* 47 1280x960x120Hz */
{Mode32Bpp + SupportRAMDAC2 + SyncPN, RES1024x768x160, VCLK139_054,
0x30, 0x47, 0x37, 1024, 768},/* 48 1024x768x160Hz */
};
static unsigned char XGI330_ScreenOffset[] = {
0x14, 0x19, 0x20, 0x28, 0x32, 0x40,
0x50, 0x64, 0x78, 0x80, 0x2d, 0x35,
0x57, 0x48
};
static struct SiS_StResInfo_S XGI330_StResInfo[] = {
{640, 400},
{640, 350},
{720, 400},
{720, 350},
{640, 480}
};
static struct SiS_ModeResInfo_S XGI330_ModeResInfo[] = {
{ 320, 200, 8, 8},
{ 320, 240, 8, 8},
{ 320, 400, 8, 8},
{ 400, 300, 8, 8},
{ 512, 384, 8, 8},
{ 640, 400, 8, 16},
{ 640, 480, 8, 16},
{ 800, 600, 8, 16},
{1024, 768, 8, 16},
{1280, 1024, 8, 16},
{1600, 1200, 8, 16},
{1920, 1440, 8, 16},
{2048, 1536, 8, 16},
{ 720, 480, 8, 16},
{ 720, 576, 8, 16},
{1280, 960, 8, 16},
{ 800, 480, 8, 16},
{1024, 576, 8, 16},
{1280, 720, 8, 16},
{ 856, 480, 8, 16},
{1280, 768, 8, 16},
{1400, 1050, 8, 16},
{1152, 864, 8, 16}
};
static struct SiS_VCLKData XGI_VCLKData[] = {
/* SR2B,SR2C,SR2D */
{0x1B, 0xE1, 25}, /* 00 (25.175MHz) */
{0x4E, 0xE4, 28}, /* 01 (28.322MHz) */
{0x57, 0xE4, 31}, /* 02 (31.500MHz) */
{0xC3, 0xC8, 36}, /* 03 (36.000MHz) */
{0x42, 0xE2, 40}, /* 04 (40.000MHz) */
{0xFE, 0xCD, 43}, /* 05 (43.163MHz) */
{0x5D, 0xC4, 44}, /* 06 (44.900MHz) */
{0x52, 0xE2, 49}, /* 07 (49.500MHz) */
{0x53, 0xE2, 50}, /* 08 (50.000MHz) */
{0x74, 0x67, 52}, /* 09 (52.406MHz) */
{0x6D, 0x66, 56}, /* 0A (56.250MHz) */
{0x6C, 0xC3, 65}, /* 0B (65.000MHz) */
{0x46, 0x44, 67}, /* 0C (67.765MHz) */
{0xB1, 0x46, 68}, /* 0D (68.179MHz) */
{0xD3, 0x4A, 72}, /* 0E (72.852MHz) */
{0x29, 0x61, 75}, /* 0F (75.000MHz) */
{0x6E, 0x46, 76}, /* 10 (75.800MHz) */
{0x2B, 0x61, 78}, /* 11 (78.750MHz) */
{0x31, 0x42, 79}, /* 12 (79.411MHz) */
{0xAB, 0x44, 83}, /* 13 (83.950MHz) */
{0x46, 0x25, 84}, /* 14 (84.800MHz) */
{0x78, 0x29, 86}, /* 15 (86.600MHz) */
{0x62, 0x44, 94}, /* 16 (94.500MHz) */
{0x2B, 0x41, 104}, /* 17 (104.998MHz) */
{0x3A, 0x23, 105}, /* 18 (105.882MHz) */
{0x70, 0x44, 108}, /* 19 (107.862MHz) */
{0x3C, 0x23, 109}, /* 1A (109.175MHz) */
{0x5E, 0x43, 113}, /* 1B (113.309MHz) */
{0xBC, 0x44, 116}, /* 1C (116.406MHz) */
{0xE0, 0x46, 132}, /* 1D (132.258MHz) */
{0x54, 0x42, 135}, /* 1E (135.500MHz) */
{0x9C, 0x22, 139}, /* 1F (139.275MHz) */
{0x41, 0x22, 157}, /* 20 (157.500MHz) */
{0x70, 0x24, 162}, /* 21 (161.793MHz) */
{0x30, 0x21, 175}, /* 22 (175.000MHz) */
{0x4E, 0x22, 189}, /* 23 (188.520MHz) */
{0xDE, 0x26, 194}, /* 24 (194.400MHz) */
{0x62, 0x06, 202}, /* 25 (202.500MHz) */
{0x3F, 0x03, 229}, /* 26 (229.500MHz) */
{0xB8, 0x06, 234}, /* 27 (233.178MHz) */
{0x34, 0x02, 253}, /* 28 (252.699MHz) */
{0x58, 0x04, 255}, /* 29 (254.817MHz) */
{0x24, 0x01, 265}, /* 2A (265.728MHz) */
{0x9B, 0x02, 267}, /* 2B (266.952MHz) */
{0x70, 0x05, 270}, /* 2C (269.65567MHz) */
{0x25, 0x01, 272}, /* 2D (272.04199MHz) */
{0x9C, 0x02, 277}, /* 2E (277.015MHz) */
{0x27, 0x01, 286}, /* 2F (286.359985MHz) */
{0xB3, 0x04, 291}, /* 30 (291.13266MHz) */
{0xBC, 0x05, 292}, /* 31 (291.766MHz) */
{0xF6, 0x0A, 310}, /* 32 (309.789459MHz) */
{0x95, 0x01, 315}, /* 33 (315.195MHz) */
{0xF0, 0x09, 324}, /* 34 (323.586792MHz) */
{0xFE, 0x0A, 331}, /* 35 (330.615631MHz) */
{0xF3, 0x09, 332}, /* 36 (332.177612MHz) */
{0x5E, 0x03, 340}, /* 37 (340.477MHz) */
{0xE8, 0x07, 376}, /* 38 (375.847504MHz) */
{0xDE, 0x06, 389}, /* 39 (388.631439MHz) */
{0x52, 0x2A, 54}, /* 3A (54.000MHz) */
{0x52, 0x6A, 27}, /* 3B (27.000MHz) */
{0x62, 0x24, 70}, /* 3C (70.874991MHz) */
{0x62, 0x64, 70}, /* 3D (70.1048912MHz) */
{0xA8, 0x4C, 30}, /* 3E (30.1048912MHz) */
{0x20, 0x26, 33}, /* 3F (33.7499957MHz) */
{0x31, 0xc2, 39}, /* 40 (39.77MHz) */
{0x11, 0x21, 30}, /* 41 (30MHz) }// NTSC 1024X768 */
{0x2E, 0x48, 25}, /* 42 (25.175MHz) }// ScaleLCD */
{0x24, 0x46, 25}, /* 43 (25.175MHz) */
{0x26, 0x64, 28}, /* 44 (28.322MHz) */
{0x37, 0x64, 40}, /* 45 (40.000MHz) */
{0xA1, 0x42, 108}, /* 46 (95.000MHz) }// QVGA */
{0x37, 0x61, 100}, /* 47 (100.00MHz) */
{0x78, 0x27, 108}, /* 48 (108.200MHz) */
{0xBF, 0xC8, 35}, /* 49 (35.2MHz) */
{0x66, 0x43, 123}, /* 4A (122.61Mhz) */
{0x2C, 0x61, 80}, /* 4B (80.350Mhz) */
{0x3B, 0x61, 108}, /* 4C (107.385Mhz) */
{0x69, 0x61, 191}, /* 4D (190.96MHz ) */
{0x4F, 0x22, 192}, /* 4E (192.069MHz) */
{0x28, 0x26, 322}, /* 4F (322.273MHz) */
{0x5C, 0x6B, 27}, /* 50 (27.74HMz) */
{0x57, 0x24, 126}, /* 51 (125.999MHz) */
{0x5C, 0x42, 148}, /* 52 (148.5MHz) */
{0x42, 0x61, 120}, /* 53 (120.839MHz) */
{0x62, 0x61, 178}, /* 54 (178.992MHz) */
{0x59, 0x22, 217}, /* 55 (217.325MHz) */
{0x29, 0x01, 300}, /* 56 (299.505Mhz) */
{0x52, 0x63, 74}, /* 57 (74.25MHz) */
{0xFF, 0x00, 0} /* End mark */
};
static struct SiS_VCLKData XGI_VBVCLKData[] = {
{0x1B, 0xE1, 25}, /* 00 (25.175MHz) */
{0x4E, 0xE4, 28}, /* 01 (28.322MHz) */
{0x57, 0xE4, 31}, /* 02 (31.500MHz) */
{0xC3, 0xC8, 36}, /* 03 (36.000MHz) */
{0x42, 0x47, 40}, /* 04 (40.000MHz) */
{0xFE, 0xCD, 43}, /* 05 (43.163MHz) */
{0x5D, 0xC4, 44}, /* 06 (44.900MHz) */
{0x52, 0x47, 49}, /* 07 (49.500MHz) */
{0x53, 0x47, 50}, /* 08 (50.000MHz) */
{0x74, 0x67, 52}, /* 09 (52.406MHz) */
{0x6D, 0x66, 56}, /* 0A (56.250MHz) */
{0x35, 0x62, 65}, /* 0B (65.000MHz) */
{0x46, 0x44, 67}, /* 0C (67.765MHz) */
{0xB1, 0x46, 68}, /* 0D (68.179MHz) */
{0xD3, 0x4A, 72}, /* 0E (72.852MHz) */
{0x29, 0x61, 75}, /* 0F (75.000MHz) */
{0x6D, 0x46, 75}, /* 10 (75.800MHz) */
{0x41, 0x43, 78}, /* 11 (78.750MHz) */
{0x31, 0x42, 79}, /* 12 (79.411MHz) */
{0xAB, 0x44, 83}, /* 13 (83.950MHz) */
{0x46, 0x25, 84}, /* 14 (84.800MHz) */
{0x78, 0x29, 86}, /* 15 (86.600MHz) */
{0x62, 0x44, 94}, /* 16 (94.500MHz) */
{0x2B, 0x22, 104}, /* 17 (104.998MHz) */
{0x49, 0x24, 105}, /* 18 (105.882MHz) */
{0xF8, 0x2F, 108}, /* 19 (108.279MHz) */
{0x3C, 0x23, 109}, /* 1A (109.175MHz) */
{0x5E, 0x43, 113}, /* 1B (113.309MHz) */
{0xBC, 0x44, 116}, /* 1C (116.406MHz) */
{0xE0, 0x46, 132}, /* 1D (132.258MHz) */
{0xD4, 0x28, 135}, /* 1E (135.220MHz) */
{0xEA, 0x2A, 139}, /* 1F (139.275MHz) */
{0x41, 0x22, 157}, /* 20 (157.500MHz) */
{0x70, 0x24, 162}, /* 21 (161.793MHz) */
{0x30, 0x21, 175}, /* 22 (175.000MHz) */
{0x4E, 0x22, 189}, /* 23 (188.520MHz) */
{0xDE, 0x26, 194}, /* 24 (194.400MHz) */
{0x70, 0x07, 202}, /* 25 (202.500MHz) */
{0x3F, 0x03, 229}, /* 26 (229.500MHz) */
{0xB8, 0x06, 234}, /* 27 (233.178MHz) */
{0x34, 0x02, 253}, /* 28 (252.699997 MHz) */
{0x58, 0x04, 255}, /* 29 (254.817MHz) */
{0x24, 0x01, 265}, /* 2A (265.728MHz) */
{0x9B, 0x02, 267}, /* 2B (266.952MHz) */
{0x70, 0x05, 270}, /* 2C (269.65567 MHz) */
{0x25, 0x01, 272}, /* 2D (272.041992 MHz) */
{0x9C, 0x02, 277}, /* 2E (277.015MHz) */
{0x27, 0x01, 286}, /* 2F (286.359985 MHz) */
{0x3C, 0x02, 291}, /* 30 (291.132660 MHz) */
{0xEF, 0x0A, 292}, /* 31 (291.766MHz) */
{0xF6, 0x0A, 310}, /* 32 (309.789459 MHz) */
{0x95, 0x01, 315}, /* 33 (315.195MHz) */
{0xF0, 0x09, 324}, /* 34 (323.586792 MHz) */
{0xFE, 0x0A, 331}, /* 35 (330.615631 MHz) */
{0xF3, 0x09, 332}, /* 36 (332.177612 MHz) */
{0xEA, 0x08, 340}, /* 37 (340.477MHz) */
{0xE8, 0x07, 376}, /* 38 (375.847504 MHz) */
{0xDE, 0x06, 389}, /* 39 (388.631439 MHz) */
{0x52, 0x2A, 54}, /* 3A (54.000MHz) */
{0x52, 0x6A, 27}, /* 3B (27.000MHz) */
{0x62, 0x24, 70}, /* 3C (70.874991MHz) */
{0x62, 0x64, 70}, /* 3D (70.1048912MHz) */
{0xA8, 0x4C, 30}, /* 3E (30.1048912MHz) */
{0x20, 0x26, 33}, /* 3F (33.7499957MHz) */
{0x31, 0xc2, 39}, /* 40 (39.77MHz) */
{0x11, 0x21, 30}, /* 41 (30MHz) }// NTSC 1024X768 */
{0x2E, 0x48, 25}, /* 42 (25.175MHz) }// ScaleLCD */
{0x24, 0x46, 25}, /* 43 (25.175MHz) */
{0x26, 0x64, 28}, /* 44 (28.322MHz) */
{0x37, 0x64, 40}, /* 45 (40.000MHz) */
{0xA1, 0x42, 108}, /* 46 (95.000MHz) }// QVGA */
{0x37, 0x61, 100}, /* 47 (100.00MHz) */
{0x78, 0x27, 108}, /* 48 (108.200MHz) */
{0xBF, 0xC8, 35 }, /* 49 (35.2MHz) */
{0x66, 0x43, 123}, /* 4A (122.61Mhz) */
{0x2C, 0x61, 80 }, /* 4B (80.350Mhz) */
{0x3B, 0x61, 108}, /* 4C (107.385Mhz) */
{0x69, 0x61, 191}, /* 4D (190.96MHz ) */
{0x4F, 0x22, 192}, /* 4E (192.069MHz) */
{0x28, 0x26, 322}, /* 4F (322.273MHz) */
{0x5C, 0x6B, 27}, /* 50 (27.74HMz) */
{0x57, 0x24, 126}, /* 51 (125.999MHz) */
{0x5C, 0x42, 148}, /* 52 (148.5MHz) */
{0x42, 0x61, 120}, /* 53 (120.839MHz) */
{0x62, 0x61, 178}, /* 54 (178.992MHz) */
{0x59, 0x22, 217}, /* 55 (217.325MHz) */
{0x29, 0x01, 300}, /* 56 (299.505Mhz) */
{0x52, 0x63, 74}, /* 57 (74.25MHz) */
{0xFF, 0x00, 0} /* End mark */
};
#define XGI301TVDelay 0x22
#define XGI301LCDDelay 0x12
static unsigned char TVAntiFlickList[] = {/* NTSCAntiFlicker */
0x04, /* ; 0 Adaptive */
0x00, /* ; 1 new anti-flicker ? */
0x04, /* ; 0 Adaptive */
0x08, /* ; 1 new anti-flicker ? */
0x04, /* ; 0 ? */
0x00 /* ; 1 new anti-flicker ? */
};
static unsigned char TVEdgeList[] = {
0x00, /* ; 0 NTSC No Edge enhance */
0x04, /* ; 1 NTSC Adaptive Edge enhance */
0x00, /* ; 0 PAL No Edge enhance */
0x04, /* ; 1 PAL Adaptive Edge enhance */
0x00, /* ; 0 HiTV */
0x00 /* ; 1 HiTV */
};
static unsigned long TVPhaseList[] = {
0x08BAED21, /* ; 0 NTSC phase */
0x00E3052A, /* ; 1 PAL phase */
0x9B2EE421, /* ; 2 PAL-M phase */
0xBA3EF421, /* ; 3 PAL-N phase */
0xA7A28B1E, /* ; 4 NTSC 1024x768 */
0xE00A831E, /* ; 5 PAL-M 1024x768 */
0x00000000, /* ; 6 reserved */
0x00000000, /* ; 7 reserved */
0xD67BF021, /* ; 8 NTSC phase */
0xE986092A, /* ; 9 PAL phase */
0xA4EFE621, /* ; A PAL-M phase */
0x4694F621, /* ; B PAL-N phase */
0x8BDE711C, /* ; C NTSC 1024x768 */
0xE00A831E /* ; D PAL-M 1024x768 */
};
static unsigned char NTSCYFilter1[] = {
0x00, 0xF4, 0x10, 0x38, /* 0 : 320x text mode */
0x00, 0xF4, 0x10, 0x38, /* 1 : 360x text mode */
0xEB, 0x04, 0x25, 0x18, /* 2 : 640x text mode */
0xF1, 0x04, 0x1F, 0x18, /* 3 : 720x text mode */
0x00, 0xF4, 0x10, 0x38, /* 4 : 320x gra. mode */
0xEB, 0x04, 0x25, 0x18, /* 5 : 640x gra. mode */
0xEB, 0x15, 0x25, 0xF6 /* 6 : 800x gra. mode */
};
static unsigned char PALYFilter1[] = {
0x00, 0xF4, 0x10, 0x38, /* 0 : 320x text mode */
0x00, 0xF4, 0x10, 0x38, /* 1 : 360x text mode */
0xF1, 0xF7, 0x1F, 0x32, /* 2 : 640x text mode */
0xF3, 0x00, 0x1D, 0x20, /* 3 : 720x text mode */
0x00, 0xF4, 0x10, 0x38, /* 4 : 320x gra. mode */
0xF1, 0xF7, 0x1F, 0x32, /* 5 : 640x gra. mode */
0xFC, 0xFB, 0x14, 0x2A /* 6 : 800x gra. mode */
};
static unsigned char xgifb_palmn_yfilter1[] = {
0x00, 0xF4, 0x10, 0x38, /* 0 : 320x text mode */
0x00, 0xF4, 0x10, 0x38, /* 1 : 360x text mode */
0xEB, 0x04, 0x10, 0x18, /* 2 : 640x text mode */
0xF7, 0x06, 0x19, 0x14, /* 3 : 720x text mode */
0x00, 0xF4, 0x10, 0x38, /* 4 : 320x gra. mode */
0xEB, 0x04, 0x25, 0x18, /* 5 : 640x gra. mode */
0xEB, 0x15, 0x25, 0xF6, /* 6 : 800x gra. mode */
0xFF, 0xFF, 0xFF, 0xFF /* End of Table */
};
static unsigned char xgifb_yfilter2[] = {
0xFF, 0x03, 0x02, 0xF6, 0xFC, 0x27, 0x46, /* 0 : 320x text mode */
0x01, 0x02, 0xFE, 0xF7, 0x03, 0x27, 0x3C, /* 1 : 360x text mode */
0xFF, 0x03, 0x02, 0xF6, 0xFC, 0x27, 0x46, /* 2 : 640x text mode */
0x01, 0x02, 0xFE, 0xF7, 0x03, 0x27, 0x3C, /* 3 : 720x text mode */
0xFF, 0x03, 0x02, 0xF6, 0xFC, 0x27, 0x46, /* 4 : 320x gra. mode */
0xFF, 0x03, 0x02, 0xF6, 0xFC, 0x27, 0x46, /* 5 : 640x gra. mode */
0x01, 0x01, 0xFC, 0xF8, 0x08, 0x26, 0x38, /* 6 : 800x gra. mode */
0xFF, 0xFF, 0xFC, 0x00, 0x0F, 0x22, 0x28 /* 7 : 1024xgra. mode */
};
static unsigned char XGI_NTSC1024AdjTime[] = {
0xa7, 0x07, 0xf2, 0x6e, 0x17, 0x8b, 0x73, 0x53,
0x13, 0x40, 0x34, 0xF4, 0x63, 0xBB, 0xCC, 0x7A,
0x58, 0xe4, 0x73, 0xd0, 0x13
};
static struct XGI301C_Tap4TimingStruct xgifb_tap4_timing[] = {
{0, {
0x00, 0x20, 0x00, 0x00, 0x7F, 0x20, 0x02, 0x7F, /* ; C0-C7 */
0x7D, 0x20, 0x04, 0x7F, 0x7D, 0x1F, 0x06, 0x7E, /* ; C8-CF */
0x7C, 0x1D, 0x09, 0x7E, 0x7C, 0x1B, 0x0B, 0x7E, /* ; D0-D7 */
0x7C, 0x19, 0x0E, 0x7D, 0x7C, 0x17, 0x11, 0x7C, /* ; D8-DF */
0x7C, 0x14, 0x14, 0x7C, 0x7C, 0x11, 0x17, 0x7C, /* ; E0-E7 */
0x7D, 0x0E, 0x19, 0x7C, 0x7E, 0x0B, 0x1B, 0x7C, /* ; EA-EF */
0x7E, 0x09, 0x1D, 0x7C, 0x7F, 0x06, 0x1F, 0x7C, /* ; F0-F7 */
0x7F, 0x04, 0x20, 0x7D, 0x00, 0x02, 0x20, 0x7E /* ; F8-FF */
}
}
};
static struct XGI301C_Tap4TimingStruct PALTap4Timing[] = {
{600, {
0x05, 0x19, 0x05, 0x7D, 0x03, 0x19, 0x06, 0x7E, /* ; C0-C7 */
0x02, 0x19, 0x08, 0x7D, 0x01, 0x18, 0x0A, 0x7D, /* ; C8-CF */
0x00, 0x18, 0x0C, 0x7C, 0x7F, 0x17, 0x0E, 0x7C, /* ; D0-D7 */
0x7E, 0x16, 0x0F, 0x7D, 0x7E, 0x14, 0x11, 0x7D, /* ; D8-DF */
0x7D, 0x13, 0x13, 0x7D, 0x7D, 0x11, 0x14, 0x7E, /* ; E0-E7 */
0x7D, 0x0F, 0x16, 0x7E, 0x7D, 0x0E, 0x17, 0x7E, /* ; EA-EF */
0x7D, 0x0C, 0x18, 0x7F, 0x7D, 0x0A, 0x18, 0x01, /* ; F0-F7 */
0x7D, 0x08, 0x19, 0x02, 0x7D, 0x06, 0x19, 0x04 /* ; F8-FF */
}
},
{768, {
0x08, 0x12, 0x08, 0x7E, 0x07, 0x12, 0x09, 0x7E, /* ; C0-C7 */
0x06, 0x12, 0x0A, 0x7E, 0x05, 0x11, 0x0B, 0x7F, /* ; C8-CF */
0x04, 0x11, 0x0C, 0x7F, 0x03, 0x11, 0x0C, 0x00, /* ; D0-D7 */
0x03, 0x10, 0x0D, 0x00, 0x02, 0x0F, 0x0E, 0x01, /* ; D8-DF */
0x01, 0x0F, 0x0F, 0x01, 0x01, 0x0E, 0x0F, 0x02, /* ; E0-E7 */
0x00, 0x0D, 0x10, 0x03, 0x7F, 0x0C, 0x11, 0x04, /* ; EA-EF */
0x7F, 0x0C, 0x11, 0x04, 0x7F, 0x0B, 0x11, 0x05, /* ; F0-F7 */
0x7E, 0x0A, 0x12, 0x06, 0x7E, 0x09, 0x12, 0x07 /* ; F8-FF */
}
},
{0xFFFF, {
0x04, 0x1A, 0x04, 0x7E, 0x02, 0x1B, 0x05, 0x7E, /* ; C0-C7 */
0x01, 0x1A, 0x07, 0x7E, 0x00, 0x1A, 0x09, 0x7D, /* ; C8-CF */
0x7F, 0x19, 0x0B, 0x7D, 0x7E, 0x18, 0x0D, 0x7D, /* ; D0-D7 */
0x7D, 0x17, 0x10, 0x7C, 0x7D, 0x15, 0x12, 0x7C, /* ; D8-DF */
0x7C, 0x14, 0x14, 0x7C, 0x7C, 0x12, 0x15, 0x7D, /* ; E0-E7 */
0x7C, 0x10, 0x17, 0x7D, 0x7C, 0x0D, 0x18, 0x7F, /* ; EA-EF */
0x7D, 0x0B, 0x19, 0x7F, 0x7D, 0x09, 0x1A, 0x00, /* ; F0-F7 */
0x7D, 0x07, 0x1A, 0x02, 0x7E, 0x05, 0x1B, 0x02 /* ; F8-FF */
}
}
};
static struct XGI301C_Tap4TimingStruct xgifb_ntsc_525_tap4_timing[] = {
{480, {
0x04, 0x1A, 0x04, 0x7E, 0x03, 0x1A, 0x06, 0x7D, /* ; C0-C7 */
0x01, 0x1A, 0x08, 0x7D, 0x00, 0x19, 0x0A, 0x7D, /* ; C8-CF */
0x7F, 0x19, 0x0C, 0x7C, 0x7E, 0x18, 0x0E, 0x7C, /* ; D0-D7 */
0x7E, 0x17, 0x10, 0x7B, 0x7D, 0x15, 0x12, 0x7C, /* ; D8-DF */
0x7D, 0x13, 0x13, 0x7D, 0x7C, 0x12, 0x15, 0x7D, /* ; E0-E7 */
0x7C, 0x10, 0x17, 0x7D, 0x7C, 0x0E, 0x18, 0x7E, /* ; EA-EF */
0x7D, 0x0C, 0x19, 0x7E, 0x7D, 0x0A, 0x19, 0x00, /* ; F0-F7 */
0x7D, 0x08, 0x1A, 0x01, 0x7E, 0x06, 0x1A, 0x02 /* ; F8-FF */
}
},
{600, {
0x07, 0x14, 0x07, 0x7E, 0x06, 0x14, 0x09, 0x7D, /* ; C0-C7 */
0x05, 0x14, 0x0A, 0x7D, 0x04, 0x13, 0x0B, 0x7E, /* ; C8-CF */
0x03, 0x13, 0x0C, 0x7E, 0x02, 0x12, 0x0D, 0x7F, /* ; D0-D7 */
0x01, 0x12, 0x0E, 0x7F, 0x01, 0x11, 0x0F, 0x7F, /* ; D8-DF */
0x01, 0x10, 0x10, 0x00, 0x7F, 0x0F, 0x11, 0x01, /* ; E0-E7 */
0x7F, 0x0E, 0x12, 0x01, 0x7E, 0x0D, 0x12, 0x03, /* ; EA-EF */
0x7E, 0x0C, 0x13, 0x03, 0x7E, 0x0B, 0x13, 0x04, /* ; F0-F7 */
0x7E, 0x0A, 0x14, 0x04, 0x7D, 0x09, 0x14, 0x06 /* ; F8-FF */
}
},
{0xFFFF, {
0x09, 0x0F, 0x09, 0x7F, 0x08, 0x0F, 0x09, 0x00, /* ; C0-C7 */
0x07, 0x0F, 0x0A, 0x00, 0x06, 0x0F, 0x0A, 0x01, /* ; C8-CF */
0x06, 0x0E, 0x0B, 0x01, 0x05, 0x0E, 0x0B, 0x02, /* ; D0-D7 */
0x04, 0x0E, 0x0C, 0x02, 0x04, 0x0D, 0x0C, 0x03, /* ; D8-DF */
0x03, 0x0D, 0x0D, 0x03, 0x02, 0x0C, 0x0D, 0x05, /* ; E0-E7 */
0x02, 0x0C, 0x0E, 0x04, 0x01, 0x0B, 0x0E, 0x06, /* ; EA-EF */
0x01, 0x0B, 0x0E, 0x06, 0x00, 0x0A, 0x0F, 0x07, /* ; F0-F7 */
0x00, 0x0A, 0x0F, 0x07, 0x00, 0x09, 0x0F, 0x08 /* ; F8-FF */
}
}
};
static struct XGI301C_Tap4TimingStruct YPbPr750pTap4Timing[] = {
{0xFFFF, {
0x05, 0x19, 0x05, 0x7D, 0x03, 0x19, 0x06, 0x7E, /* ; C0-C7 */
0x02, 0x19, 0x08, 0x7D, 0x01, 0x18, 0x0A, 0x7D, /* ; C8-CF */
0x00, 0x18, 0x0C, 0x7C, 0x7F, 0x17, 0x0E, 0x7C, /* ; D0-D7 */
0x7E, 0x16, 0x0F, 0x7D, 0x7E, 0x14, 0x11, 0x7D, /* ; D8-DF */
0x7D, 0x13, 0x13, 0x7D, 0x7D, 0x11, 0x14, 0x7E, /* ; E0-E7 */
0x7D, 0x0F, 0x16, 0x7E, 0x7D, 0x0E, 0x17, 0x7E, /* ; EA-EF */
0x7D, 0x0C, 0x18, 0x7F, 0x7D, 0x0A, 0x18, 0x01, /* ; F0-F7 */
0x7D, 0x08, 0x19, 0x02, 0x7D, 0x06, 0x19, 0x04 /* F8-FF */
}
}
};
#endif
| soap-DEIM/l4android | drivers/staging/xgifb/vb_table.h | C | gpl-2.0 | 115,672 |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import parse_iso8601
class HowcastIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
_TEST = {
'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly',
'md5': '7d45932269a288149483144f01b99789',
'info_dict': {
'id': '390161',
'ext': 'mp4',
'title': 'How to Tie a Square Knot Properly',
'description': 'md5:dbe792e5f6f1489027027bf2eba188a3',
'timestamp': 1276081287,
'upload_date': '20100609',
'duration': 56.823,
},
'params': {
'skip_download': True,
},
'add_ie': ['Ooyala'],
}
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
embed_code = self._search_regex(
r'<iframe[^>]+src="[^"]+\bembed_code=([^\b]+)\b',
webpage, 'ooyala embed code')
return {
'_type': 'url_transparent',
'ie_key': 'Ooyala',
'url': 'ooyala:%s' % embed_code,
'id': video_id,
'timestamp': parse_iso8601(self._html_search_meta(
'article:published_time', webpage, 'timestamp')),
}
| fluxw42/youtube-dl | youtube_dl/extractor/howcast.py | Python | unlicense | 1,370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.