code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for goog.labs.style.PixelDensityMonitor.
*
*/
/** @suppress {extraProvide} */
goog.provide('goog.labs.style.PixelDensityMonitorTest');
goog.setTestOnly('goog.labs.style.PixelDensityMonitorTest');
goog.require('goog.array');
goog.require('goog.dom.DomHelper');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.labs.style.PixelDensityMonitor');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.recordFunction');
var fakeWindow;
var recordFunction;
var monitor;
var mockControl;
var mediaQueryLists;
function setUp() {
recordFunction = goog.testing.recordFunction();
mediaQueryLists = [];
mockControl = new goog.testing.MockControl();
}
function tearDown() {
mockControl.$verifyAll();
goog.dispose(monitor);
goog.dispose(recordFunction);
}
function setUpMonitor(initialRatio, hasMatchMedia) {
fakeWindow = {
devicePixelRatio: initialRatio
};
if (hasMatchMedia) {
// Every call to matchMedia should return a new media query list with its
// own set of listeners.
fakeWindow.matchMedia = function(query) {
var listeners = [];
var newList = {
addListener: function(listener) {
listeners.push(listener);
},
removeListener: function(listener) {
goog.array.remove(listeners, listener);
},
callListeners: function() {
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
},
getListenerCount: function() {
return listeners.length;
}
};
mediaQueryLists.push(newList);
return newList;
};
}
var domHelper = mockControl.createStrictMock(goog.dom.DomHelper);
domHelper.getWindow().$returns(fakeWindow);
mockControl.$replayAll();
monitor = new goog.labs.style.PixelDensityMonitor(domHelper);
goog.events.listen(monitor,
goog.labs.style.PixelDensityMonitor.EventType.CHANGE, recordFunction);
}
function setNewRatio(newRatio) {
fakeWindow.devicePixelRatio = newRatio;
for (var i = 0; i < mediaQueryLists.length; i++) {
mediaQueryLists[i].callListeners();
}
}
function testNormalDensity() {
setUpMonitor(1, false);
assertEquals(goog.labs.style.PixelDensityMonitor.Density.NORMAL,
monitor.getDensity());
}
function testHighDensity() {
setUpMonitor(1.5, false);
assertEquals(goog.labs.style.PixelDensityMonitor.Density.HIGH,
monitor.getDensity());
}
function testNormalDensityIfUndefined() {
setUpMonitor(undefined, false);
assertEquals(goog.labs.style.PixelDensityMonitor.Density.NORMAL,
monitor.getDensity());
}
function testChangeEvent() {
setUpMonitor(1, true);
assertEquals(goog.labs.style.PixelDensityMonitor.Density.NORMAL,
monitor.getDensity());
monitor.start();
setNewRatio(2);
var call = recordFunction.popLastCall();
assertEquals(goog.labs.style.PixelDensityMonitor.Density.HIGH,
call.getArgument(0).target.getDensity());
assertEquals(goog.labs.style.PixelDensityMonitor.Density.HIGH,
monitor.getDensity());
setNewRatio(1);
call = recordFunction.popLastCall();
assertEquals(goog.labs.style.PixelDensityMonitor.Density.NORMAL,
call.getArgument(0).target.getDensity());
assertEquals(goog.labs.style.PixelDensityMonitor.Density.NORMAL,
monitor.getDensity());
}
function testListenerIsDisposed() {
setUpMonitor(1, true);
monitor.start();
assertEquals(1, mediaQueryLists.length);
assertEquals(1, mediaQueryLists[0].getListenerCount());
goog.dispose(monitor);
assertEquals(1, mediaQueryLists.length);
assertEquals(0, mediaQueryLists[0].getListenerCount());
}
| JavaScript |
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utility class that monitors pixel density ratio changes.
*
* @see ../demos/pixeldensitymonitor.html
*/
goog.provide('goog.labs.style.PixelDensityMonitor');
goog.provide('goog.labs.style.PixelDensityMonitor.Density');
goog.provide('goog.labs.style.PixelDensityMonitor.EventType');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
/**
* Monitors the window for changes to the ratio between device and screen
* pixels, e.g. when the user moves the window from a high density screen to a
* screen with normal density. Dispatches
* goog.labs.style.PixelDensityMonitor.EventType.CHANGE events when the density
* changes between the two predefined values NORMAL and HIGH.
*
* This class uses the window.devicePixelRatio value which is supported in
* WebKit and FF18. If the value does not exist, it will always return a
* NORMAL density. It requires support for MediaQueryList to detect changes to
* the devicePixelRatio.
*
* @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper which contains the
* document associated with the window to listen to. Defaults to the one in
* which this code is executing.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.labs.style.PixelDensityMonitor = function(opt_domHelper) {
goog.base(this);
/**
* @type {Window}
* @private
*/
this.window_ = opt_domHelper ? opt_domHelper.getWindow() : window;
/**
* The last density that was reported so that changes can be detected.
* @type {goog.labs.style.PixelDensityMonitor.Density}
* @private
*/
this.lastDensity_ = this.getDensity();
/**
* @type {function (MediaQueryList)}
* @private
*/
this.listener_ = goog.bind(this.handleMediaQueryChange_, this);
/**
* The media query list for a query that detects high density, if supported
* by the browser. Because matchMedia returns a new object for every call, it
* needs to be saved here so the listener can be removed when disposing.
* @type {?MediaQueryList}
* @private
*/
this.mediaQueryList_ = this.window_.matchMedia ? this.window_.matchMedia(
goog.labs.style.PixelDensityMonitor.HIGH_DENSITY_QUERY_) : null;
};
goog.inherits(goog.labs.style.PixelDensityMonitor, goog.events.EventTarget);
/**
* The two different pixel density modes on which the various ratios between
* physical and device pixels are mapped.
* @enum {number}
*/
goog.labs.style.PixelDensityMonitor.Density = {
/**
* Mode for older portable devices and desktop screens, defined as having a
* device pixel ratio of less than 1.5.
*/
NORMAL: 1,
/**
* Mode for newer portable devices with a high resolution screen, defined as
* having a device pixel ratio of more than 1.5.
*/
HIGH: 2
};
/**
* The events fired by the PixelDensityMonitor.
* @enum {string}
*/
goog.labs.style.PixelDensityMonitor.EventType = {
/**
* Dispatched when density changes between NORMAL and HIGH.
*/
CHANGE: goog.events.getUniqueId('change')
};
/**
* Minimum ratio between device and screen pixel needed for high density mode.
* @type {number}
* @private
*/
goog.labs.style.PixelDensityMonitor.HIGH_DENSITY_RATIO_ = 1.5;
/**
* Media query that matches for high density.
* @type {string}
* @private
*/
goog.labs.style.PixelDensityMonitor.HIGH_DENSITY_QUERY_ =
'(min-resolution: 144dpi), (-webkit-min-device-pixel-ratio: 1.5)';
/**
* Starts monitoring for changes in pixel density.
*/
goog.labs.style.PixelDensityMonitor.prototype.start = function() {
if (this.mediaQueryList_) {
this.mediaQueryList_.addListener(this.listener_);
}
};
/**
* @return {goog.labs.style.PixelDensityMonitor.Density} The density for the
* window.
*/
goog.labs.style.PixelDensityMonitor.prototype.getDensity = function() {
if (this.window_.devicePixelRatio >=
goog.labs.style.PixelDensityMonitor.HIGH_DENSITY_RATIO_) {
return goog.labs.style.PixelDensityMonitor.Density.HIGH;
} else {
return goog.labs.style.PixelDensityMonitor.Density.NORMAL;
}
};
/**
* Handles a change to the media query and checks whether the density has
* changed since the last call.
* @param {MediaQueryList} mql The list of changed media queries.
* @private
*/
goog.labs.style.PixelDensityMonitor.prototype.handleMediaQueryChange_ =
function(mql) {
var newDensity = this.getDensity();
if (this.lastDensity_ != newDensity) {
this.lastDensity_ = newDensity;
this.dispatchEvent(goog.labs.style.PixelDensityMonitor.EventType.CHANGE);
}
};
/** @override */
goog.labs.style.PixelDensityMonitor.prototype.disposeInternal = function() {
if (this.mediaQueryList_) {
this.mediaQueryList_.removeListener(this.listener_);
}
goog.base(this, 'disposeInternal');
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a mocking framework in Closure to make unit tests easy
* to write and understand. The methods provided here can be used to replace
* implementations of existing objects with 'mock' objects to abstract out
* external services and dependencies thereby isolating the code under test.
* Apart from mocking, methods are also provided to just monitor calls to an
* object (spying) and returning specific values for some or all the inputs to
* methods (stubbing).
*
* Design doc : http://go/closuremock
*
*/
goog.provide('goog.labs.mock');
goog.require('goog.array');
goog.require('goog.debug');
goog.require('goog.debug.Error');
goog.require('goog.functions');
goog.require('goog.json');
/**
* Mocks a given object or class.
*
* @param {!Object} objectOrClass An instance or a constructor of a class to be
* mocked.
* @return {!Object} The mocked object.
*/
goog.labs.mock.mock = function(objectOrClass) {
// Go over properties of 'objectOrClass' and create a MockManager to
// be used for stubbing out calls to methods.
var mockObjectManager = new goog.labs.mock.MockObjectManager_(objectOrClass);
var mockedObject = mockObjectManager.getMockedItem();
goog.asserts.assertObject(mockedObject);
return /** @type {!Object} */ (mockedObject);
};
/**
* Mocks a given function.
*
* @param {!Function} func A function to be mocked.
* @return {!Function} The mocked function.
*/
goog.labs.mock.mockFunction = function(func) {
var mockFuncManager = new goog.labs.mock.MockFunctionManager_(func);
var mockedFunction = mockFuncManager.getMockedItem();
goog.asserts.assertFunction(mockedFunction);
return /** @type {!Function} */ (mockedFunction);
};
/**
* Spies on a given object.
*
* @param {!Object} obj The object to be spied on.
* @return {!Object} The spy object.
*/
goog.labs.mock.spy = function(obj) {
// Go over properties of 'obj' and create a MockSpyManager_ to
// be used for spying on calls to methods.
var mockSpyManager = new goog.labs.mock.MockSpyManager_(obj);
var spyObject = mockSpyManager.getMockedItem();
goog.asserts.assert(spyObject);
return spyObject;
};
/**
* Returns an object that can be used to verify calls to specific methods of a
* given mock.
*
* @param {!Object} obj The mocked object.
* @return {!Object} The verifier.
*/
goog.labs.mock.verify = function(obj) {
return obj.$callVerifier;
};
/**
* Returns a name to identify a function. Named functions return their names,
* unnamed functions return a string of the form '#anonymous{ID}' where ID is
* a unique identifier for each anonymous function.
* @private
* @param {!Function} func The function.
* @return {string} The function name.
*/
goog.labs.mock.getFunctionName_ = function(func) {
var funcName = goog.debug.getFunctionName(func);
if (funcName == '' || funcName == '[Anonymous]') {
funcName = '#anonymous' + goog.getUid(func);
}
return funcName;
};
/**
* Returns a nicely formatted, readble representation of a method call.
* @private
* @param {string} methodName The name of the method.
* @param {Array=} opt_args The method arguments.
* @return {string} The string representation of the method call.
*/
goog.labs.mock.formatMethodCall_ = function(methodName, opt_args) {
opt_args = opt_args || [];
opt_args = goog.array.map(opt_args, function(arg) {
if (goog.isFunction(arg)) {
var funcName = goog.labs.mock.getFunctionName_(arg);
return '<function ' + funcName + '>';
} else {
return goog.json.serialize(arg);
}
});
return methodName + '(' + opt_args.join(', ') + ')';
};
/**
* Error thrown when verification failed.
*
* @param {Array} recordedCalls The recorded calls that didn't match the
* expectation.
* @param {!string} methodName The expected method call.
* @param {!Array} args The expected arguments.
* @constructor
* @extends {goog.debug.Error}
*/
goog.labs.mock.VerificationError = function(recordedCalls, methodName, args) {
var msg = goog.labs.mock.VerificationError.getVerificationErrorMsg_(
recordedCalls, methodName, args);
goog.base(this, msg);
};
goog.inherits(goog.labs.mock.VerificationError, goog.debug.Error);
/** @override */
goog.labs.mock.VerificationError.prototype.name = 'VerificationError';
/**
* This array contains the name of the functions that are part of the base
* Object prototype.
* Basically a copy of goog.object.PROTOTYPE_FIELDS_.
* @const
* @type {!Array.<string>}
* @private
*/
goog.labs.mock.PROTOTYPE_FIELDS_ = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/**
* Constructs a descriptive error message for an expected method call.
* @private
* @param {Array} recordedCalls The recorded calls that didn't match the
* expectation.
* @param {!string} methodName The expected method call.
* @param {!Array} args The expected arguments.
* @return {string} The error message.
*/
goog.labs.mock.VerificationError.getVerificationErrorMsg_ =
function(recordedCalls, methodName, args) {
recordedCalls = goog.array.filter(recordedCalls, function(binding) {
return binding.getMethodName() == methodName;
});
var expected = goog.labs.mock.formatMethodCall_(methodName, args);
var msg = '\nExpected: ' + expected.toString();
msg += '\nRecorded: ';
if (recordedCalls.length > 0) {
msg += recordedCalls.join(',\n ');
} else {
msg += 'No recorded calls';
}
return msg;
};
/**
* Base class that provides basic functionality for creating, adding and
* finding bindings, offering an executor method that is called when a call to
* the stub is made, an array to hold the bindings and the mocked item, among
* other things.
*
* @constructor
* @private
*/
goog.labs.mock.MockManager_ = function() {
/**
* Proxies the methods for the mocked object or class to execute the stubs.
* @type {!Object}
* @protected
* TODO(user): make instanceof work.
*/
this.mockedItem = {};
/**
* A reference to the object or function being mocked.
* @type {Object|Function}
* @protected
*/
this.mockee = null;
/**
* Holds the stub bindings established so far.
* @protected
*/
this.methodBindings = [];
/**
* Holds a reference to the binder used to define stubs.
* @protected
*/
this.$stubBinder = null;
/**
* Record method calls with no stub definitions.
* @type {!Array.<!goog.labs.mock.MethodBinding_>}
* @private
*/
this.callRecords_ = [];
};
/**
* Handles the first step in creating a stub, returning a stub-binder that
* is later used to bind a stub for a method.
*
* @param {string} methodName The name of the method being bound.
* @param {...} var_args The arguments to the method.
* @return {!goog.labs.mock.StubBinder_} The stub binder.
* @private
*/
goog.labs.mock.MockManager_.prototype.handleMockCall_ =
function(methodName, var_args) {
var args = goog.array.slice(arguments, 1);
return new goog.labs.mock.StubBinder_(this, methodName, args);
};
/**
* Returns the mock object. This should have a stubbed method for each method
* on the object being mocked.
*
* @return {!Object|!Function} The mock object.
*/
goog.labs.mock.MockManager_.prototype.getMockedItem = function() {
return this.mockedItem;
};
/**
* Adds a binding for the method name and arguments to be stubbed.
*
* @param {?string} methodName The name of the stubbed method.
* @param {!Array} args The arguments passed to the method.
* @param {!Function} func The stub function.
*
*/
goog.labs.mock.MockManager_.prototype.addBinding =
function(methodName, args, func) {
var binding = new goog.labs.mock.MethodBinding_(methodName, args, func);
this.methodBindings.push(binding);
};
/**
* Returns a stub, if defined, for the method name and arguments passed in.
*
* @param {string} methodName The name of the stubbed method.
* @param {!Array} args The arguments passed to the method.
* @return {Function} The stub function or undefined.
* @protected
*/
goog.labs.mock.MockManager_.prototype.findBinding =
function(methodName, args) {
var stub = goog.array.find(this.methodBindings, function(binding) {
return binding.matches(methodName, args, false /* isVerification */);
});
return stub && stub.getStub();
};
/**
* Returns a stub, if defined, for the method name and arguments passed in as
* parameters.
*
* @param {string} methodName The name of the stubbed method.
* @param {!Array} args The arguments passed to the method.
* @return {Function} The stub function or undefined.
* @protected
*/
goog.labs.mock.MockManager_.prototype.getExecutor = function(methodName, args) {
return this.findBinding(methodName, args);
};
/**
* Looks up the list of stubs defined on the mock object and executes the
* function associated with that stub.
*
* @param {string} methodName The name of the method to execute.
* @param {...} var_args The arguments passed to the method.
* @return {*} Value returned by the stub function.
* @protected
*/
goog.labs.mock.MockManager_.prototype.executeStub =
function(methodName, var_args) {
var args = goog.array.slice(arguments, 1);
// Record this call
this.recordCall_(methodName, args);
var func = this.getExecutor(methodName, args);
if (func) {
return func.apply(null, args);
}
};
/**
* Records a call to 'methodName' with arguments 'args'.
*
* @param {string} methodName The name of the called method.
* @param {!Array} args The array of arguments.
* @private
*/
goog.labs.mock.MockManager_.prototype.recordCall_ =
function(methodName, args) {
var callRecord = new goog.labs.mock.MethodBinding_(methodName, args,
goog.nullFunction);
this.callRecords_.push(callRecord);
};
/**
* Verify invocation of a method with specific arguments.
*
* @param {string} methodName The name of the method.
* @param {...} var_args The arguments passed.
* @return {!Function} The stub, if defined, or the spy method.
* @protected
*/
goog.labs.mock.MockManager_.prototype.verifyInvocation =
function(methodName, var_args) {
var args = goog.array.slice(arguments, 1);
var binding = goog.array.find(this.callRecords_, function(binding) {
return binding.matches(methodName, args, true /* isVerification */);
});
if (!binding) {
throw new goog.labs.mock.VerificationError(
this.callRecords_, methodName, args);
}
};
/**
* Sets up mock for the given object (or class), stubbing out all the defined
* methods. By default, all stubs return {@code undefined}, though stubs can be
* later defined using {@code goog.labs.mock.when}.
*
* @param {!Object|!Function} objOrClass The object or class to set up the mock
* for. A class is a constructor function.
*
* @constructor
* @extends {goog.labs.mock.MockManager_}
* @private
*/
goog.labs.mock.MockObjectManager_ = function(objOrClass) {
goog.base(this);
/**
* Proxies the calls to establish the first step of the stub bindings (object
* and method name)
* @private
*/
this.objectStubBinder_ = {};
this.mockee = objOrClass;
/**
* The call verifier is used to verify the calls. It maps property names to
* the method that does call verification.
* @type {!Object.<string, function(string, ...)>}
* @private
*/
this.objectCallVerifier_ = {};
var obj;
if (goog.isFunction(objOrClass)) {
// Create a temporary subclass with a no-op constructor so that we can
// create an instance and determine what methods it has.
/** @constructor */
var tempCtor = function() {};
goog.inherits(tempCtor, objOrClass);
obj = new tempCtor();
} else {
obj = objOrClass;
}
var enumerableProperties = goog.object.getKeys(obj);
// The non enumerable properties are added due to the fact that IE8 does not
// enumerate any of the prototype Object functions even when overriden and
// mocking these is sometimes needed.
for (var i = 0; i < goog.labs.mock.PROTOTYPE_FIELDS_.length; i++) {
var prop = goog.labs.mock.PROTOTYPE_FIELDS_[i];
if (!goog.array.contains(enumerableProperties, prop)) {
enumerableProperties.push(prop);
}
}
// Adds the properties to the mock, creating a proxy stub for each method on
// the instance.
for (var i = 0; i < enumerableProperties.length; i++) {
var prop = enumerableProperties[i];
if (goog.isFunction(obj[prop])) {
this.mockedItem[prop] = goog.bind(this.executeStub, this, prop);
// The stub binder used to create bindings.
this.objectStubBinder_[prop] =
goog.bind(this.handleMockCall_, this, prop);
// The verifier verifies the calls.
this.objectCallVerifier_[prop] =
goog.bind(this.verifyInvocation, this, prop);
}
}
// The alias for stub binder exposed to the world.
this.mockedItem.$stubBinder = this.objectStubBinder_;
// The alias for verifier for the world.
this.mockedItem.$callVerifier = this.objectCallVerifier_;
};
goog.inherits(goog.labs.mock.MockObjectManager_,
goog.labs.mock.MockManager_);
/**
* Sets up the spying behavior for the given object.
*
* @param {!Object} obj The object to be spied on.
*
* @constructor
* @extends {goog.labs.mock.MockObjectManager_}
* @private
*/
goog.labs.mock.MockSpyManager_ = function(obj) {
goog.base(this, obj);
};
goog.inherits(goog.labs.mock.MockSpyManager_,
goog.labs.mock.MockObjectManager_);
/**
* Return a stub, if defined, for the method and arguments passed in. If we lack
* a stub, instead look for a call record that matches the method and arguments.
*
* @return {Function} The stub or the invocation logger, if defined.
* @override
*/
goog.labs.mock.MockSpyManager_.prototype.findBinding =
function(methodName, args) {
var stub = goog.base(this, 'findBinding', methodName, args);
if (!stub) {
stub = goog.bind(this.mockee[methodName], this.mockee);
}
return stub;
};
/**
* Sets up mock for the given function, stubbing out. By default, all stubs
* return {@code undefined}, though stubs can be later defined using
* {@code goog.labs.mock.when}.
*
* @param {!Function} func The function to set up the mock for.
*
* @constructor
* @extends {goog.labs.mock.MockManager_}
* @private
*/
goog.labs.mock.MockFunctionManager_ = function(func) {
goog.base(this);
this.func_ = func;
/**
* The stub binder used to create bindings.
* Sets the first argument of handleMockCall_ to the function name.
* @type {!Function}
* @private
*/
this.functionStubBinder_ = this.useMockedFunctionName_(this.handleMockCall_);
this.mockedItem = this.useMockedFunctionName_(this.executeStub);
this.mockedItem.$stubBinder = this.functionStubBinder_;
/**
* The call verifier is used to verify function invocations.
* Sets the first argument of verifyInvocation to the function name.
* @type {!Function}
*/
this.mockedItem.$callVerifier =
this.useMockedFunctionName_(this.verifyInvocation);
};
goog.inherits(goog.labs.mock.MockFunctionManager_,
goog.labs.mock.MockManager_);
/**
* Given a method, returns a new function that calls the first one setting
* the first argument to the mocked function name.
* This is used to dynamically override the stub binders and call verifiers.
* @private
* @param {Function} nextFunc The function to override.
* @return {!Function} The overloaded function.
*/
goog.labs.mock.MockFunctionManager_.prototype.useMockedFunctionName_ =
function(nextFunc) {
return goog.bind(function(var_args) {
var args = goog.array.slice(arguments, 0);
var name =
'#mockFor<' + goog.labs.mock.getFunctionName_(this.func_) + '>';
goog.array.insertAt(args, name, 0);
return nextFunc.apply(this, args);
}, this);
};
/**
* The stub binder is the object that helps define the stubs by binding
* method name to the stub method.
*
* @param {!goog.labs.mock.MockManager_}
* mockManager The mock manager.
* @param {?string} name The method name.
* @param {!Array} args The other arguments to the method.
*
* @constructor
* @private
*/
goog.labs.mock.StubBinder_ = function(mockManager, name, args) {
/**
* The mock manager instance.
* @type {!goog.labs.mock.MockManager_}
* @private
*/
this.mockManager_ = mockManager;
/**
* Holds the name of the method to be bound.
* @type {?string}
* @private
*/
this.name_ = name;
/**
* Holds the arguments for the method.
* @type {!Array}
* @private
*/
this.args_ = args;
};
/**
* Defines the stub to be called for the method name and arguments bound
* earlier.
* TODO(user): Add support for the 'Answer' interface.
*
* @param {!Function} func The stub.
*/
goog.labs.mock.StubBinder_.prototype.then = function(func) {
this.mockManager_.addBinding(this.name_, this.args_, func);
};
/**
* Defines the stub to return a specific value for a method name and arguments.
*
* @param {*} value The value to return.
*/
goog.labs.mock.StubBinder_.prototype.thenReturn = function(value) {
this.mockManager_.addBinding(this.name_, this.args_,
goog.functions.constant(value));
};
/**
* Facilitates (and is the first step in) setting up stubs. Obtains an object
* on which, the method to be mocked is called to create a stub. Sample usage:
*
* var mockObj = goog.labs.mock.mock(objectBeingMocked);
* goog.labs.mock.when(mockObj).getFoo(3).thenReturn(4);
*
* @param {!Object} mockObject The mocked object.
* @return {!goog.labs.mock.StubBinder_} The property binder.
*/
goog.labs.mock.when = function(mockObject) {
goog.asserts.assert(mockObject.$stubBinder, 'Stub binder cannot be null!');
return mockObject.$stubBinder;
};
/**
* Represents a binding between a method name, args and a stub.
*
* @param {?string} methodName The name of the method being stubbed.
* @param {!Array} args The arguments passed to the method.
* @param {!Function} stub The stub function to be called for the given method.
* @constructor
* @private
*/
goog.labs.mock.MethodBinding_ = function(methodName, args, stub) {
/**
* The name of the method being stubbed.
* @type {?string}
* @private
*/
this.methodName_ = methodName;
/**
* The arguments for the method being stubbed.
* @type {!Array}
* @private
*/
this.args_ = args;
/**
* The stub function.
* @type {!Function}
* @private
*/
this.stub_ = stub;
};
/**
* @return {!Function} The stub to be executed.
*/
goog.labs.mock.MethodBinding_.prototype.getStub = function() {
return this.stub_;
};
/**
* @override
* @return {string} A readable string representation of the binding
* as a method call.
*/
goog.labs.mock.MethodBinding_.prototype.toString = function() {
return goog.labs.mock.formatMethodCall_(this.methodName_ || '', this.args_);
};
/**
* @return {string} The method name for this binding.
*/
goog.labs.mock.MethodBinding_.prototype.getMethodName = function() {
return this.methodName_ || '';
};
/**
* Determines whether the given args match the stored args_. Used to determine
* which stub to invoke for a method.
*
* @param {string} methodName The name of the method being stubbed.
* @param {!Array} args An array of arguments.
* @param {boolean} isVerification Whether this is a function verification call
* or not.
* @return {boolean} If it matches the stored arguments.
*/
goog.labs.mock.MethodBinding_.prototype.matches = function(
methodName, args, isVerification) {
var specs = isVerification ? args : this.args_;
var calls = isVerification ? this.args_ : args;
//TODO(user): More elaborate argument matching. Think about matching
// objects.
return this.methodName_ == methodName &&
goog.array.equals(calls, specs, function(arg, spec) {
// Duck-type to see if this is an object that implements the
// goog.labs.testing.Matcher interface.
if (goog.isFunction(spec.matches)) {
return spec.matches(arg);
} else {
return goog.array.defaultCompareEquality(spec, arg);
}
});
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a convenient API for data persistence with key and
* object encryption. Without a valid secret, the existence of a particular
* key can't be verified and values can't be decrypted. The value encryption
* is salted, so subsequent writes of the same cleartext result in different
* ciphertext. The ciphertext is *not* authenticated, so there is no protection
* against data manipulation.
*
* The metadata is *not* encrypted, so expired keys can be cleaned up without
* decrypting them. If sensitive metadata is added in subclasses, it is up
* to the subclass to protect this information, perhaps by embedding it in
* the object.
*
*/
goog.provide('goog.storage.EncryptedStorage');
goog.require('goog.crypt');
goog.require('goog.crypt.Arc4');
goog.require('goog.crypt.Sha1');
goog.require('goog.crypt.base64');
goog.require('goog.json');
goog.require('goog.json.Serializer');
goog.require('goog.storage.CollectableStorage');
goog.require('goog.storage.ErrorCode');
goog.require('goog.storage.RichStorage');
goog.require('goog.storage.RichStorage.Wrapper');
goog.require('goog.storage.mechanism.IterableMechanism');
/**
* Provides an encrypted storage. The keys are hashed with a secret, so
* their existence cannot be verified without the knowledge of the secret.
* The values are encrypted using the key, a salt, and the secret, so
* stream cipher initialization varies for each stored value.
*
* @param {!goog.storage.mechanism.IterableMechanism} mechanism The underlying
* storage mechanism.
* @param {string} secret The secret key used to encrypt the storage.
* @constructor
* @extends {goog.storage.CollectableStorage}
*/
goog.storage.EncryptedStorage = function(mechanism, secret) {
goog.base(this, mechanism);
this.secret_ = goog.crypt.stringToByteArray(secret);
this.cleartextSerializer_ = new goog.json.Serializer();
};
goog.inherits(goog.storage.EncryptedStorage, goog.storage.CollectableStorage);
/**
* Metadata key under which the salt is stored.
*
* @type {string}
* @protected
*/
goog.storage.EncryptedStorage.SALT_KEY = 'salt';
/**
* The secret used to encrypt the storage.
*
* @type {Array.<number>}
* @private
*/
goog.storage.EncryptedStorage.prototype.secret_ = null;
/**
* The JSON serializer used to serialize values before encryption. This can
* be potentially different from serializing for the storage mechanism (see
* goog.storage.Storage), so a separate serializer is kept here.
*
* @type {goog.json.Serializer}
* @private
*/
goog.storage.EncryptedStorage.prototype.cleartextSerializer_ = null;
/**
* Hashes a key using the secret.
*
* @param {string} key The key.
* @return {string} The hash.
* @private
*/
goog.storage.EncryptedStorage.prototype.hashKeyWithSecret_ = function(key) {
var sha1 = new goog.crypt.Sha1();
sha1.update(goog.crypt.stringToByteArray(key));
sha1.update(this.secret_);
return goog.crypt.base64.encodeByteArray(sha1.digest(), true);
};
/**
* Encrypts a value using a key, a salt, and the secret.
*
* @param {!Array.<number>} salt The salt.
* @param {string} key The key.
* @param {string} value The cleartext value.
* @return {string} The encrypted value.
* @private
*/
goog.storage.EncryptedStorage.prototype.encryptValue_ = function(
salt, key, value) {
if (!(salt.length > 0)) {
throw Error('Non-empty salt must be provided');
}
var sha1 = new goog.crypt.Sha1();
sha1.update(goog.crypt.stringToByteArray(key));
sha1.update(salt);
sha1.update(this.secret_);
var arc4 = new goog.crypt.Arc4();
arc4.setKey(sha1.digest());
// Warm up the streamcypher state, see goog.crypt.Arc4 for details.
arc4.discard(1536);
var bytes = goog.crypt.stringToByteArray(value);
arc4.crypt(bytes);
return goog.crypt.byteArrayToString(bytes);
};
/**
* Decrypts a value using a key, a salt, and the secret.
*
* @param {!Array.<number>} salt The salt.
* @param {string} key The key.
* @param {string} value The encrypted value.
* @return {string} The decrypted value.
* @private
*/
goog.storage.EncryptedStorage.prototype.decryptValue_ = function(
salt, key, value) {
// ARC4 is symmetric.
return this.encryptValue_(salt, key, value);
};
/** @override */
goog.storage.EncryptedStorage.prototype.set = function(
key, value, opt_expiration) {
if (!goog.isDef(value)) {
goog.storage.EncryptedStorage.prototype.remove.call(this, key);
return;
}
var salt = [];
// 64-bit random salt.
for (var i = 0; i < 8; ++i) {
salt[i] = Math.floor(Math.random() * 0x100);
}
var wrapper = new goog.storage.RichStorage.Wrapper(
this.encryptValue_(salt, key,
this.cleartextSerializer_.serialize(value)));
wrapper[goog.storage.EncryptedStorage.SALT_KEY] = salt;
goog.base(this, 'set', this.hashKeyWithSecret_(key), wrapper, opt_expiration);
};
/** @override */
goog.storage.EncryptedStorage.prototype.getWrapper = function(
key, opt_expired) {
var wrapper = goog.base(this, 'getWrapper',
this.hashKeyWithSecret_(key), opt_expired);
if (!wrapper) {
return undefined;
}
var value = goog.storage.RichStorage.Wrapper.unwrap(wrapper);
var salt = wrapper[goog.storage.EncryptedStorage.SALT_KEY];
if (!goog.isString(value) || !goog.isArray(salt) || !salt.length) {
throw goog.storage.ErrorCode.INVALID_VALUE;
}
var json = this.decryptValue_(salt, key, value);
/** @preserveTry */
try {
wrapper[goog.storage.RichStorage.DATA_KEY] = goog.json.parse(json);
} catch (e) {
throw goog.storage.ErrorCode.DECRYPTION_ERROR;
}
return wrapper;
};
/** @override */
goog.storage.EncryptedStorage.prototype.remove = function(key) {
goog.base(this, 'remove', this.hashKeyWithSecret_(key));
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a convenient API for data persistence using a selected
* data storage mechanism.
*
*/
goog.provide('goog.storage.Storage');
goog.require('goog.json');
goog.require('goog.json.Serializer');
goog.require('goog.storage.ErrorCode');
goog.require('goog.storage.mechanism.Mechanism');
/**
* The base implementation for all storage APIs.
*
* @param {!goog.storage.mechanism.Mechanism} mechanism The underlying
* storage mechanism.
* @constructor
*/
goog.storage.Storage = function(mechanism) {
this.mechanism = mechanism;
this.serializer_ = new goog.json.Serializer();
};
/**
* The mechanism used to persist key-value pairs.
*
* @type {goog.storage.mechanism.Mechanism}
* @protected
*/
goog.storage.Storage.prototype.mechanism = null;
/**
* The JSON serializer used to serialize values.
*
* @type {goog.json.Serializer}
* @private
*/
goog.storage.Storage.prototype.serializer_ = null;
/**
* Set an item in the data storage.
*
* @param {string} key The key to set.
* @param {*} value The value to serialize to a string and save.
*/
goog.storage.Storage.prototype.set = function(key, value) {
if (!goog.isDef(value)) {
this.mechanism.remove(key);
return;
}
this.mechanism.set(key, this.serializer_.serialize(value));
};
/**
* Get an item from the data storage.
*
* @param {string} key The key to get.
* @return {*} Deserialized value or undefined if not found.
*/
goog.storage.Storage.prototype.get = function(key) {
var json = this.mechanism.get(key);
if (goog.isNull(json)) {
return undefined;
}
/** @preserveTry */
try {
return goog.json.parse(json);
} catch (e) {
throw goog.storage.ErrorCode.INVALID_VALUE;
}
};
/**
* Remove an item from the data storage.
*
* @param {string} key The key to remove.
*/
goog.storage.Storage.prototype.remove = function(key) {
this.mechanism.remove(key);
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the storage interface.
*
*/
goog.provide('goog.storage.storage_test');
goog.require('goog.storage.Storage');
goog.require('goog.structs.Map');
goog.require('goog.testing.asserts');
goog.setTestOnly('storage_test');
goog.storage.storage_test.runBasicTests = function(storage) {
// Simple Objects.
storage.set('first', 'Hello world!');
storage.set('second', ['one', 'two', 'three']);
storage.set('third', {'a': 97, 'b': 98});
assertEquals('Hello world!', storage.get('first'));
assertObjectEquals(['one', 'two', 'three'], storage.get('second'));
assertObjectEquals({'a': 97, 'b': 98}, storage.get('third'));
// Some more complex fun with a Map.
var map = new goog.structs.Map();
map.set('Alice', 'Hello world!');
map.set('Bob', ['one', 'two', 'three']);
map.set('Cecile', {'a': 97, 'b': 98});
storage.set('first', map.toObject());
assertObjectEquals(map.toObject(), storage.get('first'));
// Setting weird values.
storage.set('second', null);
assertEquals(null, storage.get('second'));
storage.set('second', undefined);
assertEquals(undefined, storage.get('second'));
storage.set('second', '');
assertEquals('', storage.get('second'));
// Clean up.
storage.remove('first');
storage.remove('second');
storage.remove('third');
assertUndefined(storage.get('first'));
assertUndefined(storage.get('second'));
assertUndefined(storage.get('third'));
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a convenient API for data persistence with data
* expiration and user-initiated expired key collection.
*
*/
goog.provide('goog.storage.CollectableStorage');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.iter');
goog.require('goog.storage.ErrorCode');
goog.require('goog.storage.ExpiringStorage');
goog.require('goog.storage.RichStorage.Wrapper');
goog.require('goog.storage.mechanism.IterableMechanism');
/**
* Provides a storage with expirning keys and a collection method.
*
* @param {!goog.storage.mechanism.IterableMechanism} mechanism The underlying
* storage mechanism.
* @constructor
* @extends {goog.storage.ExpiringStorage}
*/
goog.storage.CollectableStorage = function(mechanism) {
goog.base(this, mechanism);
};
goog.inherits(goog.storage.CollectableStorage, goog.storage.ExpiringStorage);
/**
* Cleans up the storage by removing expired keys.
*
* @param {boolean=} opt_strict Also remove invalid keys.
*/
goog.storage.CollectableStorage.prototype.collect = function(opt_strict) {
var selfObj = this;
var keysToRemove = [];
goog.iter.forEach(this.mechanism.__iterator__(true), function(key) {
// Get the wrapper.
var wrapper;
/** @preserveTry */
try {
wrapper = goog.storage.CollectableStorage.prototype.getWrapper.call(
selfObj, key, true);
} catch (ex) {
if (ex == goog.storage.ErrorCode.INVALID_VALUE) {
// Bad wrappers are removed in strict mode.
if (opt_strict) {
keysToRemove.push(key);
}
// Skip over bad wrappers and continue.
return;
}
// Unknown error, escalate.
throw ex;
}
goog.asserts.assert(wrapper);
// Remove expired objects.
if (goog.storage.ExpiringStorage.isExpired(wrapper)) {
keysToRemove.push(key);
// Continue with the next key.
return;
}
// Objects which can't be decoded are removed in strict mode.
if (opt_strict) {
/** @preserveTry */
try {
goog.storage.RichStorage.Wrapper.unwrap(wrapper);
} catch (ex) {
if (ex == goog.storage.ErrorCode.INVALID_VALUE) {
keysToRemove.push(key);
// Skip over bad wrappers and continue.
return;
}
// Unknown error, escalate.
throw ex;
}
}
});
goog.array.forEach(keysToRemove, function(key) {
goog.storage.CollectableStorage.prototype.remove.call(selfObj, key);
});
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a convenient API for data persistence with expiration.
*
*/
goog.provide('goog.storage.ExpiringStorage');
goog.require('goog.storage.RichStorage');
goog.require('goog.storage.RichStorage.Wrapper');
goog.require('goog.storage.mechanism.Mechanism');
/**
* Provides a storage with expirning keys.
*
* @param {!goog.storage.mechanism.Mechanism} mechanism The underlying
* storage mechanism.
* @constructor
* @extends {goog.storage.RichStorage}
*/
goog.storage.ExpiringStorage = function(mechanism) {
goog.base(this, mechanism);
};
goog.inherits(goog.storage.ExpiringStorage, goog.storage.RichStorage);
/**
* Metadata key under which the expiration time is stored.
*
* @type {string}
* @protected
*/
goog.storage.ExpiringStorage.EXPIRATION_TIME_KEY = 'expiration';
/**
* Metadata key under which the creation time is stored.
*
* @type {string}
* @protected
*/
goog.storage.ExpiringStorage.CREATION_TIME_KEY = 'creation';
/**
* Returns the wrapper creation time.
*
* @param {!Object} wrapper The wrapper.
* @return {number|undefined} Wrapper creation time.
*/
goog.storage.ExpiringStorage.getCreationTime = function(wrapper) {
return wrapper[goog.storage.ExpiringStorage.CREATION_TIME_KEY];
};
/**
* Returns the wrapper expiration time.
*
* @param {!Object} wrapper The wrapper.
* @return {number|undefined} Wrapper expiration time.
*/
goog.storage.ExpiringStorage.getExpirationTime = function(wrapper) {
return wrapper[goog.storage.ExpiringStorage.EXPIRATION_TIME_KEY];
};
/**
* Checks if the data item has expired.
*
* @param {!Object} wrapper The wrapper.
* @return {boolean} True if the item has expired.
*/
goog.storage.ExpiringStorage.isExpired = function(wrapper) {
var creation = goog.storage.ExpiringStorage.getCreationTime(wrapper);
var expiration = goog.storage.ExpiringStorage.getExpirationTime(wrapper);
return !!expiration && expiration < goog.now() ||
!!creation && creation > goog.now();
};
/**
* Set an item in the storage.
*
* @param {string} key The key to set.
* @param {*} value The value to serialize to a string and save.
* @param {number=} opt_expiration The number of miliseconds since epoch
* (as in goog.now()) when the value is to expire. If the expiration
* time is not provided, the value will persist as long as possible.
* @override
*/
goog.storage.ExpiringStorage.prototype.set = function(
key, value, opt_expiration) {
var wrapper = goog.storage.RichStorage.Wrapper.wrapIfNecessary(value);
if (wrapper) {
if (opt_expiration) {
if (opt_expiration < goog.now()) {
goog.storage.ExpiringStorage.prototype.remove.call(this, key);
return;
}
wrapper[goog.storage.ExpiringStorage.EXPIRATION_TIME_KEY] =
opt_expiration;
}
wrapper[goog.storage.ExpiringStorage.CREATION_TIME_KEY] = goog.now();
}
goog.base(this, 'set', key, wrapper);
};
/**
* Get an item wrapper (the item and its metadata) from the storage.
*
* @param {string} key The key to get.
* @param {boolean=} opt_expired If true, return expired wrappers as well.
* @return {(!Object|undefined)} The wrapper, or undefined if not found.
* @override
*/
goog.storage.ExpiringStorage.prototype.getWrapper = function(key, opt_expired) {
var wrapper = goog.base(this, 'getWrapper', key);
if (!wrapper) {
return undefined;
}
if (!opt_expired && goog.storage.ExpiringStorage.isExpired(wrapper)) {
goog.storage.ExpiringStorage.prototype.remove.call(this, key);
return undefined;
}
return wrapper;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines errors to be thrown by the storage.
*
*/
goog.provide('goog.storage.ErrorCode');
/**
* Errors thrown by the storage.
* @enum {string}
*/
goog.storage.ErrorCode = {
INVALID_VALUE: 'Storage: Invalid value was encountered',
DECRYPTION_ERROR: 'Storage: The value could not be decrypted'
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the abstract storage mechanism interface.
*
* These tests should be included in tests of any class extending
* goog.storage.mechanism.Mechanism.
*
*/
goog.provide('goog.storage.mechanism.mechanismTester');
goog.require('goog.storage.mechanism.ErrorCode');
goog.require('goog.storage.mechanism.HTML5LocalStorage');
goog.require('goog.storage.mechanism.Mechanism');
goog.require('goog.testing.asserts');
goog.require('goog.userAgent.product');
goog.require('goog.userAgent.product.isVersion');
goog.setTestOnly('goog.storage.mechanism.mechanismTester');
var mechanism = null;
var minimumQuota = 0;
function testSetGet() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
assertEquals('one', mechanism.get('first'));
}
function testChange() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.set('first', 'two');
assertEquals('two', mechanism.get('first'));
}
function testRemove() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.remove('first');
assertNull(mechanism.get('first'));
}
function testSetRemoveSet() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.remove('first');
mechanism.set('first', 'one');
assertEquals('one', mechanism.get('first'));
}
function testRemoveRemove() {
if (!mechanism) {
return;
}
mechanism.remove('first');
mechanism.remove('first');
assertNull(mechanism.get('first'));
}
function testSetTwo() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.set('second', 'two');
assertEquals('one', mechanism.get('first'));
assertEquals('two', mechanism.get('second'));
}
function testChangeTwo() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.set('second', 'two');
mechanism.set('second', 'three');
mechanism.set('first', 'four');
assertEquals('four', mechanism.get('first'));
assertEquals('three', mechanism.get('second'));
}
function testSetRemoveThree() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.set('second', 'two');
mechanism.set('third', 'three');
mechanism.remove('second');
assertNull(mechanism.get('second'));
assertEquals('one', mechanism.get('first'));
assertEquals('three', mechanism.get('third'));
mechanism.remove('first');
assertNull(mechanism.get('first'));
assertEquals('three', mechanism.get('third'));
mechanism.remove('third');
assertNull(mechanism.get('third'));
}
function testEmptyValue() {
if (!mechanism) {
return;
}
mechanism.set('third', '');
assertEquals('', mechanism.get('third'));
}
function testWeirdKeys() {
if (!mechanism) {
return;
}
// Some weird keys. We leave out some tests for some browsers where they
// trigger browser bugs, and where the keys are too obscure to prepare a
// workaround.
mechanism.set(' ', 'space');
mechanism.set('=+!@#$%^&*()-_\\|;:\'",./<>?[]{}~`', 'control');
mechanism.set(
'\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341', 'ten');
mechanism.set('\0', 'null');
mechanism.set('\0\0', 'double null');
mechanism.set('\0A', 'null A');
mechanism.set('', 'zero');
assertEquals('space', mechanism.get(' '));
assertEquals('control', mechanism.get('=+!@#$%^&*()-_\\|;:\'",./<>?[]{}~`'));
assertEquals('ten', mechanism.get(
'\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341'));
if (!goog.userAgent.IE) {
// IE does not properly handle nulls in HTML5 localStorage keys (IE8, IE9).
// https://connect.microsoft.com/IE/feedback/details/667799/
assertEquals('null', mechanism.get('\0'));
assertEquals('double null', mechanism.get('\0\0'));
assertEquals('null A', mechanism.get('\0A'));
}
if (!goog.userAgent.GECKO) {
// Firefox does not properly handle the empty key (FF 3.5, 3.6, 4.0).
// https://bugzilla.mozilla.org/show_bug.cgi?id=510849
assertEquals('zero', mechanism.get(''));
}
}
function testQuota() {
if (!mechanism) {
return;
}
// This test might crash Safari 4, so it is disabled for this version.
// It works fine on Safari 3 and Safari 5.
if (goog.userAgent.product.SAFARI &&
goog.userAgent.product.isVersion(4) &&
!goog.userAgent.product.isVersion(5)) {
return;
}
var buffer = '\u03ff'; // 2 bytes
var savedBytes = 0;
try {
while (buffer.length < minimumQuota) {
buffer = buffer + buffer;
mechanism.set('foo', buffer);
savedBytes = buffer.length;
}
} catch (ex) {
if (ex != goog.storage.mechanism.ErrorCode.QUOTA_EXCEEDED) {
throw ex;
}
}
mechanism.remove('foo');
assertTrue(savedBytes >= minimumQuota);
}
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wraps an iterable storage mechanism and creates artificial
* namespaces using a prefix in the global namespace.
*
*/
goog.provide('goog.storage.mechanism.PrefixedMechanism');
goog.require('goog.iter.Iterator');
goog.require('goog.storage.mechanism.IterableMechanism');
/**
* Wraps an iterable storage mechanism and creates artificial namespaces.
*
* @param {!goog.storage.mechanism.IterableMechanism} mechanism Underlying
* iterable storage mechanism.
* @param {string} prefix Prefix for creating an artificial namespace.
* @constructor
* @extends {goog.storage.mechanism.IterableMechanism}
*/
goog.storage.mechanism.PrefixedMechanism = function(mechanism, prefix) {
goog.base(this);
this.mechanism_ = mechanism;
this.prefix_ = prefix + '::';
};
goog.inherits(goog.storage.mechanism.PrefixedMechanism,
goog.storage.mechanism.IterableMechanism);
/**
* The mechanism to be prefixed.
*
* @type {goog.storage.mechanism.IterableMechanism}
* @private
*/
goog.storage.mechanism.PrefixedMechanism.prototype.mechanism_ = null;
/**
* The prefix for creating artificial namespaces.
*
* @type {string}
* @private
*/
goog.storage.mechanism.PrefixedMechanism.prototype.prefix_ = '';
/** @override */
goog.storage.mechanism.PrefixedMechanism.prototype.set = function(key, value) {
this.mechanism_.set(this.prefix_ + key, value);
};
/** @override */
goog.storage.mechanism.PrefixedMechanism.prototype.get = function(key) {
return this.mechanism_.get(this.prefix_ + key);
};
/** @override */
goog.storage.mechanism.PrefixedMechanism.prototype.remove = function(key) {
this.mechanism_.remove(this.prefix_ + key);
};
/** @override */
goog.storage.mechanism.PrefixedMechanism.prototype.__iterator__ = function(
opt_keys) {
var subIter = this.mechanism_.__iterator__(true);
var selfObj = this;
var newIter = new goog.iter.Iterator();
newIter.next = function() {
var key = /** @type {string} */ (subIter.next());
while (key.substr(0, selfObj.prefix_.length) != selfObj.prefix_) {
key = /** @type {string} */ (subIter.next());
}
return opt_keys ? key.substr(selfObj.prefix_.length) :
selfObj.mechanism_.get(key);
};
return newIter;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for storage mechanism separation.
*
* These tests should be included by tests of any mechanism which natively
* implements namespaces. There is no need to include those tests for mechanisms
* extending goog.storage.mechanism.PrefixedMechanism. Make sure a different
* namespace is used for each object.
*
*/
goog.provide('goog.storage.mechanism.mechanismSeparationTester');
goog.require('goog.iter.Iterator');
goog.require('goog.storage.mechanism.IterableMechanism');
goog.require('goog.testing.asserts');
goog.setTestOnly('goog.storage.mechanism.mechanismSeparationTester');
var mechanism = null;
var mechanism_separate = null;
function testSeparateSet() {
if (!mechanism || !mechanism_separate) {
return;
}
mechanism.set('first', 'one');
assertNull(mechanism_separate.get('first'));
assertEquals(0, mechanism_separate.getCount());
assertEquals(goog.iter.StopIteration,
assertThrows(mechanism_separate.__iterator__().next));
}
function testSeparateSetInverse() {
if (!mechanism || !mechanism_separate) {
return;
}
mechanism.set('first', 'one');
mechanism_separate.set('first', 'two');
assertEquals('one', mechanism.get('first'));
assertEquals(1, mechanism.getCount());
var iterator = mechanism.__iterator__();
assertEquals('one', iterator.next());
assertEquals(goog.iter.StopIteration,
assertThrows(iterator.next));
}
function testSeparateRemove() {
if (!mechanism || !mechanism_separate) {
return;
}
mechanism.set('first', 'one');
mechanism_separate.remove('first');
assertEquals('one', mechanism.get('first'));
assertEquals(1, mechanism.getCount());
var iterator = mechanism.__iterator__();
assertEquals('one', iterator.next());
assertEquals(goog.iter.StopIteration,
assertThrows(iterator.next));
}
function testSeparateClean() {
if (!mechanism || !mechanism_separate) {
return;
}
mechanism_separate.set('first', 'two');
mechanism.clear();
assertEquals('two', mechanism_separate.get('first'));
assertEquals(1, mechanism_separate.getCount());
var iterator = mechanism_separate.__iterator__();
assertEquals('two', iterator.next());
assertEquals(goog.iter.StopIteration,
assertThrows(iterator.next));
}
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Base class that implements functionality common
* across both session and local web storage mechanisms.
*
*/
goog.provide('goog.storage.mechanism.HTML5WebStorage');
goog.require('goog.asserts');
goog.require('goog.iter.Iterator');
goog.require('goog.iter.StopIteration');
goog.require('goog.storage.mechanism.ErrorCode');
goog.require('goog.storage.mechanism.IterableMechanism');
/**
* Provides a storage mechanism that uses HTML5 Web storage.
*
* @param {Storage} storage The Web storage object.
* @constructor
* @extends {goog.storage.mechanism.IterableMechanism}
*/
goog.storage.mechanism.HTML5WebStorage = function(storage) {
goog.base(this);
this.storage_ = storage;
};
goog.inherits(goog.storage.mechanism.HTML5WebStorage,
goog.storage.mechanism.IterableMechanism);
/**
* The key used to check if the storage instance is available.
* @type {string}
* @const
* @private
*/
goog.storage.mechanism.HTML5WebStorage.STORAGE_AVAILABLE_KEY_ = '__sak';
/**
* The web storage object (window.localStorage or window.sessionStorage).
*
* @type {Storage}
* @private
*/
goog.storage.mechanism.HTML5WebStorage.prototype.storage_;
/**
* Determines whether or not the mechanism is available.
* It works only if the provided web storage object exists and is enabled.
*
* @return {boolean} True if the mechanism is available.
*/
goog.storage.mechanism.HTML5WebStorage.prototype.isAvailable = function() {
if (!this.storage_) {
return false;
}
/** @preserveTry */
try {
// setItem will throw an exception if we cannot access WebStorage (e.g.,
// Safari in private mode).
this.storage_.setItem(
goog.storage.mechanism.HTML5WebStorage.STORAGE_AVAILABLE_KEY_, '1');
this.storage_.removeItem(
goog.storage.mechanism.HTML5WebStorage.STORAGE_AVAILABLE_KEY_);
return true;
} catch (e) {
return false;
}
};
/** @override */
goog.storage.mechanism.HTML5WebStorage.prototype.set = function(key, value) {
/** @preserveTry */
try {
// May throw an exception if storage quota is exceeded.
this.storage_.setItem(key, value);
} catch (e) {
// In Safari Private mode, conforming to the W3C spec, invoking
// Storage.prototype.setItem will allways throw a QUOTA_EXCEEDED_ERR
// exception. Since it's impossible to verify if we're in private browsing
// mode, we throw a different exception if the storage is empty.
if (this.storage_.length == 0) {
throw goog.storage.mechanism.ErrorCode.STORAGE_DISABLED;
} else {
throw goog.storage.mechanism.ErrorCode.QUOTA_EXCEEDED;
}
}
};
/** @override */
goog.storage.mechanism.HTML5WebStorage.prototype.get = function(key) {
// According to W3C specs, values can be of any type. Since we only save
// strings, any other type is a storage error. If we returned nulls for
// such keys, i.e., treated them as non-existent, this would lead to a
// paradox where a key exists, but it does not when it is retrieved.
// http://www.w3.org/TR/2009/WD-webstorage-20091029/#the-storage-interface
var value = this.storage_.getItem(key);
if (!goog.isString(value) && !goog.isNull(value)) {
throw goog.storage.mechanism.ErrorCode.INVALID_VALUE;
}
return value;
};
/** @override */
goog.storage.mechanism.HTML5WebStorage.prototype.remove = function(key) {
this.storage_.removeItem(key);
};
/** @override */
goog.storage.mechanism.HTML5WebStorage.prototype.getCount = function() {
return this.storage_.length;
};
/** @override */
goog.storage.mechanism.HTML5WebStorage.prototype.__iterator__ = function(
opt_keys) {
var i = 0;
var storage = this.storage_;
var newIter = new goog.iter.Iterator();
newIter.next = function() {
if (i >= storage.length) {
throw goog.iter.StopIteration;
}
var key = goog.asserts.assertString(storage.key(i++));
if (opt_keys) {
return key;
}
var value = storage.getItem(key);
// The value must exist and be a string, otherwise it is a storage error.
if (!goog.isString(value)) {
throw goog.storage.mechanism.ErrorCode.INVALID_VALUE;
}
return value;
};
return newIter;
};
/** @override */
goog.storage.mechanism.HTML5WebStorage.prototype.clear = function() {
this.storage_.clear();
};
/**
* Gets the key for a given key index. If an index outside of
* [0..this.getCount()) is specified, this function returns null.
* @param {number} index A key index.
* @return {?string} A storage key, or null if the specified index is out of
* range.
*/
goog.storage.mechanism.HTML5WebStorage.prototype.key = function(index) {
return this.storage_.key(index);
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Abstract interface for storing and retrieving data using
* some persistence mechanism.
*
*/
goog.provide('goog.storage.mechanism.Mechanism');
/**
* Basic interface for all storage mechanisms.
*
* @constructor
*/
goog.storage.mechanism.Mechanism = function() {};
/**
* Set a value for a key.
*
* @param {string} key The key to set.
* @param {string} value The string to save.
*/
goog.storage.mechanism.Mechanism.prototype.set = goog.abstractMethod;
/**
* Get the value stored under a key.
*
* @param {string} key The key to get.
* @return {?string} The corresponding value, null if not found.
*/
goog.storage.mechanism.Mechanism.prototype.get = goog.abstractMethod;
/**
* Remove a key and its value.
*
* @param {string} key The key to remove.
*/
goog.storage.mechanism.Mechanism.prototype.remove = goog.abstractMethod;
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the iterable storage mechanism interface.
*
* These tests should be included in tests of any class extending
* goog.storage.mechanism.IterableMechanism.
*
*/
goog.provide('goog.storage.mechanism.iterableMechanismTester');
goog.require('goog.iter.Iterator');
goog.require('goog.storage.mechanism.IterableMechanism');
goog.require('goog.testing.asserts');
goog.setTestOnly('iterableMechanismTester');
var mechanism = null;
function testCount() {
if (!mechanism) {
return;
}
assertEquals(0, mechanism.getCount());
mechanism.set('first', 'one');
assertEquals(1, mechanism.getCount());
mechanism.set('second', 'two');
assertEquals(2, mechanism.getCount());
mechanism.set('first', 'three');
assertEquals(2, mechanism.getCount());
}
function testIteratorBasics() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
assertEquals('first', mechanism.__iterator__(true).next());
assertEquals('one', mechanism.__iterator__(false).next());
var iterator = mechanism.__iterator__();
assertEquals('one', iterator.next());
assertEquals(goog.iter.StopIteration,
assertThrows(iterator.next));
}
function testIteratorWithTwoValues() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.set('second', 'two');
assertSameElements(['one', 'two'], goog.iter.toArray(mechanism));
assertSameElements(['first', 'second'],
goog.iter.toArray(mechanism.__iterator__(true)));
}
function testClear() {
if (!mechanism) {
return;
}
mechanism.set('first', 'one');
mechanism.set('second', 'two');
mechanism.clear();
assertNull(mechanism.get('first'));
assertNull(mechanism.get('second'));
assertEquals(0, mechanism.getCount());
assertEquals(goog.iter.StopIteration,
assertThrows(mechanism.__iterator__(true).next));
assertEquals(goog.iter.StopIteration,
assertThrows(mechanism.__iterator__(false).next));
}
function testClearClear() {
if (!mechanism) {
return;
}
mechanism.clear();
mechanism.clear();
assertEquals(0, mechanism.getCount());
}
function testIteratorWithWeirdKeys() {
if (!mechanism) {
return;
}
mechanism.set(' ', 'space');
mechanism.set('=+!@#$%^&*()-_\\|;:\'",./<>?[]{}~`', 'control');
mechanism.set(
'\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341', 'ten');
assertEquals(3, mechanism.getCount());
assertSameElements([
' ',
'=+!@#$%^&*()-_\\|;:\'",./<>?[]{}~`',
'\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341'
], goog.iter.toArray(mechanism.__iterator__(true)));
mechanism.clear();
assertEquals(0, mechanism.getCount());
}
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides data persistence using IE userData mechanism.
* UserData uses proprietary Element.addBehavior(), Element.load(),
* Element.save(), and Element.XMLDocument() methods, see:
* http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx.
*
*/
goog.provide('goog.storage.mechanism.IEUserData');
goog.require('goog.asserts');
goog.require('goog.iter.Iterator');
goog.require('goog.iter.StopIteration');
goog.require('goog.storage.mechanism.ErrorCode');
goog.require('goog.storage.mechanism.IterableMechanism');
goog.require('goog.structs.Map');
goog.require('goog.userAgent');
/**
* Provides a storage mechanism using IE userData.
*
* @param {string} storageKey The key (store name) to store the data under.
* @param {string=} opt_storageNodeId The ID of the associated HTML element,
* one will be created if not provided.
* @constructor
* @extends {goog.storage.mechanism.IterableMechanism}
*/
goog.storage.mechanism.IEUserData = function(storageKey, opt_storageNodeId) {
goog.base(this);
// Tested on IE6, IE7 and IE8. It seems that IE9 introduces some security
// features which make persistent (loaded) node attributes invisible from
// JavaScript.
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
if (!goog.storage.mechanism.IEUserData.storageMap_) {
goog.storage.mechanism.IEUserData.storageMap_ = new goog.structs.Map();
}
this.storageNode_ = /** @type {Element} */ (
goog.storage.mechanism.IEUserData.storageMap_.get(storageKey));
if (!this.storageNode_) {
if (opt_storageNodeId) {
this.storageNode_ = document.getElementById(opt_storageNodeId);
} else {
this.storageNode_ = document.createElement('userdata');
// This is a special IE-only method letting us persist data.
this.storageNode_['addBehavior']('#default#userData');
document.body.appendChild(this.storageNode_);
}
goog.storage.mechanism.IEUserData.storageMap_.set(
storageKey, this.storageNode_);
}
this.storageKey_ = storageKey;
/** @preserveTry */
try {
// Availability check.
this.loadNode_();
} catch (e) {
this.storageNode_ = null;
}
}
};
goog.inherits(goog.storage.mechanism.IEUserData,
goog.storage.mechanism.IterableMechanism);
/**
* Encoding map for characters which are not encoded by encodeURIComponent().
* See encodeKey_ documentation for encoding details.
*
* @type {!Object}
* @const
*/
goog.storage.mechanism.IEUserData.ENCODE_MAP = {
'.': '.2E',
'!': '.21',
'~': '.7E',
'*': '.2A',
'\'': '.27',
'(': '.28',
')': '.29',
'%': '.'
};
/**
* Global storageKey to storageNode map, so we save on reloading the storage.
*
* @type {goog.structs.Map}
* @private
*/
goog.storage.mechanism.IEUserData.storageMap_ = null;
/**
* The document element used for storing data.
*
* @type {Element}
* @private
*/
goog.storage.mechanism.IEUserData.prototype.storageNode_ = null;
/**
* The key to store the data under.
*
* @type {?string}
* @private
*/
goog.storage.mechanism.IEUserData.prototype.storageKey_ = null;
/**
* Encodes anything other than [-a-zA-Z0-9_] using a dot followed by hex,
* and prefixes with underscore to form a valid and safe HTML attribute name.
*
* We use URI encoding to do the initial heavy lifting, then escape the
* remaining characters that we can't use. Since a valid attribute name can't
* contain the percent sign (%), we use a dot (.) as an escape character.
*
* @param {string} key The key to be encoded.
* @return {string} The encoded key.
* @private
*/
goog.storage.mechanism.IEUserData.encodeKey_ = function(key) {
// encodeURIComponent leaves - _ . ! ~ * ' ( ) unencoded.
return '_' + encodeURIComponent(key).replace(/[.!~*'()%]/g, function(c) {
return goog.storage.mechanism.IEUserData.ENCODE_MAP[c];
});
};
/**
* Decodes a dot-encoded and character-prefixed key.
* See encodeKey_ documentation for encoding details.
*
* @param {string} key The key to be decoded.
* @return {string} The decoded key.
* @private
*/
goog.storage.mechanism.IEUserData.decodeKey_ = function(key) {
return decodeURIComponent(key.replace(/\./g, '%')).substr(1);
};
/**
* Determines whether or not the mechanism is available.
*
* @return {boolean} True if the mechanism is available.
*/
goog.storage.mechanism.IEUserData.prototype.isAvailable = function() {
return !!this.storageNode_;
};
/** @override */
goog.storage.mechanism.IEUserData.prototype.set = function(key, value) {
this.storageNode_.setAttribute(
goog.storage.mechanism.IEUserData.encodeKey_(key), value);
this.saveNode_();
};
/** @override */
goog.storage.mechanism.IEUserData.prototype.get = function(key) {
// According to Microsoft, values can be strings, numbers or booleans. Since
// we only save strings, any other type is a storage error. If we returned
// nulls for such keys, i.e., treated them as non-existent, this would lead
// to a paradox where a key exists, but it does not when it is retrieved.
// http://msdn.microsoft.com/en-us/library/ms531348(v=vs.85).aspx
var value = this.storageNode_.getAttribute(
goog.storage.mechanism.IEUserData.encodeKey_(key));
if (!goog.isString(value) && !goog.isNull(value)) {
throw goog.storage.mechanism.ErrorCode.INVALID_VALUE;
}
return value;
};
/** @override */
goog.storage.mechanism.IEUserData.prototype.remove = function(key) {
this.storageNode_.removeAttribute(
goog.storage.mechanism.IEUserData.encodeKey_(key));
this.saveNode_();
};
/** @override */
goog.storage.mechanism.IEUserData.prototype.getCount = function() {
return this.getNode_().attributes.length;
};
/** @override */
goog.storage.mechanism.IEUserData.prototype.__iterator__ = function(opt_keys) {
var i = 0;
var attributes = this.getNode_().attributes;
var newIter = new goog.iter.Iterator();
newIter.next = function() {
if (i >= attributes.length) {
throw goog.iter.StopIteration;
}
var item = goog.asserts.assert(attributes[i++]);
if (opt_keys) {
return goog.storage.mechanism.IEUserData.decodeKey_(item.nodeName);
}
var value = item.nodeValue;
// The value must exist and be a string, otherwise it is a storage error.
if (!goog.isString(value)) {
throw goog.storage.mechanism.ErrorCode.INVALID_VALUE;
}
return value;
};
return newIter;
};
/** @override */
goog.storage.mechanism.IEUserData.prototype.clear = function() {
var node = this.getNode_();
for (var left = node.attributes.length; left > 0; left--) {
node.removeAttribute(node.attributes[left - 1].nodeName);
}
this.saveNode_();
};
/**
* Loads the underlying storage node to the state we saved it to before.
*
* @private
*/
goog.storage.mechanism.IEUserData.prototype.loadNode_ = function() {
// This is a special IE-only method on Elements letting us persist data.
this.storageNode_['load'](this.storageKey_);
};
/**
* Saves the underlying storage node.
*
* @private
*/
goog.storage.mechanism.IEUserData.prototype.saveNode_ = function() {
/** @preserveTry */
try {
// This is a special IE-only method on Elements letting us persist data.
// Do not try to assign this.storageNode_['save'] to a variable, it does
// not work. May throw an exception when the quota is exceeded.
this.storageNode_['save'](this.storageKey_);
} catch (e) {
throw goog.storage.mechanism.ErrorCode.QUOTA_EXCEEDED;
}
};
/**
* Returns the storage node.
*
* @return {Element} Storage DOM Element.
* @private
*/
goog.storage.mechanism.IEUserData.prototype.getNode_ = function() {
// This is a special IE-only property letting us browse persistent data.
var doc = /** @type {Document} */ (this.storageNode_['XMLDocument']);
return doc.documentElement;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines error codes to be thrown by storage mechanisms.
*
*/
goog.provide('goog.storage.mechanism.ErrorCode');
/**
* Errors thrown by storage mechanisms.
* @enum {string}
*/
goog.storage.mechanism.ErrorCode = {
INVALID_VALUE: 'Storage mechanism: Invalid value was encountered',
QUOTA_EXCEEDED: 'Storage mechanism: Quota exceeded',
STORAGE_DISABLED: 'Storage mechanism: Storage disabled'
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for storage mechanism sharing.
*
* These tests should be included in tests of any storage mechanism in which
* separate mechanism instances share the same underlying storage. Most (if
* not all) storage mechanisms should have this property. If the mechanism
* employs namespaces, make sure the same namespace is used for both objects.
*
*/
goog.provide('goog.storage.mechanism.mechanismSharingTester');
goog.require('goog.iter.Iterator');
goog.require('goog.storage.mechanism.IterableMechanism');
goog.require('goog.testing.asserts');
goog.setTestOnly('goog.storage.mechanism.mechanismSharingTester');
var mechanism = null;
var mechanism_shared = null;
function testSharedSet() {
if (!mechanism || !mechanism_shared) {
return;
}
mechanism.set('first', 'one');
assertEquals('one', mechanism_shared.get('first'));
assertEquals(1, mechanism_shared.getCount());
var iterator = mechanism_shared.__iterator__();
assertEquals('one', iterator.next());
assertEquals(goog.iter.StopIteration,
assertThrows(iterator.next));
}
function testSharedSetInverse() {
if (!mechanism || !mechanism_shared) {
return;
}
mechanism_shared.set('first', 'two');
assertEquals('two', mechanism.get('first'));
assertEquals(1, mechanism.getCount());
var iterator = mechanism.__iterator__();
assertEquals('two', iterator.next());
assertEquals(goog.iter.StopIteration,
assertThrows(iterator.next));
}
function testSharedRemove() {
if (!mechanism || !mechanism_shared) {
return;
}
mechanism_shared.set('first', 'three');
mechanism.remove('first');
assertNull(mechanism_shared.get('first'));
assertEquals(0, mechanism_shared.getCount());
assertEquals(goog.iter.StopIteration,
assertThrows(mechanism_shared.__iterator__().next));
}
function testSharedClean() {
if (!mechanism || !mechanism_shared) {
return;
}
mechanism.set('first', 'four');
mechanism_shared.clear();
assertEquals(0, mechanism.getCount());
assertEquals(goog.iter.StopIteration,
assertThrows(mechanism.__iterator__().next));
}
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides data persistence using HTML5 session storage
* mechanism. Session storage must be available under window.sessionStorage,
* see: http://www.w3.org/TR/webstorage/#the-sessionstorage-attribute.
*
*/
goog.provide('goog.storage.mechanism.HTML5SessionStorage');
goog.require('goog.storage.mechanism.HTML5WebStorage');
/**
* Provides a storage mechanism that uses HTML5 session storage.
*
* @constructor
* @extends {goog.storage.mechanism.HTML5WebStorage}
*/
goog.storage.mechanism.HTML5SessionStorage = function() {
var storage = null;
/** @preserveTry */
try {
// May throw an exception in cases where the session storage object is
// visible but access to it is disabled. For example, accessing the file
// in local mode in Firefox throws 'Operation is not supported' exception.
storage = window.sessionStorage || null;
} catch (e) {}
goog.base(this, storage);
};
goog.inherits(goog.storage.mechanism.HTML5SessionStorage,
goog.storage.mechanism.HTML5WebStorage);
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wraps a storage mechanism with a custom error handler.
*
*/
goog.provide('goog.storage.mechanism.ErrorHandlingMechanism');
goog.require('goog.storage.mechanism.Mechanism');
/**
* Wraps a storage mechanism with a custom error handler.
*
* @param {!goog.storage.mechanism.Mechanism} mechanism Underlying storage
* mechanism.
* @param {goog.storage.mechanism.ErrorHandlingMechanism.ErrorHandler}
* errorHandler An error handler.
* @constructor
* @extends {goog.storage.mechanism.Mechanism}
*/
goog.storage.mechanism.ErrorHandlingMechanism = function(mechanism,
errorHandler) {
goog.base(this);
/**
* The mechanism to be wrapped.
* @type {!goog.storage.mechanism.Mechanism}
* @private
*/
this.mechanism_ = mechanism;
/**
* The error handler.
* @type {goog.storage.mechanism.ErrorHandlingMechanism.ErrorHandler}
* @private
*/
this.errorHandler_ = errorHandler;
};
goog.inherits(goog.storage.mechanism.ErrorHandlingMechanism,
goog.storage.mechanism.Mechanism);
/**
* Valid storage mechanism operations.
* @enum {string}
*/
goog.storage.mechanism.ErrorHandlingMechanism.Operation = {
SET: 'set',
GET: 'get',
REMOVE: 'remove'
};
/**
* A function that handles errors raised in goog.storage. Since some places in
* the goog.storage codebase throw strings instead of Error objects, we accept
* these as a valid parameter type. It supports the following arguments:
*
* 1) The raised error (either in Error or string form);
* 2) The operation name which triggered the error, as defined per the
* ErrorHandlingMechanism.Operation enum;
* 3) The key that is passed to a storage method;
* 4) An optional value that is passed to a storage method (only used in set
* operations).
*
* @typedef {function(
* (!Error|string),
* goog.storage.mechanism.ErrorHandlingMechanism.Operation,
* string,
* *=)}
*/
goog.storage.mechanism.ErrorHandlingMechanism.ErrorHandler;
/** @override */
goog.storage.mechanism.ErrorHandlingMechanism.prototype.set = function(key,
value) {
try {
this.mechanism_.set(key, value);
} catch (e) {
this.errorHandler_(
e,
goog.storage.mechanism.ErrorHandlingMechanism.Operation.SET,
key,
value);
}
};
/** @override */
goog.storage.mechanism.ErrorHandlingMechanism.prototype.get = function(key) {
try {
return this.mechanism_.get(key);
} catch (e) {
this.errorHandler_(
e,
goog.storage.mechanism.ErrorHandlingMechanism.Operation.GET,
key);
}
};
/** @override */
goog.storage.mechanism.ErrorHandlingMechanism.prototype.remove = function(key) {
try {
this.mechanism_.remove(key);
} catch (e) {
this.errorHandler_(
e,
goog.storage.mechanism.ErrorHandlingMechanism.Operation.REMOVE,
key);
}
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides data persistence using HTML5 local storage
* mechanism. Local storage must be available under window.localStorage,
* see: http://www.w3.org/TR/webstorage/#the-localstorage-attribute.
*
*/
goog.provide('goog.storage.mechanism.HTML5LocalStorage');
goog.require('goog.storage.mechanism.HTML5WebStorage');
/**
* Provides a storage mechanism that uses HTML5 local storage.
*
* @constructor
* @extends {goog.storage.mechanism.HTML5WebStorage}
*/
goog.storage.mechanism.HTML5LocalStorage = function() {
var storage = null;
/** @preserveTry */
try {
// May throw an exception in cases where the local storage object
// is visible but access to it is disabled.
storage = window.localStorage || null;
} catch (e) {}
goog.base(this, storage);
};
goog.inherits(goog.storage.mechanism.HTML5LocalStorage,
goog.storage.mechanism.HTML5WebStorage);
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Interface for storing, retieving and scanning data using some
* persistence mechanism.
*
*/
goog.provide('goog.storage.mechanism.IterableMechanism');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.iter');
goog.require('goog.iter.Iterator');
goog.require('goog.storage.mechanism.Mechanism');
/**
* Interface for all iterable storage mechanisms.
*
* @constructor
* @extends {goog.storage.mechanism.Mechanism}
*/
goog.storage.mechanism.IterableMechanism = function() {
goog.base(this);
};
goog.inherits(goog.storage.mechanism.IterableMechanism,
goog.storage.mechanism.Mechanism);
/**
* Get the number of stored key-value pairs.
*
* Could be overridden in a subclass, as the default implementation is not very
* efficient - it iterates over all keys.
*
* @return {number} Number of stored elements.
*/
goog.storage.mechanism.IterableMechanism.prototype.getCount = function() {
var count = 0;
goog.iter.forEach(this.__iterator__(true), function(key) {
goog.asserts.assertString(key);
count++;
});
return count;
};
/**
* Returns an iterator that iterates over the elements in the storage. Will
* throw goog.iter.StopIteration after the last element.
*
* @param {boolean=} opt_keys True to iterate over the keys. False to iterate
* over the values. The default value is false.
* @return {!goog.iter.Iterator} The iterator.
*/
goog.storage.mechanism.IterableMechanism.prototype.__iterator__ =
goog.abstractMethod;
/**
* Remove all key-value pairs.
*
* Could be overridden in a subclass, as the default implementation is not very
* efficient - it iterates over all keys.
*/
goog.storage.mechanism.IterableMechanism.prototype.clear = function() {
var keys = goog.iter.toArray(this.__iterator__(true));
var selfObj = this;
goog.array.forEach(keys, function(key) {
selfObj.remove(key);
});
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides factory methods for selecting the best storage
* mechanism, depending on availability and needs.
*
*/
goog.provide('goog.storage.mechanism.mechanismfactory');
goog.require('goog.storage.mechanism.HTML5LocalStorage');
goog.require('goog.storage.mechanism.HTML5SessionStorage');
goog.require('goog.storage.mechanism.IEUserData');
goog.require('goog.storage.mechanism.IterableMechanism');
goog.require('goog.storage.mechanism.PrefixedMechanism');
/**
* The key to shared userData storage.
* @type {string}
*/
goog.storage.mechanism.mechanismfactory.USER_DATA_SHARED_KEY =
'UserDataSharedStore';
/**
* Returns the best local storage mechanism, or null if unavailable.
* Local storage means that the database is placed on user's computer.
* The key-value database is normally shared between all the code paths
* that request it, so using an optional namespace is recommended. This
* provides separation and makes key collisions unlikely.
*
* @param {string=} opt_namespace Restricts the visibility to given namespace.
* @return {goog.storage.mechanism.IterableMechanism} Created mechanism or null.
*/
goog.storage.mechanism.mechanismfactory.create = function(opt_namespace) {
return goog.storage.mechanism.mechanismfactory.createHTML5LocalStorage(
opt_namespace) ||
goog.storage.mechanism.mechanismfactory.createIEUserData(opt_namespace);
};
/**
* Returns an HTML5 local storage mechanism, or null if unavailable.
* Since the HTML5 local storage does not support namespaces natively,
* and the key-value database is shared between all the code paths
* that request it, it is recommended that an optional namespace is
* used to provide key separation employing a prefix.
*
* @param {string=} opt_namespace Restricts the visibility to given namespace.
* @return {goog.storage.mechanism.IterableMechanism} Created mechanism or null.
*/
goog.storage.mechanism.mechanismfactory.createHTML5LocalStorage = function(
opt_namespace) {
var storage = new goog.storage.mechanism.HTML5LocalStorage();
if (storage.isAvailable()) {
return opt_namespace ? new goog.storage.mechanism.PrefixedMechanism(
storage, opt_namespace) : storage;
}
return null;
};
/**
* Returns an HTML5 session storage mechanism, or null if unavailable.
* Since the HTML5 session storage does not support namespaces natively,
* and the key-value database is shared between all the code paths
* that request it, it is recommended that an optional namespace is
* used to provide key separation employing a prefix.
*
* @param {string=} opt_namespace Restricts the visibility to given namespace.
* @return {goog.storage.mechanism.IterableMechanism} Created mechanism or null.
*/
goog.storage.mechanism.mechanismfactory.createHTML5SessionStorage = function(
opt_namespace) {
var storage = new goog.storage.mechanism.HTML5SessionStorage();
if (storage.isAvailable()) {
return opt_namespace ? new goog.storage.mechanism.PrefixedMechanism(
storage, opt_namespace) : storage;
}
return null;
};
/**
* Returns an IE userData local storage mechanism, or null if unavailable.
* Using an optional namespace is recommended to provide separation and
* avoid key collisions.
*
* @param {string=} opt_namespace Restricts the visibility to given namespace.
* @return {goog.storage.mechanism.IterableMechanism} Created mechanism or null.
*/
goog.storage.mechanism.mechanismfactory.createIEUserData = function(
opt_namespace) {
var storage = new goog.storage.mechanism.IEUserData(opt_namespace ||
goog.storage.mechanism.mechanismfactory.USER_DATA_SHARED_KEY);
if (storage.isAvailable()) {
return storage;
}
return null;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a convenient API for data with attached metadata
* persistence. You probably don't want to use this class directly as it
* does not save any metadata by itself. It only provides the necessary
* infrastructure for subclasses that need to save metadata along with
* values stored.
*
*/
goog.provide('goog.storage.RichStorage');
goog.provide('goog.storage.RichStorage.Wrapper');
goog.require('goog.storage.ErrorCode');
goog.require('goog.storage.Storage');
goog.require('goog.storage.mechanism.Mechanism');
/**
* Provides a storage for data with attached metadata.
*
* @param {!goog.storage.mechanism.Mechanism} mechanism The underlying
* storage mechanism.
* @constructor
* @extends {goog.storage.Storage}
*/
goog.storage.RichStorage = function(mechanism) {
goog.base(this, mechanism);
};
goog.inherits(goog.storage.RichStorage, goog.storage.Storage);
/**
* Metadata key under which the actual data is stored.
*
* @type {string}
* @protected
*/
goog.storage.RichStorage.DATA_KEY = 'data';
/**
* Wraps a value so metadata can be associated with it. You probably want
* to use goog.storage.RichStorage.Wrapper.wrapIfNecessary to avoid multiple
* embeddings.
*
* @param {*} value The value to wrap.
* @constructor
*/
goog.storage.RichStorage.Wrapper = function(value) {
this[goog.storage.RichStorage.DATA_KEY] = value;
};
/**
* Convenience method for wrapping a value so metadata can be associated with
* it. No-op if the value is already wrapped or is undefined.
*
* @param {*} value The value to wrap.
* @return {(!goog.storage.RichStorage.Wrapper|undefined)} The wrapper.
*/
goog.storage.RichStorage.Wrapper.wrapIfNecessary = function(value) {
if (!goog.isDef(value) || value instanceof goog.storage.RichStorage.Wrapper) {
return /** @type {(!goog.storage.RichStorage.Wrapper|undefined)} */ (value);
}
return new goog.storage.RichStorage.Wrapper(value);
};
/**
* Unwraps a value, any metadata is discarded (not returned). You might want to
* use goog.storage.RichStorage.Wrapper.unwrapIfPossible to handle cases where
* the wrapper is missing.
*
* @param {!Object} wrapper The wrapper.
* @return {*} The wrapped value.
*/
goog.storage.RichStorage.Wrapper.unwrap = function(wrapper) {
var value = wrapper[goog.storage.RichStorage.DATA_KEY];
if (!goog.isDef(value)) {
throw goog.storage.ErrorCode.INVALID_VALUE;
}
return value;
};
/**
* Convenience method for unwrapping a value. Returns undefined if the
* wrapper is missing.
*
* @param {(!Object|undefined)} wrapper The wrapper.
* @return {*} The wrapped value or undefined.
*/
goog.storage.RichStorage.Wrapper.unwrapIfPossible = function(wrapper) {
if (!wrapper) {
return undefined;
}
return goog.storage.RichStorage.Wrapper.unwrap(wrapper);
};
/** @override */
goog.storage.RichStorage.prototype.set = function(key, value) {
goog.base(this, 'set', key,
goog.storage.RichStorage.Wrapper.wrapIfNecessary(value));
};
/**
* Get an item wrapper (the item and its metadata) from the storage.
*
* WARNING: This returns an Object, which once used to be
* goog.storage.RichStorage.Wrapper. This is due to the fact
* that deserialized objects lose type information and it
* is hard to do proper typecasting in JavaScript. Be sure
* you know what you are doing when using the returned value.
*
* @param {string} key The key to get.
* @return {(!Object|undefined)} The wrapper, or undefined if not found.
*/
goog.storage.RichStorage.prototype.getWrapper = function(key) {
var wrapper = goog.storage.RichStorage.superClass_.get.call(this, key);
if (!goog.isDef(wrapper) || wrapper instanceof Object) {
return /** @type {(!Object|undefined)} */ (wrapper);
}
throw goog.storage.ErrorCode.INVALID_VALUE;
};
/** @override */
goog.storage.RichStorage.prototype.get = function(key) {
return goog.storage.RichStorage.Wrapper.unwrapIfPossible(
this.getWrapper(key));
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A timer class to which other classes and objects can
* listen on. This is only an abstraction above setInterval.
*
* @see ../demos/timers.html
*/
goog.provide('goog.Timer');
goog.require('goog.events.EventTarget');
/**
* Class for handling timing events.
*
* @param {number=} opt_interval Number of ms between ticks (Default: 1ms).
* @param {Object=} opt_timerObject An object that has setTimeout, setInterval,
* clearTimeout and clearInterval (eg Window).
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.Timer = function(opt_interval, opt_timerObject) {
goog.events.EventTarget.call(this);
/**
* Number of ms between ticks
* @type {number}
* @private
*/
this.interval_ = opt_interval || 1;
/**
* An object that implements setTimout, setInterval, clearTimeout and
* clearInterval. We default to the window object. Changing this on
* goog.Timer.prototype changes the object for all timer instances which can
* be useful if your environment has some other implementation of timers than
* the window object.
* @type {Object}
* @private
*/
this.timerObject_ = opt_timerObject || goog.Timer.defaultTimerObject;
/**
* Cached tick_ bound to the object for later use in the timer.
* @type {Function}
* @private
*/
this.boundTick_ = goog.bind(this.tick_, this);
/**
* Firefox browser often fires the timer event sooner
* (sometimes MUCH sooner) than the requested timeout. So we
* compare the time to when the event was last fired, and
* reschedule if appropriate. See also goog.Timer.intervalScale
* @type {number}
* @private
*/
this.last_ = goog.now();
};
goog.inherits(goog.Timer, goog.events.EventTarget);
/**
* Maximum timeout value.
*
* Timeout values too big to fit into a signed 32-bit integer may cause
* overflow in FF, Safari, and Chrome, resulting in the timeout being
* scheduled immediately. It makes more sense simply not to schedule these
* timeouts, since 24.8 days is beyond a reasonable expectation for the
* browser to stay open.
*
* @type {number}
* @private
*/
goog.Timer.MAX_TIMEOUT_ = 2147483647;
/**
* Whether this timer is enabled
* @type {boolean}
*/
goog.Timer.prototype.enabled = false;
/**
* An object that implements setTimout, setInterval, clearTimeout and
* clearInterval. We default to the global object. Changing
* goog.Timer.defaultTimerObject changes the object for all timer instances
* which can be useful if your environment has some other implementation of
* timers you'd like to use.
* @type {Object}
*/
goog.Timer.defaultTimerObject = goog.global;
/**
* A variable that controls the timer error correction. If the
* timer is called before the requested interval times
* intervalScale, which often happens on mozilla, the timer is
* rescheduled. See also this.last_
* @type {number}
*/
goog.Timer.intervalScale = 0.8;
/**
* Variable for storing the result of setInterval
* @type {?number}
* @private
*/
goog.Timer.prototype.timer_ = null;
/**
* Gets the interval of the timer.
* @return {number} interval Number of ms between ticks.
*/
goog.Timer.prototype.getInterval = function() {
return this.interval_;
};
/**
* Sets the interval of the timer.
* @param {number} interval Number of ms between ticks.
*/
goog.Timer.prototype.setInterval = function(interval) {
this.interval_ = interval;
if (this.timer_ && this.enabled) {
// Stop and then start the timer to reset the interval.
this.stop();
this.start();
} else if (this.timer_) {
this.stop();
}
};
/**
* Callback for the setTimeout used by the timer
* @private
*/
goog.Timer.prototype.tick_ = function() {
if (this.enabled) {
var elapsed = goog.now() - this.last_;
if (elapsed > 0 &&
elapsed < this.interval_ * goog.Timer.intervalScale) {
this.timer_ = this.timerObject_.setTimeout(this.boundTick_,
this.interval_ - elapsed);
return;
}
this.dispatchTick();
// The timer could be stopped in the timer event handler.
if (this.enabled) {
this.timer_ = this.timerObject_.setTimeout(this.boundTick_,
this.interval_);
this.last_ = goog.now();
}
}
};
/**
* Dispatches the TICK event. This is its own method so subclasses can override.
*/
goog.Timer.prototype.dispatchTick = function() {
this.dispatchEvent(goog.Timer.TICK);
};
/**
* Starts the timer.
*/
goog.Timer.prototype.start = function() {
this.enabled = true;
// If there is no interval already registered, start it now
if (!this.timer_) {
// IMPORTANT!
// window.setInterval in FireFox has a bug - it fires based on
// absolute time, rather than on relative time. What this means
// is that if a computer is sleeping/hibernating for 24 hours
// and the timer interval was configured to fire every 1000ms,
// then after the PC wakes up the timer will fire, in rapid
// succession, 3600*24 times.
// This bug is described here and is already fixed, but it will
// take time to propagate, so for now I am switching this over
// to setTimeout logic.
// https://bugzilla.mozilla.org/show_bug.cgi?id=376643
//
this.timer_ = this.timerObject_.setTimeout(this.boundTick_,
this.interval_);
this.last_ = goog.now();
}
};
/**
* Stops the timer.
*/
goog.Timer.prototype.stop = function() {
this.enabled = false;
if (this.timer_) {
this.timerObject_.clearTimeout(this.timer_);
this.timer_ = null;
}
};
/** @override */
goog.Timer.prototype.disposeInternal = function() {
goog.Timer.superClass_.disposeInternal.call(this);
this.stop();
delete this.timerObject_;
};
/**
* Constant for the timer's event type
* @type {string}
*/
goog.Timer.TICK = 'tick';
/**
* Calls the given function once, after the optional pause.
*
* The function is always called asynchronously, even if the delay is 0. This
* is a common trick to schedule a function to run after a batch of browser
* event processing.
*
* @param {Function} listener Function or object that has a handleEvent method.
* @param {number=} opt_delay Milliseconds to wait; default is 0.
* @param {Object=} opt_handler Object in whose scope to call the listener.
* @return {number} A handle to the timer ID.
*/
goog.Timer.callOnce = function(listener, opt_delay, opt_handler) {
if (goog.isFunction(listener)) {
if (opt_handler) {
listener = goog.bind(listener, opt_handler);
}
} else if (listener && typeof listener.handleEvent == 'function') {
// using typeof to prevent strict js warning
listener = goog.bind(listener.handleEvent, listener);
} else {
throw Error('Invalid listener argument');
}
if (opt_delay > goog.Timer.MAX_TIMEOUT_) {
// Timeouts greater than MAX_INT return immediately due to integer
// overflow in many browsers. Since MAX_INT is 24.8 days, just don't
// schedule anything at all.
return -1;
} else {
return goog.Timer.defaultTimerObject.setTimeout(
listener, opt_delay || 0);
}
};
/**
* Clears a timeout initiated by callOnce
* @param {?number} timerId a timer ID.
*/
goog.Timer.clear = function(timerId) {
goog.Timer.defaultTimerObject.clearTimeout(timerId);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// All other code copyright its respective owners(s).
/**
* @fileoverview Generated Protocol Buffer code for file
* closure/goog/proto2/package_test.proto.
*/
goog.provide('someprotopackage.TestPackageTypes');
goog.require('goog.proto2.Message');
goog.require('proto2.TestAllTypes');
goog.setTestOnly('package_test.pb');
/**
* Message TestPackageTypes.
* @constructor
* @extends {goog.proto2.Message}
*/
someprotopackage.TestPackageTypes = function() {
goog.proto2.Message.apply(this);
};
goog.inherits(someprotopackage.TestPackageTypes, goog.proto2.Message);
/**
* Overrides {@link goog.proto2.Message#clone} to specify its exact return type.
* @return {!someprotopackage.TestPackageTypes} The cloned message.
* @override
*/
someprotopackage.TestPackageTypes.prototype.clone;
/**
* Gets the value of the optional_int32 field.
* @return {?number} The value.
*/
someprotopackage.TestPackageTypes.prototype.getOptionalInt32 = function() {
return /** @type {?number} */ (this.get$Value(1));
};
/**
* Gets the value of the optional_int32 field or the default value if not set.
* @return {number} The value.
*/
someprotopackage.TestPackageTypes.prototype.getOptionalInt32OrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(1));
};
/**
* Sets the value of the optional_int32 field.
* @param {number} value The value.
*/
someprotopackage.TestPackageTypes.prototype.setOptionalInt32 = function(value) {
this.set$Value(1, value);
};
/**
* @return {boolean} Whether the optional_int32 field has a value.
*/
someprotopackage.TestPackageTypes.prototype.hasOptionalInt32 = function() {
return this.has$Value(1);
};
/**
* @return {number} The number of values in the optional_int32 field.
*/
someprotopackage.TestPackageTypes.prototype.optionalInt32Count = function() {
return this.count$Values(1);
};
/**
* Clears the values in the optional_int32 field.
*/
someprotopackage.TestPackageTypes.prototype.clearOptionalInt32 = function() {
this.clear$Field(1);
};
/**
* Gets the value of the other_all field.
* @return {proto2.TestAllTypes} The value.
*/
someprotopackage.TestPackageTypes.prototype.getOtherAll = function() {
return /** @type {proto2.TestAllTypes} */ (this.get$Value(2));
};
/**
* Gets the value of the other_all field or the default value if not set.
* @return {!proto2.TestAllTypes} The value.
*/
someprotopackage.TestPackageTypes.prototype.getOtherAllOrDefault = function() {
return /** @type {!proto2.TestAllTypes} */ (this.get$ValueOrDefault(2));
};
/**
* Sets the value of the other_all field.
* @param {!proto2.TestAllTypes} value The value.
*/
someprotopackage.TestPackageTypes.prototype.setOtherAll = function(value) {
this.set$Value(2, value);
};
/**
* @return {boolean} Whether the other_all field has a value.
*/
someprotopackage.TestPackageTypes.prototype.hasOtherAll = function() {
return this.has$Value(2);
};
/**
* @return {number} The number of values in the other_all field.
*/
someprotopackage.TestPackageTypes.prototype.otherAllCount = function() {
return this.count$Values(2);
};
/**
* Clears the values in the other_all field.
*/
someprotopackage.TestPackageTypes.prototype.clearOtherAll = function() {
this.clear$Field(2);
};
goog.proto2.Message.set$Metadata(someprotopackage.TestPackageTypes, {
0: {
name: 'TestPackageTypes',
fullName: 'someprotopackage.TestPackageTypes'
},
1: {
name: 'optional_int32',
fieldType: goog.proto2.Message.FieldType.INT32,
type: Number
},
2: {
name: 'other_all',
fieldType: goog.proto2.Message.FieldType.MESSAGE,
type: proto2.TestAllTypes
}
});
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Protocol Buffer 2 Serializer which serializes messages
* into a user-friendly text format. Note that this code can run a bit
* slowly (especially for parsing) and should therefore not be used for
* time or space-critical applications.
*
* @see http://goo.gl/QDmDr
*/
goog.provide('goog.proto2.TextFormatSerializer');
goog.provide('goog.proto2.TextFormatSerializer.Parser');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.json');
goog.require('goog.proto2.Serializer');
goog.require('goog.proto2.Util');
goog.require('goog.string');
/**
* TextFormatSerializer, a serializer which turns Messages into the human
* readable text format.
* @param {boolean=} opt_ignoreMissingFields If true, then fields that cannot be
* found on the proto when parsing the text format will be ignored.
* @constructor
* @extends {goog.proto2.Serializer}
*/
goog.proto2.TextFormatSerializer = function(opt_ignoreMissingFields) {
/**
* Whether to ignore fields not defined on the proto when parsing the text
* format.
* @type {boolean}
* @private
*/
this.ignoreMissingFields_ = !!opt_ignoreMissingFields;
};
goog.inherits(goog.proto2.TextFormatSerializer, goog.proto2.Serializer);
/**
* Deserializes a message from text format and places the data in the message.
* @param {goog.proto2.Message} message The message in which to
* place the information.
* @param {*} data The text format data.
* @return {?string} The parse error or null on success.
* @override
*/
goog.proto2.TextFormatSerializer.prototype.deserializeTo =
function(message, data) {
var descriptor = message.getDescriptor();
var textData = data.toString();
var parser = new goog.proto2.TextFormatSerializer.Parser();
if (!parser.parse(message, textData, this.ignoreMissingFields_)) {
return parser.getError();
}
return null;
};
/**
* Serializes a message to a string.
* @param {goog.proto2.Message} message The message to be serialized.
* @return {string} The serialized form of the message.
* @override
*/
goog.proto2.TextFormatSerializer.prototype.serialize = function(message) {
var printer = new goog.proto2.TextFormatSerializer.Printer_();
this.serializeMessage_(message, printer);
return printer.toString();
};
/**
* Serializes the message and prints the text form into the given printer.
* @param {goog.proto2.Message} message The message to serialize.
* @param {goog.proto2.TextFormatSerializer.Printer_} printer The printer to
* which the text format will be printed.
* @private
*/
goog.proto2.TextFormatSerializer.prototype.serializeMessage_ =
function(message, printer) {
var descriptor = message.getDescriptor();
var fields = descriptor.getFields();
// Add the defined fields, recursively.
goog.array.forEach(fields, function(field) {
this.printField_(message, field, printer);
}, this);
// Add the unknown fields, if any.
message.forEachUnknown(function(tag, value) {
if (!value) { return; }
printer.append(tag);
if (goog.typeOf(value) == 'object') {
printer.append(' {');
printer.appendLine();
printer.indent();
} else {
printer.append(': ');
}
switch (goog.typeOf(value)) {
case 'string':
value = goog.string.quote(/** @type {string} */ (value));
printer.append(value);
break;
case 'object':
this.serializeMessage_(value, printer);
break;
default:
printer.append(value.toString());
break;
}
if (goog.typeOf(value) == 'object') {
printer.dedent();
printer.append('}');
} else {
printer.appendLine();
}
}, this);
};
/**
* Prints the serialized value for the given field to the printer.
* @param {*} value The field's value.
* @param {goog.proto2.FieldDescriptor} field The field whose value is being
* printed.
* @param {goog.proto2.TextFormatSerializer.Printer_} printer The printer to
* which the value will be printed.
* @private
*/
goog.proto2.TextFormatSerializer.prototype.printFieldValue_ =
function(value, field, printer) {
switch (field.getFieldType()) {
case goog.proto2.FieldDescriptor.FieldType.DOUBLE:
case goog.proto2.FieldDescriptor.FieldType.FLOAT:
case goog.proto2.FieldDescriptor.FieldType.INT64:
case goog.proto2.FieldDescriptor.FieldType.UINT64:
case goog.proto2.FieldDescriptor.FieldType.INT32:
case goog.proto2.FieldDescriptor.FieldType.UINT32:
case goog.proto2.FieldDescriptor.FieldType.FIXED64:
case goog.proto2.FieldDescriptor.FieldType.FIXED32:
case goog.proto2.FieldDescriptor.FieldType.BOOL:
case goog.proto2.FieldDescriptor.FieldType.SFIXED32:
case goog.proto2.FieldDescriptor.FieldType.SFIXED64:
case goog.proto2.FieldDescriptor.FieldType.SINT32:
case goog.proto2.FieldDescriptor.FieldType.SINT64:
printer.append(value);
break;
case goog.proto2.FieldDescriptor.FieldType.BYTES:
case goog.proto2.FieldDescriptor.FieldType.STRING:
value = goog.string.quote(value.toString());
printer.append(value);
break;
case goog.proto2.FieldDescriptor.FieldType.ENUM:
// Search the enum type for a matching key.
var found = false;
goog.object.forEach(field.getNativeType(), function(eValue, key) {
if (eValue == value) {
printer.append(key);
found = true;
}
});
if (!found) {
// Otherwise, just print the numeric value.
printer.append(value.toString());
}
break;
case goog.proto2.FieldDescriptor.FieldType.GROUP:
case goog.proto2.FieldDescriptor.FieldType.MESSAGE:
this.serializeMessage_(
/** @type {goog.proto2.Message} */ (value), printer);
break;
}
};
/**
* Prints the serialized field to the printer.
* @param {goog.proto2.Message} message The parent message.
* @param {goog.proto2.FieldDescriptor} field The field to print.
* @param {goog.proto2.TextFormatSerializer.Printer_} printer The printer to
* which the field will be printed.
* @private
*/
goog.proto2.TextFormatSerializer.prototype.printField_ =
function(message, field, printer) {
// Skip fields not present.
if (!message.has(field)) {
return;
}
var count = message.countOf(field);
for (var i = 0; i < count; ++i) {
// Field name.
printer.append(field.getName());
// Field delimiter.
if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.MESSAGE ||
field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.GROUP) {
printer.append(' {');
printer.appendLine();
printer.indent();
} else {
printer.append(': ');
}
// Write the field value.
this.printFieldValue_(message.get(field, i), field, printer);
// Close the field.
if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.MESSAGE ||
field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.GROUP) {
printer.dedent();
printer.append('}');
printer.appendLine();
} else {
printer.appendLine();
}
}
};
////////////////////////////////////////////////////////////////////////////////
/**
* Helper class used by the text format serializer for pretty-printing text.
* @constructor
* @private
*/
goog.proto2.TextFormatSerializer.Printer_ = function() {
/**
* The current indentation count.
* @type {number}
* @private
*/
this.indentation_ = 0;
/**
* The buffer of string pieces.
* @type {Array.<string>}
* @private
*/
this.buffer_ = [];
/**
* Whether indentation is required before the next append of characters.
* @type {boolean}
* @private
*/
this.requiresIndentation_ = true;
};
/**
* @return {string} The contents of the printer.
* @override
*/
goog.proto2.TextFormatSerializer.Printer_.prototype.toString = function() {
return this.buffer_.join('');
};
/**
* Increases the indentation in the printer.
*/
goog.proto2.TextFormatSerializer.Printer_.prototype.indent = function() {
this.indentation_ += 2;
};
/**
* Decreases the indentation in the printer.
*/
goog.proto2.TextFormatSerializer.Printer_.prototype.dedent = function() {
this.indentation_ -= 2;
goog.asserts.assert(this.indentation_ >= 0);
};
/**
* Appends the given value to the printer.
* @param {*} value The value to append.
*/
goog.proto2.TextFormatSerializer.Printer_.prototype.append = function(value) {
if (this.requiresIndentation_) {
for (var i = 0; i < this.indentation_; ++i) {
this.buffer_.push(' ');
}
this.requiresIndentation_ = false;
}
this.buffer_.push(value.toString());
};
/**
* Appends a newline to the printer.
*/
goog.proto2.TextFormatSerializer.Printer_.prototype.appendLine = function() {
this.buffer_.push('\n');
this.requiresIndentation_ = true;
};
////////////////////////////////////////////////////////////////////////////////
/**
* Helper class for tokenizing the text format.
* @param {string} data The string data to tokenize.
* @param {boolean=} opt_ignoreWhitespace If true, whitespace tokens will not
* be reported by the tokenizer.
* @constructor
* @private
*/
goog.proto2.TextFormatSerializer.Tokenizer_ =
function(data, opt_ignoreWhitespace) {
/**
* Whether to skip whitespace tokens on output.
* @type {boolean}
* @private
*/
this.ignoreWhitespace_ = !!opt_ignoreWhitespace;
/**
* The data being tokenized.
* @type {string}
* @private
*/
this.data_ = data;
/**
* The current index in the data.
* @type {number}
* @private
*/
this.index_ = 0;
/**
* The data string starting at the current index.
* @type {string}
* @private
*/
this.currentData_ = data;
/**
* The current token type.
* @type {goog.proto2.TextFormatSerializer.Tokenizer_.Token}
* @private
*/
this.current_ = {
type: goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes.END,
value: null
};
};
/**
* @typedef {{type: goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes,
* value: ?string}}
*/
goog.proto2.TextFormatSerializer.Tokenizer_.Token;
/**
* @return {goog.proto2.TextFormatSerializer.Tokenizer_.Token} The current
* token.
*/
goog.proto2.TextFormatSerializer.Tokenizer_.prototype.getCurrent = function() {
return this.current_;
};
/**
* An enumeration of all the token types.
* @enum {*}
*/
goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes = {
END: /---end---/,
// Leading "-" to identify "-infinity"."
IDENTIFIER: /^-?[a-zA-Z][a-zA-Z0-9_]*/,
NUMBER: /^(0x[0-9a-f]+)|(([-])?[0-9][0-9]*(\.?[0-9]+)?([f])?)/,
COMMENT: /^#.*/,
OPEN_BRACE: /^{/,
CLOSE_BRACE: /^}/,
OPEN_TAG: /^</,
CLOSE_TAG: /^>/,
OPEN_LIST: /^\[/,
CLOSE_LIST: /^\]/,
STRING: new RegExp('^"([^"\\\\]|\\\\.)*"'),
COLON: /^:/,
COMMA: /^,/,
SEMI: /^;/,
WHITESPACE: /^\s/
};
/**
* Advances to the next token.
* @return {boolean} True if a valid token was found, false if the end was
* reached or no valid token was found.
*/
goog.proto2.TextFormatSerializer.Tokenizer_.prototype.next = function() {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
// Skip any whitespace if requested.
while (this.nextInternal_()) {
if (this.getCurrent().type != types.WHITESPACE || !this.ignoreWhitespace_) {
return true;
}
}
// If we reach this point, set the current token to END.
this.current_ = {
type: goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes.END,
value: null
};
return false;
};
/**
* Internal method for determining the next token.
* @return {boolean} True if a next token was found, false otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Tokenizer_.prototype.nextInternal_ =
function() {
if (this.index_ >= this.data_.length) {
return false;
}
var data = this.currentData_;
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
var next = null;
// Loop through each token type and try to match the beginning of the string
// with the token's regular expression.
goog.object.forEach(types, function(type, id) {
if (next || type == types.END) {
return;
}
// Note: This regular expression check is at, minimum, O(n).
var info = type.exec(data);
if (info && info.index == 0) {
next = {
type: type,
value: info[0]
};
}
});
// Advance the index by the length of the token.
if (next) {
this.current_ =
/** @type {goog.proto2.TextFormatSerializer.Tokenizer_.Token} */ (next);
this.index_ += next.value.length;
this.currentData_ = this.currentData_.substring(next.value.length);
}
return !!next;
};
////////////////////////////////////////////////////////////////////////////////
/**
* Helper class for parsing the text format.
* @constructor
*/
goog.proto2.TextFormatSerializer.Parser = function() {
/**
* The error during parsing, if any.
* @type {?string}
* @private
*/
this.error_ = null;
/**
* The current tokenizer.
* @type {goog.proto2.TextFormatSerializer.Tokenizer_}
* @private
*/
this.tokenizer_ = null;
/**
* Whether to ignore missing fields in the proto when parsing.
* @type {boolean}
* @private
*/
this.ignoreMissingFields_ = false;
};
/**
* Parses the given data, filling the message as it goes.
* @param {goog.proto2.Message} message The message to fill.
* @param {string} data The text format data.
* @param {boolean=} opt_ignoreMissingFields If true, fields missing in the
* proto will be ignored.
* @return {boolean} True on success, false on failure. On failure, the
* getError method can be called to get the reason for failure.
*/
goog.proto2.TextFormatSerializer.Parser.prototype.parse =
function(message, data, opt_ignoreMissingFields) {
this.error_ = null;
this.ignoreMissingFields_ = !!opt_ignoreMissingFields;
this.tokenizer_ = new goog.proto2.TextFormatSerializer.Tokenizer_(data, true);
this.tokenizer_.next();
return this.consumeMessage_(message, '');
};
/**
* @return {?string} The parse error, if any.
*/
goog.proto2.TextFormatSerializer.Parser.prototype.getError = function() {
return this.error_;
};
/**
* Reports a parse error.
* @param {string} msg The error message.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.reportError_ =
function(msg) {
this.error_ = msg;
};
/**
* Attempts to consume the given message.
* @param {goog.proto2.Message} message The message to consume and fill. If
* null, then the message contents will be consumed without ever being set
* to anything.
* @param {string} delimiter The delimiter expected at the end of the message.
* @return {boolean} True on success, false otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeMessage_ =
function(message, delimiter) {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
while (!this.lookingAt_('>') && !this.lookingAt_('}') &&
!this.lookingAtType_(types.END)) {
if (!this.consumeField_(message)) { return false; }
}
if (delimiter) {
if (!this.consume_(delimiter)) { return false; }
} else {
if (!this.lookingAtType_(types.END)) {
this.reportError_('Expected END token');
}
}
return true;
};
/**
* Attempts to consume the value of the given field.
* @param {goog.proto2.Message} message The parent message.
* @param {goog.proto2.FieldDescriptor} field The field.
* @return {boolean} True on success, false otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeFieldValue_ =
function(message, field) {
var value = this.getFieldValue_(field);
if (goog.isNull(value)) { return false; }
if (field.isRepeated()) {
message.add(field, value);
} else {
message.set(field, value);
}
return true;
};
/**
* Attempts to convert a string to a number.
* @param {string} num in hexadecimal or float format.
* @return {?number} The converted number or null on error.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.getNumberFromString_ =
function(num) {
var returnValue = goog.string.contains(num, '.') ?
parseFloat(num) : // num is a float.
goog.string.parseInt(num); // num is an int.
goog.asserts.assert(!isNaN(returnValue));
goog.asserts.assert(isFinite(returnValue));
return returnValue;
};
/**
* Parse NaN, positive infinity, or negative infinity from a string.
* @param {string} identifier An identifier string to check.
* @return {?number} Infinity, negative infinity, NaN, or null if none
* of the constants could be parsed.
* @private.
*/
goog.proto2.TextFormatSerializer.Parser.parseNumericalConstant_ =
function(identifier) {
if (/^-?inf(?:inity)?f?$/i.test(identifier)) {
return Infinity * (goog.string.startsWith(identifier, '-') ? -1 : 1);
}
if (/^nanf?$/i.test(identifier)) {
return NaN;
}
return null;
};
/**
* Attempts to parse the given field's value from the stream.
* @param {goog.proto2.FieldDescriptor} field The field.
* @return {*} The field's value or null if none.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.getFieldValue_ =
function(field) {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
switch (field.getFieldType()) {
case goog.proto2.FieldDescriptor.FieldType.DOUBLE:
case goog.proto2.FieldDescriptor.FieldType.FLOAT:
var identifier = this.consumeIdentifier_();
if (identifier) {
var numericalIdentifier =
goog.proto2.TextFormatSerializer.Parser.parseNumericalConstant_(
identifier);
// Use isDefAndNotNull since !!NaN is false.
if (goog.isDefAndNotNull(numericalIdentifier)) {
return numericalIdentifier;
}
}
case goog.proto2.FieldDescriptor.FieldType.INT32:
case goog.proto2.FieldDescriptor.FieldType.UINT32:
case goog.proto2.FieldDescriptor.FieldType.FIXED32:
case goog.proto2.FieldDescriptor.FieldType.SFIXED32:
case goog.proto2.FieldDescriptor.FieldType.SINT32:
var num = this.consumeNumber_();
if (!num) { return null; }
return goog.proto2.TextFormatSerializer.Parser.getNumberFromString_(num);
case goog.proto2.FieldDescriptor.FieldType.INT64:
case goog.proto2.FieldDescriptor.FieldType.UINT64:
case goog.proto2.FieldDescriptor.FieldType.FIXED64:
case goog.proto2.FieldDescriptor.FieldType.SFIXED64:
case goog.proto2.FieldDescriptor.FieldType.SINT64:
var num = this.consumeNumber_();
if (!num) { return null; }
if (field.getNativeType() == Number) {
// 64-bit number stored as a number.
return goog.proto2.TextFormatSerializer.Parser.getNumberFromString_(
num);
}
return num; // 64-bit numbers are by default stored as strings.
case goog.proto2.FieldDescriptor.FieldType.BOOL:
var ident = this.consumeIdentifier_();
if (!ident) { return null; }
switch (ident) {
case 'true': return true;
case 'false': return false;
default:
this.reportError_('Unknown type for bool: ' + ident);
return null;
}
case goog.proto2.FieldDescriptor.FieldType.ENUM:
if (this.lookingAtType_(types.NUMBER)) {
return this.consumeNumber_();
} else {
// Search the enum type for a matching key.
var name = this.consumeIdentifier_();
if (!name) {
return null;
}
var enumValue = field.getNativeType()[name];
if (enumValue == null) {
this.reportError_('Unknown enum value: ' + name);
return null;
}
return enumValue;
}
case goog.proto2.FieldDescriptor.FieldType.BYTES:
case goog.proto2.FieldDescriptor.FieldType.STRING:
return this.consumeString_();
}
};
/**
* Attempts to consume a nested message.
* @param {goog.proto2.Message} message The parent message.
* @param {goog.proto2.FieldDescriptor} field The field.
* @return {boolean} True on success, false otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeNestedMessage_ =
function(message, field) {
var delimiter = '';
// Messages support both < > and { } as delimiters for legacy reasons.
if (this.tryConsume_('<')) {
delimiter = '>';
} else {
if (!this.consume_('{')) { return false; }
delimiter = '}';
}
var msg = field.getFieldMessageType().createMessageInstance();
var result = this.consumeMessage_(msg, delimiter);
if (!result) { return false; }
// Add the message to the parent message.
if (field.isRepeated()) {
message.add(field, msg);
} else {
message.set(field, msg);
}
return true;
};
/**
* Attempts to consume the value of an unknown field. This method uses
* heuristics to try to consume just the right tokens.
* @return {boolean} True on success, false otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeUnknownFieldValue_ =
function() {
// : is optional.
this.tryConsume_(':');
// Handle form: [.. , ... , ..]
if (this.tryConsume_('[')) {
while (true) {
this.tokenizer_.next();
if (this.tryConsume_(']')) {
break;
}
if (!this.consume_(',')) { return false; }
}
return true;
}
// Handle nested messages/groups.
if (this.tryConsume_('<')) {
return this.consumeMessage_(null /* unknown */, '>');
} else if (this.tryConsume_('{')) {
return this.consumeMessage_(null /* unknown */, '}');
} else {
// Otherwise, consume a single token for the field value.
this.tokenizer_.next();
}
return true;
};
/**
* Attempts to consume a field under a message.
* @param {goog.proto2.Message} message The parent message. If null, then the
* field value will be consumed without being assigned to anything.
* @return {boolean} True on success, false otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeField_ =
function(message) {
var fieldName = this.consumeIdentifier_();
if (!fieldName) {
this.reportError_('Missing field name');
return false;
}
var field = null;
if (message) {
field = message.getDescriptor().findFieldByName(fieldName.toString());
}
if (field == null) {
if (this.ignoreMissingFields_) {
return this.consumeUnknownFieldValue_();
} else {
this.reportError_('Unknown field: ' + fieldName);
return false;
}
}
if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.MESSAGE ||
field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.GROUP) {
// : is optional here.
this.tryConsume_(':');
if (!this.consumeNestedMessage_(message, field)) { return false; }
} else {
// Long Format: "someField: 123"
// Short Format: "someField: [123, 456, 789]"
if (!this.consume_(':')) { return false; }
if (field.isRepeated() && this.tryConsume_('[')) {
// Short repeated format, e.g. "foo: [1, 2, 3]"
while (true) {
if (!this.consumeFieldValue_(message, field)) { return false; }
if (this.tryConsume_(']')) {
break;
}
if (!this.consume_(',')) { return false; }
}
} else {
// Normal field format.
if (!this.consumeFieldValue_(message, field)) { return false; }
}
}
// For historical reasons, fields may optionally be separated by commas or
// semicolons.
this.tryConsume_(',') || this.tryConsume_(';');
return true;
};
/**
* Attempts to consume a token with the given string value.
* @param {string} value The string value for the token.
* @return {boolean} True if the token matches and was consumed, false
* otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.tryConsume_ =
function(value) {
if (this.lookingAt_(value)) {
this.tokenizer_.next();
return true;
}
return false;
};
/**
* Consumes a token of the given type.
* @param {goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes} type The type
* of the token to consume.
* @return {?string} The string value of the token or null on error.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeToken_ =
function(type) {
if (!this.lookingAtType_(type)) {
this.reportError_('Expected token type: ' + type);
return null;
}
var value = this.tokenizer_.getCurrent().value;
this.tokenizer_.next();
return value;
};
/**
* Consumes an IDENTIFIER token.
* @return {?string} The string value or null on error.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeIdentifier_ =
function() {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
return this.consumeToken_(types.IDENTIFIER);
};
/**
* Consumes a NUMBER token.
* @return {?string} The string value or null on error.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeNumber_ =
function() {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
return this.consumeToken_(types.NUMBER);
};
/**
* Consumes a STRING token.
* @return {?string} The *deescaped* string value or null on error.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consumeString_ =
function() {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
var value = this.consumeToken_(types.STRING);
if (!value) {
return null;
}
return goog.json.parse(value).toString();
};
/**
* Consumes a token with the given value. If not found, reports an error.
* @param {string} value The string value expected for the token.
* @return {boolean} True on success, false otherwise.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.consume_ = function(value) {
if (!this.tryConsume_(value)) {
this.reportError_('Expected token "' + value + '"');
return false;
}
return true;
};
/**
* @param {string} value The value to check against.
* @return {boolean} True if the current token has the given string value.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.lookingAt_ =
function(value) {
return this.tokenizer_.getCurrent().value == value;
};
/**
* @param {goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes} type The
* token type.
* @return {boolean} True if the current token has the given type.
* @private
*/
goog.proto2.TextFormatSerializer.Parser.prototype.lookingAtType_ =
function(type) {
return this.tokenizer_.getCurrent().type == type;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// All other code copyright its respective owners(s).
/**
* @fileoverview Generated Protocol Buffer code for file
* closure/goog/proto2/test.proto.
*/
goog.provide('proto2.TestAllTypes');
goog.provide('proto2.TestAllTypes.NestedEnum');
goog.provide('proto2.TestAllTypes.NestedMessage');
goog.provide('proto2.TestAllTypes.OptionalGroup');
goog.provide('proto2.TestAllTypes.RepeatedGroup');
goog.require('goog.proto2.Message');
/**
* Message TestAllTypes.
* @constructor
* @extends {goog.proto2.Message}
*/
proto2.TestAllTypes = function() {
goog.proto2.Message.apply(this);
};
goog.inherits(proto2.TestAllTypes, goog.proto2.Message);
/**
* Overrides {@link goog.proto2.Message#clone} to specify its exact return type.
* @return {!proto2.TestAllTypes} The cloned message.
* @override
*/
proto2.TestAllTypes.prototype.clone;
/**
* Gets the value of the optional_int32 field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt32 = function() {
return /** @type {?number} */ (this.get$Value(1));
};
/**
* Gets the value of the optional_int32 field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt32OrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(1));
};
/**
* Sets the value of the optional_int32 field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalInt32 = function(value) {
this.set$Value(1, value);
};
/**
* @return {boolean} Whether the optional_int32 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalInt32 = function() {
return this.has$Value(1);
};
/**
* @return {number} The number of values in the optional_int32 field.
*/
proto2.TestAllTypes.prototype.optionalInt32Count = function() {
return this.count$Values(1);
};
/**
* Clears the values in the optional_int32 field.
*/
proto2.TestAllTypes.prototype.clearOptionalInt32 = function() {
this.clear$Field(1);
};
/**
* Gets the value of the optional_int64 field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt64 = function() {
return /** @type {?string} */ (this.get$Value(2));
};
/**
* Gets the value of the optional_int64 field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt64OrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(2));
};
/**
* Sets the value of the optional_int64 field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalInt64 = function(value) {
this.set$Value(2, value);
};
/**
* @return {boolean} Whether the optional_int64 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalInt64 = function() {
return this.has$Value(2);
};
/**
* @return {number} The number of values in the optional_int64 field.
*/
proto2.TestAllTypes.prototype.optionalInt64Count = function() {
return this.count$Values(2);
};
/**
* Clears the values in the optional_int64 field.
*/
proto2.TestAllTypes.prototype.clearOptionalInt64 = function() {
this.clear$Field(2);
};
/**
* Gets the value of the optional_uint32 field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalUint32 = function() {
return /** @type {?number} */ (this.get$Value(3));
};
/**
* Gets the value of the optional_uint32 field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalUint32OrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(3));
};
/**
* Sets the value of the optional_uint32 field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalUint32 = function(value) {
this.set$Value(3, value);
};
/**
* @return {boolean} Whether the optional_uint32 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalUint32 = function() {
return this.has$Value(3);
};
/**
* @return {number} The number of values in the optional_uint32 field.
*/
proto2.TestAllTypes.prototype.optionalUint32Count = function() {
return this.count$Values(3);
};
/**
* Clears the values in the optional_uint32 field.
*/
proto2.TestAllTypes.prototype.clearOptionalUint32 = function() {
this.clear$Field(3);
};
/**
* Gets the value of the optional_uint64 field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalUint64 = function() {
return /** @type {?string} */ (this.get$Value(4));
};
/**
* Gets the value of the optional_uint64 field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalUint64OrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(4));
};
/**
* Sets the value of the optional_uint64 field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalUint64 = function(value) {
this.set$Value(4, value);
};
/**
* @return {boolean} Whether the optional_uint64 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalUint64 = function() {
return this.has$Value(4);
};
/**
* @return {number} The number of values in the optional_uint64 field.
*/
proto2.TestAllTypes.prototype.optionalUint64Count = function() {
return this.count$Values(4);
};
/**
* Clears the values in the optional_uint64 field.
*/
proto2.TestAllTypes.prototype.clearOptionalUint64 = function() {
this.clear$Field(4);
};
/**
* Gets the value of the optional_sint32 field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSint32 = function() {
return /** @type {?number} */ (this.get$Value(5));
};
/**
* Gets the value of the optional_sint32 field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSint32OrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(5));
};
/**
* Sets the value of the optional_sint32 field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalSint32 = function(value) {
this.set$Value(5, value);
};
/**
* @return {boolean} Whether the optional_sint32 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalSint32 = function() {
return this.has$Value(5);
};
/**
* @return {number} The number of values in the optional_sint32 field.
*/
proto2.TestAllTypes.prototype.optionalSint32Count = function() {
return this.count$Values(5);
};
/**
* Clears the values in the optional_sint32 field.
*/
proto2.TestAllTypes.prototype.clearOptionalSint32 = function() {
this.clear$Field(5);
};
/**
* Gets the value of the optional_sint64 field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSint64 = function() {
return /** @type {?string} */ (this.get$Value(6));
};
/**
* Gets the value of the optional_sint64 field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSint64OrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(6));
};
/**
* Sets the value of the optional_sint64 field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalSint64 = function(value) {
this.set$Value(6, value);
};
/**
* @return {boolean} Whether the optional_sint64 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalSint64 = function() {
return this.has$Value(6);
};
/**
* @return {number} The number of values in the optional_sint64 field.
*/
proto2.TestAllTypes.prototype.optionalSint64Count = function() {
return this.count$Values(6);
};
/**
* Clears the values in the optional_sint64 field.
*/
proto2.TestAllTypes.prototype.clearOptionalSint64 = function() {
this.clear$Field(6);
};
/**
* Gets the value of the optional_fixed32 field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalFixed32 = function() {
return /** @type {?number} */ (this.get$Value(7));
};
/**
* Gets the value of the optional_fixed32 field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalFixed32OrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(7));
};
/**
* Sets the value of the optional_fixed32 field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalFixed32 = function(value) {
this.set$Value(7, value);
};
/**
* @return {boolean} Whether the optional_fixed32 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalFixed32 = function() {
return this.has$Value(7);
};
/**
* @return {number} The number of values in the optional_fixed32 field.
*/
proto2.TestAllTypes.prototype.optionalFixed32Count = function() {
return this.count$Values(7);
};
/**
* Clears the values in the optional_fixed32 field.
*/
proto2.TestAllTypes.prototype.clearOptionalFixed32 = function() {
this.clear$Field(7);
};
/**
* Gets the value of the optional_fixed64 field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalFixed64 = function() {
return /** @type {?string} */ (this.get$Value(8));
};
/**
* Gets the value of the optional_fixed64 field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalFixed64OrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(8));
};
/**
* Sets the value of the optional_fixed64 field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalFixed64 = function(value) {
this.set$Value(8, value);
};
/**
* @return {boolean} Whether the optional_fixed64 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalFixed64 = function() {
return this.has$Value(8);
};
/**
* @return {number} The number of values in the optional_fixed64 field.
*/
proto2.TestAllTypes.prototype.optionalFixed64Count = function() {
return this.count$Values(8);
};
/**
* Clears the values in the optional_fixed64 field.
*/
proto2.TestAllTypes.prototype.clearOptionalFixed64 = function() {
this.clear$Field(8);
};
/**
* Gets the value of the optional_sfixed32 field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSfixed32 = function() {
return /** @type {?number} */ (this.get$Value(9));
};
/**
* Gets the value of the optional_sfixed32 field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSfixed32OrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(9));
};
/**
* Sets the value of the optional_sfixed32 field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalSfixed32 = function(value) {
this.set$Value(9, value);
};
/**
* @return {boolean} Whether the optional_sfixed32 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalSfixed32 = function() {
return this.has$Value(9);
};
/**
* @return {number} The number of values in the optional_sfixed32 field.
*/
proto2.TestAllTypes.prototype.optionalSfixed32Count = function() {
return this.count$Values(9);
};
/**
* Clears the values in the optional_sfixed32 field.
*/
proto2.TestAllTypes.prototype.clearOptionalSfixed32 = function() {
this.clear$Field(9);
};
/**
* Gets the value of the optional_sfixed64 field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSfixed64 = function() {
return /** @type {?string} */ (this.get$Value(10));
};
/**
* Gets the value of the optional_sfixed64 field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalSfixed64OrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(10));
};
/**
* Sets the value of the optional_sfixed64 field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalSfixed64 = function(value) {
this.set$Value(10, value);
};
/**
* @return {boolean} Whether the optional_sfixed64 field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalSfixed64 = function() {
return this.has$Value(10);
};
/**
* @return {number} The number of values in the optional_sfixed64 field.
*/
proto2.TestAllTypes.prototype.optionalSfixed64Count = function() {
return this.count$Values(10);
};
/**
* Clears the values in the optional_sfixed64 field.
*/
proto2.TestAllTypes.prototype.clearOptionalSfixed64 = function() {
this.clear$Field(10);
};
/**
* Gets the value of the optional_float field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalFloat = function() {
return /** @type {?number} */ (this.get$Value(11));
};
/**
* Gets the value of the optional_float field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalFloatOrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(11));
};
/**
* Sets the value of the optional_float field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalFloat = function(value) {
this.set$Value(11, value);
};
/**
* @return {boolean} Whether the optional_float field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalFloat = function() {
return this.has$Value(11);
};
/**
* @return {number} The number of values in the optional_float field.
*/
proto2.TestAllTypes.prototype.optionalFloatCount = function() {
return this.count$Values(11);
};
/**
* Clears the values in the optional_float field.
*/
proto2.TestAllTypes.prototype.clearOptionalFloat = function() {
this.clear$Field(11);
};
/**
* Gets the value of the optional_double field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalDouble = function() {
return /** @type {?number} */ (this.get$Value(12));
};
/**
* Gets the value of the optional_double field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalDoubleOrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(12));
};
/**
* Sets the value of the optional_double field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalDouble = function(value) {
this.set$Value(12, value);
};
/**
* @return {boolean} Whether the optional_double field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalDouble = function() {
return this.has$Value(12);
};
/**
* @return {number} The number of values in the optional_double field.
*/
proto2.TestAllTypes.prototype.optionalDoubleCount = function() {
return this.count$Values(12);
};
/**
* Clears the values in the optional_double field.
*/
proto2.TestAllTypes.prototype.clearOptionalDouble = function() {
this.clear$Field(12);
};
/**
* Gets the value of the optional_bool field.
* @return {?boolean} The value.
*/
proto2.TestAllTypes.prototype.getOptionalBool = function() {
return /** @type {?boolean} */ (this.get$Value(13));
};
/**
* Gets the value of the optional_bool field or the default value if not set.
* @return {boolean} The value.
*/
proto2.TestAllTypes.prototype.getOptionalBoolOrDefault = function() {
return /** @type {boolean} */ (this.get$ValueOrDefault(13));
};
/**
* Sets the value of the optional_bool field.
* @param {boolean} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalBool = function(value) {
this.set$Value(13, value);
};
/**
* @return {boolean} Whether the optional_bool field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalBool = function() {
return this.has$Value(13);
};
/**
* @return {number} The number of values in the optional_bool field.
*/
proto2.TestAllTypes.prototype.optionalBoolCount = function() {
return this.count$Values(13);
};
/**
* Clears the values in the optional_bool field.
*/
proto2.TestAllTypes.prototype.clearOptionalBool = function() {
this.clear$Field(13);
};
/**
* Gets the value of the optional_string field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalString = function() {
return /** @type {?string} */ (this.get$Value(14));
};
/**
* Gets the value of the optional_string field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalStringOrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(14));
};
/**
* Sets the value of the optional_string field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalString = function(value) {
this.set$Value(14, value);
};
/**
* @return {boolean} Whether the optional_string field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalString = function() {
return this.has$Value(14);
};
/**
* @return {number} The number of values in the optional_string field.
*/
proto2.TestAllTypes.prototype.optionalStringCount = function() {
return this.count$Values(14);
};
/**
* Clears the values in the optional_string field.
*/
proto2.TestAllTypes.prototype.clearOptionalString = function() {
this.clear$Field(14);
};
/**
* Gets the value of the optional_bytes field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalBytes = function() {
return /** @type {?string} */ (this.get$Value(15));
};
/**
* Gets the value of the optional_bytes field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalBytesOrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(15));
};
/**
* Sets the value of the optional_bytes field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalBytes = function(value) {
this.set$Value(15, value);
};
/**
* @return {boolean} Whether the optional_bytes field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalBytes = function() {
return this.has$Value(15);
};
/**
* @return {number} The number of values in the optional_bytes field.
*/
proto2.TestAllTypes.prototype.optionalBytesCount = function() {
return this.count$Values(15);
};
/**
* Clears the values in the optional_bytes field.
*/
proto2.TestAllTypes.prototype.clearOptionalBytes = function() {
this.clear$Field(15);
};
/**
* Gets the value of the optionalgroup field.
* @return {proto2.TestAllTypes.OptionalGroup} The value.
*/
proto2.TestAllTypes.prototype.getOptionalgroup = function() {
return /** @type {proto2.TestAllTypes.OptionalGroup} */ (this.get$Value(16));
};
/**
* Gets the value of the optionalgroup field or the default value if not set.
* @return {!proto2.TestAllTypes.OptionalGroup} The value.
*/
proto2.TestAllTypes.prototype.getOptionalgroupOrDefault = function() {
return /** @type {!proto2.TestAllTypes.OptionalGroup} */ (this.get$ValueOrDefault(16));
};
/**
* Sets the value of the optionalgroup field.
* @param {!proto2.TestAllTypes.OptionalGroup} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalgroup = function(value) {
this.set$Value(16, value);
};
/**
* @return {boolean} Whether the optionalgroup field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalgroup = function() {
return this.has$Value(16);
};
/**
* @return {number} The number of values in the optionalgroup field.
*/
proto2.TestAllTypes.prototype.optionalgroupCount = function() {
return this.count$Values(16);
};
/**
* Clears the values in the optionalgroup field.
*/
proto2.TestAllTypes.prototype.clearOptionalgroup = function() {
this.clear$Field(16);
};
/**
* Gets the value of the optional_nested_message field.
* @return {proto2.TestAllTypes.NestedMessage} The value.
*/
proto2.TestAllTypes.prototype.getOptionalNestedMessage = function() {
return /** @type {proto2.TestAllTypes.NestedMessage} */ (this.get$Value(18));
};
/**
* Gets the value of the optional_nested_message field or the default value if not set.
* @return {!proto2.TestAllTypes.NestedMessage} The value.
*/
proto2.TestAllTypes.prototype.getOptionalNestedMessageOrDefault = function() {
return /** @type {!proto2.TestAllTypes.NestedMessage} */ (this.get$ValueOrDefault(18));
};
/**
* Sets the value of the optional_nested_message field.
* @param {!proto2.TestAllTypes.NestedMessage} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalNestedMessage = function(value) {
this.set$Value(18, value);
};
/**
* @return {boolean} Whether the optional_nested_message field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalNestedMessage = function() {
return this.has$Value(18);
};
/**
* @return {number} The number of values in the optional_nested_message field.
*/
proto2.TestAllTypes.prototype.optionalNestedMessageCount = function() {
return this.count$Values(18);
};
/**
* Clears the values in the optional_nested_message field.
*/
proto2.TestAllTypes.prototype.clearOptionalNestedMessage = function() {
this.clear$Field(18);
};
/**
* Gets the value of the optional_nested_enum field.
* @return {?proto2.TestAllTypes.NestedEnum} The value.
*/
proto2.TestAllTypes.prototype.getOptionalNestedEnum = function() {
return /** @type {?proto2.TestAllTypes.NestedEnum} */ (this.get$Value(21));
};
/**
* Gets the value of the optional_nested_enum field or the default value if not set.
* @return {proto2.TestAllTypes.NestedEnum} The value.
*/
proto2.TestAllTypes.prototype.getOptionalNestedEnumOrDefault = function() {
return /** @type {proto2.TestAllTypes.NestedEnum} */ (this.get$ValueOrDefault(21));
};
/**
* Sets the value of the optional_nested_enum field.
* @param {proto2.TestAllTypes.NestedEnum} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalNestedEnum = function(value) {
this.set$Value(21, value);
};
/**
* @return {boolean} Whether the optional_nested_enum field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalNestedEnum = function() {
return this.has$Value(21);
};
/**
* @return {number} The number of values in the optional_nested_enum field.
*/
proto2.TestAllTypes.prototype.optionalNestedEnumCount = function() {
return this.count$Values(21);
};
/**
* Clears the values in the optional_nested_enum field.
*/
proto2.TestAllTypes.prototype.clearOptionalNestedEnum = function() {
this.clear$Field(21);
};
/**
* Gets the value of the optional_int64_number field.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt64Number = function() {
return /** @type {?number} */ (this.get$Value(50));
};
/**
* Gets the value of the optional_int64_number field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt64NumberOrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(50));
};
/**
* Sets the value of the optional_int64_number field.
* @param {number} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalInt64Number = function(value) {
this.set$Value(50, value);
};
/**
* @return {boolean} Whether the optional_int64_number field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalInt64Number = function() {
return this.has$Value(50);
};
/**
* @return {number} The number of values in the optional_int64_number field.
*/
proto2.TestAllTypes.prototype.optionalInt64NumberCount = function() {
return this.count$Values(50);
};
/**
* Clears the values in the optional_int64_number field.
*/
proto2.TestAllTypes.prototype.clearOptionalInt64Number = function() {
this.clear$Field(50);
};
/**
* Gets the value of the optional_int64_string field.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt64String = function() {
return /** @type {?string} */ (this.get$Value(51));
};
/**
* Gets the value of the optional_int64_string field or the default value if not set.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getOptionalInt64StringOrDefault = function() {
return /** @type {string} */ (this.get$ValueOrDefault(51));
};
/**
* Sets the value of the optional_int64_string field.
* @param {string} value The value.
*/
proto2.TestAllTypes.prototype.setOptionalInt64String = function(value) {
this.set$Value(51, value);
};
/**
* @return {boolean} Whether the optional_int64_string field has a value.
*/
proto2.TestAllTypes.prototype.hasOptionalInt64String = function() {
return this.has$Value(51);
};
/**
* @return {number} The number of values in the optional_int64_string field.
*/
proto2.TestAllTypes.prototype.optionalInt64StringCount = function() {
return this.count$Values(51);
};
/**
* Clears the values in the optional_int64_string field.
*/
proto2.TestAllTypes.prototype.clearOptionalInt64String = function() {
this.clear$Field(51);
};
/**
* Gets the value of the repeated_int32 field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt32 = function(index) {
return /** @type {?number} */ (this.get$Value(31, index));
};
/**
* Gets the value of the repeated_int32 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt32OrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(31, index));
};
/**
* Adds a value to the repeated_int32 field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedInt32 = function(value) {
this.add$Value(31, value);
};
/**
* Returns the array of values in the repeated_int32 field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedInt32Array = function() {
return /** @type {!Array.<number>} */ (this.array$Values(31));
};
/**
* @return {boolean} Whether the repeated_int32 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedInt32 = function() {
return this.has$Value(31);
};
/**
* @return {number} The number of values in the repeated_int32 field.
*/
proto2.TestAllTypes.prototype.repeatedInt32Count = function() {
return this.count$Values(31);
};
/**
* Clears the values in the repeated_int32 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedInt32 = function() {
this.clear$Field(31);
};
/**
* Gets the value of the repeated_int64 field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt64 = function(index) {
return /** @type {?string} */ (this.get$Value(32, index));
};
/**
* Gets the value of the repeated_int64 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt64OrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(32, index));
};
/**
* Adds a value to the repeated_int64 field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedInt64 = function(value) {
this.add$Value(32, value);
};
/**
* Returns the array of values in the repeated_int64 field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedInt64Array = function() {
return /** @type {!Array.<string>} */ (this.array$Values(32));
};
/**
* @return {boolean} Whether the repeated_int64 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedInt64 = function() {
return this.has$Value(32);
};
/**
* @return {number} The number of values in the repeated_int64 field.
*/
proto2.TestAllTypes.prototype.repeatedInt64Count = function() {
return this.count$Values(32);
};
/**
* Clears the values in the repeated_int64 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedInt64 = function() {
this.clear$Field(32);
};
/**
* Gets the value of the repeated_uint32 field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedUint32 = function(index) {
return /** @type {?number} */ (this.get$Value(33, index));
};
/**
* Gets the value of the repeated_uint32 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedUint32OrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(33, index));
};
/**
* Adds a value to the repeated_uint32 field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedUint32 = function(value) {
this.add$Value(33, value);
};
/**
* Returns the array of values in the repeated_uint32 field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedUint32Array = function() {
return /** @type {!Array.<number>} */ (this.array$Values(33));
};
/**
* @return {boolean} Whether the repeated_uint32 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedUint32 = function() {
return this.has$Value(33);
};
/**
* @return {number} The number of values in the repeated_uint32 field.
*/
proto2.TestAllTypes.prototype.repeatedUint32Count = function() {
return this.count$Values(33);
};
/**
* Clears the values in the repeated_uint32 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedUint32 = function() {
this.clear$Field(33);
};
/**
* Gets the value of the repeated_uint64 field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedUint64 = function(index) {
return /** @type {?string} */ (this.get$Value(34, index));
};
/**
* Gets the value of the repeated_uint64 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedUint64OrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(34, index));
};
/**
* Adds a value to the repeated_uint64 field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedUint64 = function(value) {
this.add$Value(34, value);
};
/**
* Returns the array of values in the repeated_uint64 field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedUint64Array = function() {
return /** @type {!Array.<string>} */ (this.array$Values(34));
};
/**
* @return {boolean} Whether the repeated_uint64 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedUint64 = function() {
return this.has$Value(34);
};
/**
* @return {number} The number of values in the repeated_uint64 field.
*/
proto2.TestAllTypes.prototype.repeatedUint64Count = function() {
return this.count$Values(34);
};
/**
* Clears the values in the repeated_uint64 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedUint64 = function() {
this.clear$Field(34);
};
/**
* Gets the value of the repeated_sint32 field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSint32 = function(index) {
return /** @type {?number} */ (this.get$Value(35, index));
};
/**
* Gets the value of the repeated_sint32 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSint32OrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(35, index));
};
/**
* Adds a value to the repeated_sint32 field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedSint32 = function(value) {
this.add$Value(35, value);
};
/**
* Returns the array of values in the repeated_sint32 field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedSint32Array = function() {
return /** @type {!Array.<number>} */ (this.array$Values(35));
};
/**
* @return {boolean} Whether the repeated_sint32 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedSint32 = function() {
return this.has$Value(35);
};
/**
* @return {number} The number of values in the repeated_sint32 field.
*/
proto2.TestAllTypes.prototype.repeatedSint32Count = function() {
return this.count$Values(35);
};
/**
* Clears the values in the repeated_sint32 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedSint32 = function() {
this.clear$Field(35);
};
/**
* Gets the value of the repeated_sint64 field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSint64 = function(index) {
return /** @type {?string} */ (this.get$Value(36, index));
};
/**
* Gets the value of the repeated_sint64 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSint64OrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(36, index));
};
/**
* Adds a value to the repeated_sint64 field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedSint64 = function(value) {
this.add$Value(36, value);
};
/**
* Returns the array of values in the repeated_sint64 field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedSint64Array = function() {
return /** @type {!Array.<string>} */ (this.array$Values(36));
};
/**
* @return {boolean} Whether the repeated_sint64 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedSint64 = function() {
return this.has$Value(36);
};
/**
* @return {number} The number of values in the repeated_sint64 field.
*/
proto2.TestAllTypes.prototype.repeatedSint64Count = function() {
return this.count$Values(36);
};
/**
* Clears the values in the repeated_sint64 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedSint64 = function() {
this.clear$Field(36);
};
/**
* Gets the value of the repeated_fixed32 field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedFixed32 = function(index) {
return /** @type {?number} */ (this.get$Value(37, index));
};
/**
* Gets the value of the repeated_fixed32 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedFixed32OrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(37, index));
};
/**
* Adds a value to the repeated_fixed32 field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedFixed32 = function(value) {
this.add$Value(37, value);
};
/**
* Returns the array of values in the repeated_fixed32 field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedFixed32Array = function() {
return /** @type {!Array.<number>} */ (this.array$Values(37));
};
/**
* @return {boolean} Whether the repeated_fixed32 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedFixed32 = function() {
return this.has$Value(37);
};
/**
* @return {number} The number of values in the repeated_fixed32 field.
*/
proto2.TestAllTypes.prototype.repeatedFixed32Count = function() {
return this.count$Values(37);
};
/**
* Clears the values in the repeated_fixed32 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedFixed32 = function() {
this.clear$Field(37);
};
/**
* Gets the value of the repeated_fixed64 field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedFixed64 = function(index) {
return /** @type {?string} */ (this.get$Value(38, index));
};
/**
* Gets the value of the repeated_fixed64 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedFixed64OrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(38, index));
};
/**
* Adds a value to the repeated_fixed64 field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedFixed64 = function(value) {
this.add$Value(38, value);
};
/**
* Returns the array of values in the repeated_fixed64 field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedFixed64Array = function() {
return /** @type {!Array.<string>} */ (this.array$Values(38));
};
/**
* @return {boolean} Whether the repeated_fixed64 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedFixed64 = function() {
return this.has$Value(38);
};
/**
* @return {number} The number of values in the repeated_fixed64 field.
*/
proto2.TestAllTypes.prototype.repeatedFixed64Count = function() {
return this.count$Values(38);
};
/**
* Clears the values in the repeated_fixed64 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedFixed64 = function() {
this.clear$Field(38);
};
/**
* Gets the value of the repeated_sfixed32 field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSfixed32 = function(index) {
return /** @type {?number} */ (this.get$Value(39, index));
};
/**
* Gets the value of the repeated_sfixed32 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSfixed32OrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(39, index));
};
/**
* Adds a value to the repeated_sfixed32 field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedSfixed32 = function(value) {
this.add$Value(39, value);
};
/**
* Returns the array of values in the repeated_sfixed32 field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedSfixed32Array = function() {
return /** @type {!Array.<number>} */ (this.array$Values(39));
};
/**
* @return {boolean} Whether the repeated_sfixed32 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedSfixed32 = function() {
return this.has$Value(39);
};
/**
* @return {number} The number of values in the repeated_sfixed32 field.
*/
proto2.TestAllTypes.prototype.repeatedSfixed32Count = function() {
return this.count$Values(39);
};
/**
* Clears the values in the repeated_sfixed32 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedSfixed32 = function() {
this.clear$Field(39);
};
/**
* Gets the value of the repeated_sfixed64 field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSfixed64 = function(index) {
return /** @type {?string} */ (this.get$Value(40, index));
};
/**
* Gets the value of the repeated_sfixed64 field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedSfixed64OrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(40, index));
};
/**
* Adds a value to the repeated_sfixed64 field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedSfixed64 = function(value) {
this.add$Value(40, value);
};
/**
* Returns the array of values in the repeated_sfixed64 field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedSfixed64Array = function() {
return /** @type {!Array.<string>} */ (this.array$Values(40));
};
/**
* @return {boolean} Whether the repeated_sfixed64 field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedSfixed64 = function() {
return this.has$Value(40);
};
/**
* @return {number} The number of values in the repeated_sfixed64 field.
*/
proto2.TestAllTypes.prototype.repeatedSfixed64Count = function() {
return this.count$Values(40);
};
/**
* Clears the values in the repeated_sfixed64 field.
*/
proto2.TestAllTypes.prototype.clearRepeatedSfixed64 = function() {
this.clear$Field(40);
};
/**
* Gets the value of the repeated_float field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedFloat = function(index) {
return /** @type {?number} */ (this.get$Value(41, index));
};
/**
* Gets the value of the repeated_float field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedFloatOrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(41, index));
};
/**
* Adds a value to the repeated_float field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedFloat = function(value) {
this.add$Value(41, value);
};
/**
* Returns the array of values in the repeated_float field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedFloatArray = function() {
return /** @type {!Array.<number>} */ (this.array$Values(41));
};
/**
* @return {boolean} Whether the repeated_float field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedFloat = function() {
return this.has$Value(41);
};
/**
* @return {number} The number of values in the repeated_float field.
*/
proto2.TestAllTypes.prototype.repeatedFloatCount = function() {
return this.count$Values(41);
};
/**
* Clears the values in the repeated_float field.
*/
proto2.TestAllTypes.prototype.clearRepeatedFloat = function() {
this.clear$Field(41);
};
/**
* Gets the value of the repeated_double field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedDouble = function(index) {
return /** @type {?number} */ (this.get$Value(42, index));
};
/**
* Gets the value of the repeated_double field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedDoubleOrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(42, index));
};
/**
* Adds a value to the repeated_double field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedDouble = function(value) {
this.add$Value(42, value);
};
/**
* Returns the array of values in the repeated_double field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedDoubleArray = function() {
return /** @type {!Array.<number>} */ (this.array$Values(42));
};
/**
* @return {boolean} Whether the repeated_double field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedDouble = function() {
return this.has$Value(42);
};
/**
* @return {number} The number of values in the repeated_double field.
*/
proto2.TestAllTypes.prototype.repeatedDoubleCount = function() {
return this.count$Values(42);
};
/**
* Clears the values in the repeated_double field.
*/
proto2.TestAllTypes.prototype.clearRepeatedDouble = function() {
this.clear$Field(42);
};
/**
* Gets the value of the repeated_bool field at the index given.
* @param {number} index The index to lookup.
* @return {?boolean} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedBool = function(index) {
return /** @type {?boolean} */ (this.get$Value(43, index));
};
/**
* Gets the value of the repeated_bool field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {boolean} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedBoolOrDefault = function(index) {
return /** @type {boolean} */ (this.get$ValueOrDefault(43, index));
};
/**
* Adds a value to the repeated_bool field.
* @param {boolean} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedBool = function(value) {
this.add$Value(43, value);
};
/**
* Returns the array of values in the repeated_bool field.
* @return {!Array.<boolean>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedBoolArray = function() {
return /** @type {!Array.<boolean>} */ (this.array$Values(43));
};
/**
* @return {boolean} Whether the repeated_bool field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedBool = function() {
return this.has$Value(43);
};
/**
* @return {number} The number of values in the repeated_bool field.
*/
proto2.TestAllTypes.prototype.repeatedBoolCount = function() {
return this.count$Values(43);
};
/**
* Clears the values in the repeated_bool field.
*/
proto2.TestAllTypes.prototype.clearRepeatedBool = function() {
this.clear$Field(43);
};
/**
* Gets the value of the repeated_string field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedString = function(index) {
return /** @type {?string} */ (this.get$Value(44, index));
};
/**
* Gets the value of the repeated_string field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedStringOrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(44, index));
};
/**
* Adds a value to the repeated_string field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedString = function(value) {
this.add$Value(44, value);
};
/**
* Returns the array of values in the repeated_string field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedStringArray = function() {
return /** @type {!Array.<string>} */ (this.array$Values(44));
};
/**
* @return {boolean} Whether the repeated_string field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedString = function() {
return this.has$Value(44);
};
/**
* @return {number} The number of values in the repeated_string field.
*/
proto2.TestAllTypes.prototype.repeatedStringCount = function() {
return this.count$Values(44);
};
/**
* Clears the values in the repeated_string field.
*/
proto2.TestAllTypes.prototype.clearRepeatedString = function() {
this.clear$Field(44);
};
/**
* Gets the value of the repeated_bytes field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedBytes = function(index) {
return /** @type {?string} */ (this.get$Value(45, index));
};
/**
* Gets the value of the repeated_bytes field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedBytesOrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(45, index));
};
/**
* Adds a value to the repeated_bytes field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedBytes = function(value) {
this.add$Value(45, value);
};
/**
* Returns the array of values in the repeated_bytes field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedBytesArray = function() {
return /** @type {!Array.<string>} */ (this.array$Values(45));
};
/**
* @return {boolean} Whether the repeated_bytes field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedBytes = function() {
return this.has$Value(45);
};
/**
* @return {number} The number of values in the repeated_bytes field.
*/
proto2.TestAllTypes.prototype.repeatedBytesCount = function() {
return this.count$Values(45);
};
/**
* Clears the values in the repeated_bytes field.
*/
proto2.TestAllTypes.prototype.clearRepeatedBytes = function() {
this.clear$Field(45);
};
/**
* Gets the value of the repeatedgroup field at the index given.
* @param {number} index The index to lookup.
* @return {proto2.TestAllTypes.RepeatedGroup} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedgroup = function(index) {
return /** @type {proto2.TestAllTypes.RepeatedGroup} */ (this.get$Value(46, index));
};
/**
* Gets the value of the repeatedgroup field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {!proto2.TestAllTypes.RepeatedGroup} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedgroupOrDefault = function(index) {
return /** @type {!proto2.TestAllTypes.RepeatedGroup} */ (this.get$ValueOrDefault(46, index));
};
/**
* Adds a value to the repeatedgroup field.
* @param {!proto2.TestAllTypes.RepeatedGroup} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedgroup = function(value) {
this.add$Value(46, value);
};
/**
* Returns the array of values in the repeatedgroup field.
* @return {!Array.<!proto2.TestAllTypes.RepeatedGroup>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedgroupArray = function() {
return /** @type {!Array.<!proto2.TestAllTypes.RepeatedGroup>} */ (this.array$Values(46));
};
/**
* @return {boolean} Whether the repeatedgroup field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedgroup = function() {
return this.has$Value(46);
};
/**
* @return {number} The number of values in the repeatedgroup field.
*/
proto2.TestAllTypes.prototype.repeatedgroupCount = function() {
return this.count$Values(46);
};
/**
* Clears the values in the repeatedgroup field.
*/
proto2.TestAllTypes.prototype.clearRepeatedgroup = function() {
this.clear$Field(46);
};
/**
* Gets the value of the repeated_nested_message field at the index given.
* @param {number} index The index to lookup.
* @return {proto2.TestAllTypes.NestedMessage} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedNestedMessage = function(index) {
return /** @type {proto2.TestAllTypes.NestedMessage} */ (this.get$Value(48, index));
};
/**
* Gets the value of the repeated_nested_message field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {!proto2.TestAllTypes.NestedMessage} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedNestedMessageOrDefault = function(index) {
return /** @type {!proto2.TestAllTypes.NestedMessage} */ (this.get$ValueOrDefault(48, index));
};
/**
* Adds a value to the repeated_nested_message field.
* @param {!proto2.TestAllTypes.NestedMessage} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedNestedMessage = function(value) {
this.add$Value(48, value);
};
/**
* Returns the array of values in the repeated_nested_message field.
* @return {!Array.<!proto2.TestAllTypes.NestedMessage>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedNestedMessageArray = function() {
return /** @type {!Array.<!proto2.TestAllTypes.NestedMessage>} */ (this.array$Values(48));
};
/**
* @return {boolean} Whether the repeated_nested_message field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedNestedMessage = function() {
return this.has$Value(48);
};
/**
* @return {number} The number of values in the repeated_nested_message field.
*/
proto2.TestAllTypes.prototype.repeatedNestedMessageCount = function() {
return this.count$Values(48);
};
/**
* Clears the values in the repeated_nested_message field.
*/
proto2.TestAllTypes.prototype.clearRepeatedNestedMessage = function() {
this.clear$Field(48);
};
/**
* Gets the value of the repeated_nested_enum field at the index given.
* @param {number} index The index to lookup.
* @return {?proto2.TestAllTypes.NestedEnum} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedNestedEnum = function(index) {
return /** @type {?proto2.TestAllTypes.NestedEnum} */ (this.get$Value(49, index));
};
/**
* Gets the value of the repeated_nested_enum field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {proto2.TestAllTypes.NestedEnum} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedNestedEnumOrDefault = function(index) {
return /** @type {proto2.TestAllTypes.NestedEnum} */ (this.get$ValueOrDefault(49, index));
};
/**
* Adds a value to the repeated_nested_enum field.
* @param {proto2.TestAllTypes.NestedEnum} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedNestedEnum = function(value) {
this.add$Value(49, value);
};
/**
* Returns the array of values in the repeated_nested_enum field.
* @return {!Array.<proto2.TestAllTypes.NestedEnum>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedNestedEnumArray = function() {
return /** @type {!Array.<proto2.TestAllTypes.NestedEnum>} */ (this.array$Values(49));
};
/**
* @return {boolean} Whether the repeated_nested_enum field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedNestedEnum = function() {
return this.has$Value(49);
};
/**
* @return {number} The number of values in the repeated_nested_enum field.
*/
proto2.TestAllTypes.prototype.repeatedNestedEnumCount = function() {
return this.count$Values(49);
};
/**
* Clears the values in the repeated_nested_enum field.
*/
proto2.TestAllTypes.prototype.clearRepeatedNestedEnum = function() {
this.clear$Field(49);
};
/**
* Gets the value of the repeated_int64_number field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt64Number = function(index) {
return /** @type {?number} */ (this.get$Value(52, index));
};
/**
* Gets the value of the repeated_int64_number field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt64NumberOrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(52, index));
};
/**
* Adds a value to the repeated_int64_number field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedInt64Number = function(value) {
this.add$Value(52, value);
};
/**
* Returns the array of values in the repeated_int64_number field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedInt64NumberArray = function() {
return /** @type {!Array.<number>} */ (this.array$Values(52));
};
/**
* @return {boolean} Whether the repeated_int64_number field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedInt64Number = function() {
return this.has$Value(52);
};
/**
* @return {number} The number of values in the repeated_int64_number field.
*/
proto2.TestAllTypes.prototype.repeatedInt64NumberCount = function() {
return this.count$Values(52);
};
/**
* Clears the values in the repeated_int64_number field.
*/
proto2.TestAllTypes.prototype.clearRepeatedInt64Number = function() {
this.clear$Field(52);
};
/**
* Gets the value of the repeated_int64_string field at the index given.
* @param {number} index The index to lookup.
* @return {?string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt64String = function(index) {
return /** @type {?string} */ (this.get$Value(53, index));
};
/**
* Gets the value of the repeated_int64_string field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {string} The value.
*/
proto2.TestAllTypes.prototype.getRepeatedInt64StringOrDefault = function(index) {
return /** @type {string} */ (this.get$ValueOrDefault(53, index));
};
/**
* Adds a value to the repeated_int64_string field.
* @param {string} value The value to add.
*/
proto2.TestAllTypes.prototype.addRepeatedInt64String = function(value) {
this.add$Value(53, value);
};
/**
* Returns the array of values in the repeated_int64_string field.
* @return {!Array.<string>} The values in the field.
*/
proto2.TestAllTypes.prototype.repeatedInt64StringArray = function() {
return /** @type {!Array.<string>} */ (this.array$Values(53));
};
/**
* @return {boolean} Whether the repeated_int64_string field has a value.
*/
proto2.TestAllTypes.prototype.hasRepeatedInt64String = function() {
return this.has$Value(53);
};
/**
* @return {number} The number of values in the repeated_int64_string field.
*/
proto2.TestAllTypes.prototype.repeatedInt64StringCount = function() {
return this.count$Values(53);
};
/**
* Clears the values in the repeated_int64_string field.
*/
proto2.TestAllTypes.prototype.clearRepeatedInt64String = function() {
this.clear$Field(53);
};
/**
* Enumeration NestedEnum.
* @enum {number}
*/
proto2.TestAllTypes.NestedEnum = {
FOO: 0,
BAR: 2,
BAZ: 3
};
/**
* Message NestedMessage.
* @constructor
* @extends {goog.proto2.Message}
*/
proto2.TestAllTypes.NestedMessage = function() {
goog.proto2.Message.apply(this);
};
goog.inherits(proto2.TestAllTypes.NestedMessage, goog.proto2.Message);
/**
* Overrides {@link goog.proto2.Message#clone} to specify its exact return type.
* @return {!proto2.TestAllTypes.NestedMessage} The cloned message.
* @override
*/
proto2.TestAllTypes.NestedMessage.prototype.clone;
/**
* Gets the value of the b field.
* @return {?number} The value.
*/
proto2.TestAllTypes.NestedMessage.prototype.getB = function() {
return /** @type {?number} */ (this.get$Value(1));
};
/**
* Gets the value of the b field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.NestedMessage.prototype.getBOrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(1));
};
/**
* Sets the value of the b field.
* @param {number} value The value.
*/
proto2.TestAllTypes.NestedMessage.prototype.setB = function(value) {
this.set$Value(1, value);
};
/**
* @return {boolean} Whether the b field has a value.
*/
proto2.TestAllTypes.NestedMessage.prototype.hasB = function() {
return this.has$Value(1);
};
/**
* @return {number} The number of values in the b field.
*/
proto2.TestAllTypes.NestedMessage.prototype.bCount = function() {
return this.count$Values(1);
};
/**
* Clears the values in the b field.
*/
proto2.TestAllTypes.NestedMessage.prototype.clearB = function() {
this.clear$Field(1);
};
/**
* Gets the value of the c field.
* @return {?number} The value.
*/
proto2.TestAllTypes.NestedMessage.prototype.getC = function() {
return /** @type {?number} */ (this.get$Value(2));
};
/**
* Gets the value of the c field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.NestedMessage.prototype.getCOrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(2));
};
/**
* Sets the value of the c field.
* @param {number} value The value.
*/
proto2.TestAllTypes.NestedMessage.prototype.setC = function(value) {
this.set$Value(2, value);
};
/**
* @return {boolean} Whether the c field has a value.
*/
proto2.TestAllTypes.NestedMessage.prototype.hasC = function() {
return this.has$Value(2);
};
/**
* @return {number} The number of values in the c field.
*/
proto2.TestAllTypes.NestedMessage.prototype.cCount = function() {
return this.count$Values(2);
};
/**
* Clears the values in the c field.
*/
proto2.TestAllTypes.NestedMessage.prototype.clearC = function() {
this.clear$Field(2);
};
/**
* Message OptionalGroup.
* @constructor
* @extends {goog.proto2.Message}
*/
proto2.TestAllTypes.OptionalGroup = function() {
goog.proto2.Message.apply(this);
};
goog.inherits(proto2.TestAllTypes.OptionalGroup, goog.proto2.Message);
/**
* Overrides {@link goog.proto2.Message#clone} to specify its exact return type.
* @return {!proto2.TestAllTypes.OptionalGroup} The cloned message.
* @override
*/
proto2.TestAllTypes.OptionalGroup.prototype.clone;
/**
* Gets the value of the a field.
* @return {?number} The value.
*/
proto2.TestAllTypes.OptionalGroup.prototype.getA = function() {
return /** @type {?number} */ (this.get$Value(17));
};
/**
* Gets the value of the a field or the default value if not set.
* @return {number} The value.
*/
proto2.TestAllTypes.OptionalGroup.prototype.getAOrDefault = function() {
return /** @type {number} */ (this.get$ValueOrDefault(17));
};
/**
* Sets the value of the a field.
* @param {number} value The value.
*/
proto2.TestAllTypes.OptionalGroup.prototype.setA = function(value) {
this.set$Value(17, value);
};
/**
* @return {boolean} Whether the a field has a value.
*/
proto2.TestAllTypes.OptionalGroup.prototype.hasA = function() {
return this.has$Value(17);
};
/**
* @return {number} The number of values in the a field.
*/
proto2.TestAllTypes.OptionalGroup.prototype.aCount = function() {
return this.count$Values(17);
};
/**
* Clears the values in the a field.
*/
proto2.TestAllTypes.OptionalGroup.prototype.clearA = function() {
this.clear$Field(17);
};
/**
* Message RepeatedGroup.
* @constructor
* @extends {goog.proto2.Message}
*/
proto2.TestAllTypes.RepeatedGroup = function() {
goog.proto2.Message.apply(this);
};
goog.inherits(proto2.TestAllTypes.RepeatedGroup, goog.proto2.Message);
/**
* Overrides {@link goog.proto2.Message#clone} to specify its exact return type.
* @return {!proto2.TestAllTypes.RepeatedGroup} The cloned message.
* @override
*/
proto2.TestAllTypes.RepeatedGroup.prototype.clone;
/**
* Gets the value of the a field at the index given.
* @param {number} index The index to lookup.
* @return {?number} The value.
*/
proto2.TestAllTypes.RepeatedGroup.prototype.getA = function(index) {
return /** @type {?number} */ (this.get$Value(47, index));
};
/**
* Gets the value of the a field at the index given or the default value if not set.
* @param {number} index The index to lookup.
* @return {number} The value.
*/
proto2.TestAllTypes.RepeatedGroup.prototype.getAOrDefault = function(index) {
return /** @type {number} */ (this.get$ValueOrDefault(47, index));
};
/**
* Adds a value to the a field.
* @param {number} value The value to add.
*/
proto2.TestAllTypes.RepeatedGroup.prototype.addA = function(value) {
this.add$Value(47, value);
};
/**
* Returns the array of values in the a field.
* @return {!Array.<number>} The values in the field.
*/
proto2.TestAllTypes.RepeatedGroup.prototype.aArray = function() {
return /** @type {!Array.<number>} */ (this.array$Values(47));
};
/**
* @return {boolean} Whether the a field has a value.
*/
proto2.TestAllTypes.RepeatedGroup.prototype.hasA = function() {
return this.has$Value(47);
};
/**
* @return {number} The number of values in the a field.
*/
proto2.TestAllTypes.RepeatedGroup.prototype.aCount = function() {
return this.count$Values(47);
};
/**
* Clears the values in the a field.
*/
proto2.TestAllTypes.RepeatedGroup.prototype.clearA = function() {
this.clear$Field(47);
};
goog.proto2.Message.set$Metadata(proto2.TestAllTypes, {
0: {
name: 'TestAllTypes',
fullName: 'TestAllTypes'
},
1: {
name: 'optional_int32',
fieldType: goog.proto2.Message.FieldType.INT32,
type: Number
},
2: {
name: 'optional_int64',
fieldType: goog.proto2.Message.FieldType.INT64,
defaultValue: '1',
type: String
},
3: {
name: 'optional_uint32',
fieldType: goog.proto2.Message.FieldType.UINT32,
type: Number
},
4: {
name: 'optional_uint64',
fieldType: goog.proto2.Message.FieldType.UINT64,
type: String
},
5: {
name: 'optional_sint32',
fieldType: goog.proto2.Message.FieldType.SINT32,
type: Number
},
6: {
name: 'optional_sint64',
fieldType: goog.proto2.Message.FieldType.SINT64,
type: String
},
7: {
name: 'optional_fixed32',
fieldType: goog.proto2.Message.FieldType.FIXED32,
type: Number
},
8: {
name: 'optional_fixed64',
fieldType: goog.proto2.Message.FieldType.FIXED64,
type: String
},
9: {
name: 'optional_sfixed32',
fieldType: goog.proto2.Message.FieldType.SFIXED32,
type: Number
},
10: {
name: 'optional_sfixed64',
fieldType: goog.proto2.Message.FieldType.SFIXED64,
type: String
},
11: {
name: 'optional_float',
fieldType: goog.proto2.Message.FieldType.FLOAT,
defaultValue: 1.5,
type: Number
},
12: {
name: 'optional_double',
fieldType: goog.proto2.Message.FieldType.DOUBLE,
type: Number
},
13: {
name: 'optional_bool',
fieldType: goog.proto2.Message.FieldType.BOOL,
type: Boolean
},
14: {
name: 'optional_string',
fieldType: goog.proto2.Message.FieldType.STRING,
type: String
},
15: {
name: 'optional_bytes',
fieldType: goog.proto2.Message.FieldType.BYTES,
defaultValue: 'moo',
type: String
},
16: {
name: 'optionalgroup',
fieldType: goog.proto2.Message.FieldType.GROUP,
type: proto2.TestAllTypes.OptionalGroup
},
18: {
name: 'optional_nested_message',
fieldType: goog.proto2.Message.FieldType.MESSAGE,
type: proto2.TestAllTypes.NestedMessage
},
21: {
name: 'optional_nested_enum',
fieldType: goog.proto2.Message.FieldType.ENUM,
defaultValue: proto2.TestAllTypes.NestedEnum.FOO,
type: proto2.TestAllTypes.NestedEnum
},
50: {
name: 'optional_int64_number',
fieldType: goog.proto2.Message.FieldType.INT64,
defaultValue: 1000000000000000001,
type: Number
},
51: {
name: 'optional_int64_string',
fieldType: goog.proto2.Message.FieldType.INT64,
defaultValue: '1000000000000000001',
type: String
},
31: {
name: 'repeated_int32',
repeated: true,
fieldType: goog.proto2.Message.FieldType.INT32,
type: Number
},
32: {
name: 'repeated_int64',
repeated: true,
fieldType: goog.proto2.Message.FieldType.INT64,
type: String
},
33: {
name: 'repeated_uint32',
repeated: true,
fieldType: goog.proto2.Message.FieldType.UINT32,
type: Number
},
34: {
name: 'repeated_uint64',
repeated: true,
fieldType: goog.proto2.Message.FieldType.UINT64,
type: String
},
35: {
name: 'repeated_sint32',
repeated: true,
fieldType: goog.proto2.Message.FieldType.SINT32,
type: Number
},
36: {
name: 'repeated_sint64',
repeated: true,
fieldType: goog.proto2.Message.FieldType.SINT64,
type: String
},
37: {
name: 'repeated_fixed32',
repeated: true,
fieldType: goog.proto2.Message.FieldType.FIXED32,
type: Number
},
38: {
name: 'repeated_fixed64',
repeated: true,
fieldType: goog.proto2.Message.FieldType.FIXED64,
type: String
},
39: {
name: 'repeated_sfixed32',
repeated: true,
fieldType: goog.proto2.Message.FieldType.SFIXED32,
type: Number
},
40: {
name: 'repeated_sfixed64',
repeated: true,
fieldType: goog.proto2.Message.FieldType.SFIXED64,
type: String
},
41: {
name: 'repeated_float',
repeated: true,
fieldType: goog.proto2.Message.FieldType.FLOAT,
type: Number
},
42: {
name: 'repeated_double',
repeated: true,
fieldType: goog.proto2.Message.FieldType.DOUBLE,
type: Number
},
43: {
name: 'repeated_bool',
repeated: true,
fieldType: goog.proto2.Message.FieldType.BOOL,
type: Boolean
},
44: {
name: 'repeated_string',
repeated: true,
fieldType: goog.proto2.Message.FieldType.STRING,
type: String
},
45: {
name: 'repeated_bytes',
repeated: true,
fieldType: goog.proto2.Message.FieldType.BYTES,
type: String
},
46: {
name: 'repeatedgroup',
repeated: true,
fieldType: goog.proto2.Message.FieldType.GROUP,
type: proto2.TestAllTypes.RepeatedGroup
},
48: {
name: 'repeated_nested_message',
repeated: true,
fieldType: goog.proto2.Message.FieldType.MESSAGE,
type: proto2.TestAllTypes.NestedMessage
},
49: {
name: 'repeated_nested_enum',
repeated: true,
fieldType: goog.proto2.Message.FieldType.ENUM,
defaultValue: proto2.TestAllTypes.NestedEnum.FOO,
type: proto2.TestAllTypes.NestedEnum
},
52: {
name: 'repeated_int64_number',
repeated: true,
fieldType: goog.proto2.Message.FieldType.INT64,
type: Number
},
53: {
name: 'repeated_int64_string',
repeated: true,
fieldType: goog.proto2.Message.FieldType.INT64,
type: String
}
});
goog.proto2.Message.set$Metadata(proto2.TestAllTypes.NestedMessage, {
0: {
name: 'NestedMessage',
containingType: proto2.TestAllTypes,
fullName: 'TestAllTypes.NestedMessage'
},
1: {
name: 'b',
fieldType: goog.proto2.Message.FieldType.INT32,
type: Number
},
2: {
name: 'c',
fieldType: goog.proto2.Message.FieldType.INT32,
type: Number
}
});
goog.proto2.Message.set$Metadata(proto2.TestAllTypes.OptionalGroup, {
0: {
name: 'OptionalGroup',
containingType: proto2.TestAllTypes,
fullName: 'TestAllTypes.OptionalGroup'
},
17: {
name: 'a',
fieldType: goog.proto2.Message.FieldType.INT32,
type: Number
}
});
goog.proto2.Message.set$Metadata(proto2.TestAllTypes.RepeatedGroup, {
0: {
name: 'RepeatedGroup',
containingType: proto2.TestAllTypes,
fullName: 'TestAllTypes.RepeatedGroup'
},
47: {
name: 'a',
repeated: true,
fieldType: goog.proto2.Message.FieldType.INT32,
type: Number
}
});
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for goog.proto2.TextFormatSerializer.
*
*/
/** @suppress {extraProvide} */
goog.provide('goog.proto2.TextFormatSerializerTest');
goog.require('goog.proto2.TextFormatSerializer');
goog.require('goog.testing.jsunit');
goog.require('proto2.TestAllTypes');
goog.setTestOnly('goog.proto2.TextFormatSerializerTest');
function testSerialization() {
var message = new proto2.TestAllTypes();
// Set the fields.
// Singular.
message.setOptionalInt32(101);
message.setOptionalUint32(103);
message.setOptionalSint32(105);
message.setOptionalFixed32(107);
message.setOptionalSfixed32(109);
message.setOptionalInt64('102');
message.setOptionalFloat(111.5);
message.setOptionalDouble(112.5);
message.setOptionalBool(true);
message.setOptionalString('test');
message.setOptionalBytes('abcd');
var group = new proto2.TestAllTypes.OptionalGroup();
group.setA(111);
message.setOptionalgroup(group);
var nestedMessage = new proto2.TestAllTypes.NestedMessage();
nestedMessage.setB(112);
message.setOptionalNestedMessage(nestedMessage);
message.setOptionalNestedEnum(proto2.TestAllTypes.NestedEnum.FOO);
// Repeated.
message.addRepeatedInt32(201);
message.addRepeatedInt32(202);
// Serialize to a simplified text format.
var simplified = new goog.proto2.TextFormatSerializer().serialize(message);
var expected = 'optional_int32: 101\n' +
'optional_int64: 102\n' +
'optional_uint32: 103\n' +
'optional_sint32: 105\n' +
'optional_fixed32: 107\n' +
'optional_sfixed32: 109\n' +
'optional_float: 111.5\n' +
'optional_double: 112.5\n' +
'optional_bool: true\n' +
'optional_string: "test"\n' +
'optional_bytes: "abcd"\n' +
'optionalgroup {\n' +
' a: 111\n' +
'}\n' +
'optional_nested_message {\n' +
' b: 112\n' +
'}\n' +
'optional_nested_enum: FOO\n' +
'repeated_int32: 201\n' +
'repeated_int32: 202\n';
assertEquals(expected, simplified);
}
function testSerializationOfUnknown() {
var nestedUnknown = new proto2.TestAllTypes();
var message = new proto2.TestAllTypes();
// Set the fields.
// Known.
message.setOptionalInt32(101);
message.addRepeatedInt32(201);
message.addRepeatedInt32(202);
nestedUnknown.addRepeatedInt32(301);
nestedUnknown.addRepeatedInt32(302);
// Unknown.
message.setUnknown(1000, 301);
message.setUnknown(1001, 302);
message.setUnknown(1002, 'hello world');
message.setUnknown(1002, nestedUnknown);
nestedUnknown.setUnknown(2000, 401);
// Serialize.
var simplified = new goog.proto2.TextFormatSerializer().serialize(message);
var expected = 'optional_int32: 101\n' +
'repeated_int32: 201\n' +
'repeated_int32: 202\n' +
'1000: 301\n' +
'1001: 302\n' +
'1002 {\n' +
' repeated_int32: 301\n' +
' repeated_int32: 302\n' +
' 2000: 401\n' +
'}';
assertEquals(expected, simplified);
}
/**
* Asserts that the given string value parses into the given set of tokens.
* @param {string} value The string value to parse.
* @param {Array.<Object> | Object} tokens The tokens to check against. If not
* an array, a single token is expected.
* @param {boolean=} opt_ignoreWhitespace Whether whitespace tokens should be
* skipped by the tokenizer.
*/
function assertTokens(value, tokens, opt_ignoreWhitespace) {
var tokenizer = new goog.proto2.TextFormatSerializer.Tokenizer_(
value, opt_ignoreWhitespace);
var tokensFound = [];
while (tokenizer.next()) {
tokensFound.push(tokenizer.getCurrent());
}
if (goog.typeOf(tokens) != 'array') {
tokens = [tokens];
}
assertEquals(tokens.length, tokensFound.length);
for (var i = 0; i < tokens.length; ++i) {
assertToken(tokens[i], tokensFound[i]);
}
}
function assertToken(expected, found) {
assertEquals(expected.type, found.type);
if (expected.value) {
assertEquals(expected.value, found.value);
}
}
function testTokenizer() {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
assertTokens('{ 123 }', [
{ type: types.OPEN_BRACE },
{ type: types.WHITESPACE, value: ' ' },
{ type: types.NUMBER, value: '123' },
{ type: types.WHITESPACE, value: ' '},
{ type: types.CLOSE_BRACE }
]);
}
function testTokenizerNoWhitespace() {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
assertTokens('{ "hello world" }', [
{ type: types.OPEN_BRACE },
{ type: types.STRING, value: '"hello world"' },
{ type: types.CLOSE_BRACE }
], true);
}
function assertIdentifier(identifier) {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
assertTokens(identifier, { type: types.IDENTIFIER, value: identifier });
}
function assertComment(comment) {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
assertTokens(comment, { type: types.COMMENT, value: comment });
}
function assertString(str) {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
assertTokens(str, { type: types.STRING, value: str });
}
function assertNumber(num) {
num = num.toString();
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
assertTokens(num, { type: types.NUMBER, value: num });
}
function testTokenizerSingleTokens() {
var types = goog.proto2.TextFormatSerializer.Tokenizer_.TokenTypes;
assertTokens('{', { type: types.OPEN_BRACE });
assertTokens('}', { type: types.CLOSE_BRACE });
assertTokens('<', { type: types.OPEN_TAG });
assertTokens('>', { type: types.CLOSE_TAG });
assertTokens(':', { type: types.COLON });
assertTokens(',', { type: types.COMMA });
assertTokens(';', { type: types.SEMI });
assertIdentifier('abcd');
assertIdentifier('Abcd');
assertIdentifier('ABcd');
assertIdentifier('ABcD');
assertIdentifier('a123nc');
assertIdentifier('a45_bC');
assertIdentifier('A45_bC');
assertIdentifier('inf');
assertIdentifier('infinity');
assertIdentifier('nan');
assertNumber(0);
assertNumber(10);
assertNumber(123);
assertNumber(1234);
assertNumber(123.56);
assertNumber(-124);
assertNumber(-1234);
assertNumber(-123.56);
assertNumber('123f');
assertNumber('123.6f');
assertNumber('-123f');
assertNumber('-123.8f');
assertNumber('0x1234');
assertNumber('0x12ac34');
assertNumber('0x49e281db686fb');
assertString('""');
assertString('"hello world"');
assertString('"hello # world"');
assertString('"hello #\\" world"');
assertString('"|"');
assertString('"\\"\\""');
assertString('"\\"foo\\""');
assertString('"\\"foo\\" and \\"bar\\""');
assertString('"foo \\"and\\" bar"');
assertComment('# foo bar baz');
assertComment('# foo ## bar baz');
assertComment('# foo "bar" baz');
}
function testSerializationOfStringWithQuotes() {
var nestedUnknown = new proto2.TestAllTypes();
var message = new proto2.TestAllTypes();
message.setOptionalString('hello "world"');
// Serialize.
var simplified = new goog.proto2.TextFormatSerializer().serialize(message);
var expected = 'optional_string: "hello \\"world\\""\n';
assertEquals(expected, simplified);
}
function testDeserialization() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'repeated_int32: 201\n' +
'repeated_int32: 202\n' +
'optional_float: 123.4';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(101, message.getOptionalInt32());
assertEquals(201, message.getRepeatedInt32(0));
assertEquals(202, message.getRepeatedInt32(1));
assertEquals(123.4, message.getOptionalFloat());
}
function testDeserializationOfList() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'repeated_int32: [201, 202]\n' +
'optional_float: 123.4';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(101, message.getOptionalInt32());
assertEquals(201, message.getRepeatedInt32(0));
assertEquals(123.4, message.getOptionalFloat());
}
function testDeserializationOfIntegerAsHexadecimalString() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 0x1\n' +
'optional_sint32: 0xf\n' +
'optional_uint32: 0xffffffff\n' +
'repeated_int32: [0x0, 0xff]\n';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(1, message.getOptionalInt32());
assertEquals(15, message.getOptionalSint32());
assertEquals(4294967295, message.getOptionalUint32());
assertEquals(0, message.getRepeatedInt32(0));
assertEquals(255, message.getRepeatedInt32(1));
}
function testDeserializationOfInt64AsHexadecimalString() {
var message = new proto2.TestAllTypes();
var value = 'optional_int64: 0xf';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals('0xf', message.getOptionalInt64());
}
function testDeserializationOfZeroFalseAndEmptyString() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 0\n' +
'optional_bool: false\n' +
'optional_string: ""';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(0, message.getOptionalInt32());
assertEquals(false, message.getOptionalBool());
assertEquals('', message.getOptionalString());
}
function testDeserializationSkipUnknown() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'repeated_int32: 201\n' +
'some_unknown: true\n' +
'repeated_int32: 202\n' +
'optional_float: 123.4';
var parser = new goog.proto2.TextFormatSerializer.Parser();
assertTrue(parser.parse(message, value, true));
assertEquals(101, message.getOptionalInt32());
assertEquals(201, message.getRepeatedInt32(0));
assertEquals(202, message.getRepeatedInt32(1));
assertEquals(123.4, message.getOptionalFloat());
}
function testDeserializationSkipUnknownList() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'repeated_int32: 201\n' +
'some_unknown: [true, 1, 201, "hello"]\n' +
'repeated_int32: 202\n' +
'optional_float: 123.4';
var parser = new goog.proto2.TextFormatSerializer.Parser();
assertTrue(parser.parse(message, value, true));
assertEquals(101, message.getOptionalInt32());
assertEquals(201, message.getRepeatedInt32(0));
assertEquals(202, message.getRepeatedInt32(1));
assertEquals(123.4, message.getOptionalFloat());
}
function testDeserializationSkipUnknownNested() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'repeated_int32: 201\n' +
'some_unknown: <\n' +
' a: 1\n' +
' b: 2\n' +
'>\n' +
'repeated_int32: 202\n' +
'optional_float: 123.4';
var parser = new goog.proto2.TextFormatSerializer.Parser();
assertTrue(parser.parse(message, value, true));
assertEquals(101, message.getOptionalInt32());
assertEquals(201, message.getRepeatedInt32(0));
assertEquals(202, message.getRepeatedInt32(1));
assertEquals(123.4, message.getOptionalFloat());
}
function testDeserializationSkipUnknownNestedInvalid() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'repeated_int32: 201\n' +
'some_unknown: <\n' +
' a: \n' + // Missing value.
' b: 2\n' +
'>\n' +
'repeated_int32: 202\n' +
'optional_float: 123.4';
var parser = new goog.proto2.TextFormatSerializer.Parser();
assertFalse(parser.parse(message, value, true));
}
function testDeserializationSkipUnknownNestedInvalid2() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'repeated_int32: 201\n' +
'some_unknown: <\n' +
' a: 2\n' +
' b: 2\n' +
'}\n' + // Delimiter mismatch
'repeated_int32: 202\n' +
'optional_float: 123.4';
var parser = new goog.proto2.TextFormatSerializer.Parser();
assertFalse(parser.parse(message, value, true));
}
function testDeserializationLegacyFormat() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101,\n' +
'repeated_int32: 201,\n' +
'repeated_int32: 202;\n' +
'optional_float: 123.4';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(101, message.getOptionalInt32());
assertEquals(201, message.getRepeatedInt32(0));
assertEquals(202, message.getRepeatedInt32(1));
assertEquals(123.4, message.getOptionalFloat());
}
function testDeserializationVariedNumbers() {
var message = new proto2.TestAllTypes();
var value = (
'repeated_int32: 23\n' +
'repeated_int32: -3\n' +
'repeated_int32: 0xdeadbeef\n' +
'repeated_float: 123.0\n' +
'repeated_float: -3.27\n' +
'repeated_float: -35.5f\n'
);
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(23, message.getRepeatedInt32(0));
assertEquals(-3, message.getRepeatedInt32(1));
assertEquals(3735928559, message.getRepeatedInt32(2));
assertEquals(123.0, message.getRepeatedFloat(0));
assertEquals(-3.27, message.getRepeatedFloat(1));
assertEquals(-35.5, message.getRepeatedFloat(2));
}
function testParseNumericalConstant() {
var parseNumericalConstant =
goog.proto2.TextFormatSerializer.Parser.parseNumericalConstant_;
assertEquals(Infinity, parseNumericalConstant('inf'));
assertEquals(Infinity, parseNumericalConstant('inff'));
assertEquals(Infinity, parseNumericalConstant('infinity'));
assertEquals(Infinity, parseNumericalConstant('infinityf'));
assertEquals(Infinity, parseNumericalConstant('Infinityf'));
assertEquals(-Infinity, parseNumericalConstant('-inf'));
assertEquals(-Infinity, parseNumericalConstant('-inff'));
assertEquals(-Infinity, parseNumericalConstant('-infinity'));
assertEquals(-Infinity, parseNumericalConstant('-infinityf'));
assertEquals(-Infinity, parseNumericalConstant('-Infinity'));
assertNull(parseNumericalConstant('-infin'));
assertNull(parseNumericalConstant('infin'));
assertNull(parseNumericalConstant('-infinite'));
assertNull(parseNumericalConstant('-infin'));
assertNull(parseNumericalConstant('infin'));
assertNull(parseNumericalConstant('-infinite'));
assertTrue(isNaN(parseNumericalConstant('Nan')));
assertTrue(isNaN(parseNumericalConstant('NaN')));
assertTrue(isNaN(parseNumericalConstant('NAN')));
assertTrue(isNaN(parseNumericalConstant('nan')));
assertTrue(isNaN(parseNumericalConstant('nanf')));
assertTrue(isNaN(parseNumericalConstant('NaNf')));
assertEquals(Number.POSITIVE_INFINITY, parseNumericalConstant('infinity'));
assertEquals(Number.NEGATIVE_INFINITY, parseNumericalConstant('-inf'));
assertEquals(Number.NEGATIVE_INFINITY, parseNumericalConstant('-infinity'));
assertNull(parseNumericalConstant('na'));
assertNull(parseNumericalConstant('-nan'));
assertNull(parseNumericalConstant('none'));
}
function testDeserializationOfNumericalConstants() {
var message = new proto2.TestAllTypes();
var value = (
'repeated_float: inf\n' +
'repeated_float: -inf\n' +
'repeated_float: nan\n' +
'repeated_float: 300.2\n'
);
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(Infinity, message.getRepeatedFloat(0));
assertEquals(-Infinity, message.getRepeatedFloat(1));
assertTrue(isNaN(message.getRepeatedFloat(2)));
assertEquals(300.2, message.getRepeatedFloat(3));
}
function testGetNumberFromString() {
var getNumberFromString =
goog.proto2.TextFormatSerializer.Parser.getNumberFromString_;
assertEquals(3735928559, getNumberFromString('0xdeadbeef'));
assertEquals(4276215469, getNumberFromString('0xFEE1DEAD'));
assertEquals(123.1, getNumberFromString('123.1'));
assertEquals(123.0, getNumberFromString('123.0'));
assertEquals(-29.3, getNumberFromString('-29.3f'));
assertEquals(23, getNumberFromString('23'));
assertEquals(-3, getNumberFromString('-3'));
assertEquals(-3.27, getNumberFromString('-3.27'));
assertThrows(goog.partial(getNumberFromString, 'cat'));
assertThrows(goog.partial(getNumberFromString, 'NaN'));
assertThrows(goog.partial(getNumberFromString, 'inf'));
}
function testDeserializationError() {
var message = new proto2.TestAllTypes();
var value = 'optional_int33: 101\n';
var result =
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(result, 'Unknown field: optional_int33');
}
function testNestedDeserialization() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'optional_nested_message: {\n' +
' b: 301\n' +
'}';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(101, message.getOptionalInt32());
assertEquals(301, message.getOptionalNestedMessage().getB());
}
function testNestedDeserializationLegacyFormat() {
var message = new proto2.TestAllTypes();
var value = 'optional_int32: 101\n' +
'optional_nested_message: <\n' +
' b: 301\n' +
'>';
new goog.proto2.TextFormatSerializer().deserializeTo(message, value);
assertEquals(101, message.getOptionalInt32());
assertEquals(301, message.getOptionalNestedMessage().getB());
}
function testBidirectional() {
var message = new proto2.TestAllTypes();
// Set the fields.
// Singular.
message.setOptionalInt32(101);
message.setOptionalInt64('102');
message.setOptionalUint32(103);
message.setOptionalUint64('104');
message.setOptionalSint32(105);
message.setOptionalSint64('106');
message.setOptionalFixed32(107);
message.setOptionalFixed64('108');
message.setOptionalSfixed32(109);
message.setOptionalSfixed64('110');
message.setOptionalFloat(111.5);
message.setOptionalDouble(112.5);
message.setOptionalBool(true);
message.setOptionalString('test');
message.setOptionalBytes('abcd');
var group = new proto2.TestAllTypes.OptionalGroup();
group.setA(111);
message.setOptionalgroup(group);
var nestedMessage = new proto2.TestAllTypes.NestedMessage();
nestedMessage.setB(112);
message.setOptionalNestedMessage(nestedMessage);
message.setOptionalNestedEnum(proto2.TestAllTypes.NestedEnum.FOO);
// Repeated.
message.addRepeatedInt32(201);
message.addRepeatedInt32(202);
message.addRepeatedString('hello "world"');
// Serialize the message to text form.
var serializer = new goog.proto2.TextFormatSerializer();
var textform = serializer.serialize(message);
// Create a copy and deserialize into the copy.
var copy = new proto2.TestAllTypes();
serializer.deserializeTo(copy, textform);
// Assert that the messages are structurally equivalent.
assertTrue(copy.equals(message));
}
function testBidirectional64BitNumber() {
var message = new proto2.TestAllTypes();
message.setOptionalInt64Number(10000000);
message.setOptionalInt64String('200000000000000000');
// Serialize the message to text form.
var serializer = new goog.proto2.TextFormatSerializer();
var textform = serializer.serialize(message);
// Create a copy and deserialize into the copy.
var copy = new proto2.TestAllTypes();
serializer.deserializeTo(copy, textform);
// Assert that the messages are structurally equivalent.
assertTrue(copy.equals(message));
}
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Base class for all Protocol Buffer 2 serializers.
*/
goog.provide('goog.proto2.Serializer');
goog.require('goog.proto2.Descriptor');
goog.require('goog.proto2.FieldDescriptor');
goog.require('goog.proto2.Message');
goog.require('goog.proto2.Util');
/**
* Abstract base class for PB2 serializers. A serializer is a class which
* implements the serialization and deserialization of a Protocol Buffer Message
* to/from a specific format.
*
* @constructor
*/
goog.proto2.Serializer = function() {};
/**
* Serializes a message to the expected format.
*
* @param {goog.proto2.Message} message The message to be serialized.
*
* @return {*} The serialized form of the message.
*/
goog.proto2.Serializer.prototype.serialize = goog.abstractMethod;
/**
* Returns the serialized form of the given value for the given field
* if the field is a Message or Group and returns the value unchanged
* otherwise.
*
* @param {goog.proto2.FieldDescriptor} field The field from which this
* value came.
*
* @param {*} value The value of the field.
*
* @return {*} The value.
* @protected
*/
goog.proto2.Serializer.prototype.getSerializedValue = function(field, value) {
if (field.isCompositeType()) {
return this.serialize(/** @type {goog.proto2.Message} */ (value));
} else {
return value;
}
};
/**
* Deserializes a message from the expected format.
*
* @param {goog.proto2.Descriptor} descriptor The descriptor of the message
* to be created.
* @param {*} data The data of the message.
*
* @return {goog.proto2.Message} The message created.
*/
goog.proto2.Serializer.prototype.deserialize = function(descriptor, data) {
var message = descriptor.createMessageInstance();
this.deserializeTo(message, data);
goog.proto2.Util.assert(message instanceof goog.proto2.Message);
return message;
};
/**
* Deserializes a message from the expected format and places the
* data in the message.
*
* @param {goog.proto2.Message} message The message in which to
* place the information.
* @param {*} data The data of the message.
*/
goog.proto2.Serializer.prototype.deserializeTo = goog.abstractMethod;
/**
* Returns the deserialized form of the given value for the given field if the
* field is a Message or Group and returns the value, converted or unchanged,
* for primitive field types otherwise.
*
* @param {goog.proto2.FieldDescriptor} field The field from which this
* value came.
*
* @param {*} value The value of the field.
*
* @return {*} The value.
* @protected
*/
goog.proto2.Serializer.prototype.getDeserializedValue = function(field, value) {
// Composite types are deserialized recursively.
if (field.isCompositeType()) {
if (value instanceof goog.proto2.Message) {
return value;
}
return this.deserialize(field.getFieldMessageType(), value);
}
// Return the raw value if the field does not allow the JSON input to be
// converted.
if (!field.deserializationConversionPermitted()) {
return value;
}
// Convert to native type of field. Return the converted value or fall
// through to return the raw value. The JSON encoding of int64 value 123
// might be either the number 123 or the string "123". The field native type
// could be either Number or String (depending on field options in the .proto
// file). All four combinations should work correctly.
var nativeType = field.getNativeType();
if (nativeType === String) {
// JSON numbers can be converted to strings.
if (typeof value === 'number') {
return String(value);
}
} else if (nativeType === Number) {
// JSON strings are sometimes used for large integer numeric values.
if (typeof value === 'string') {
// Validate the string. If the string is not an integral number, we would
// rather have an assertion or error in the caller than a mysterious NaN
// value.
if (/^-?[0-9]+$/.test(value)) {
return Number(value);
}
}
}
return value;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utility methods for Protocol Buffer 2 implementation.
*/
goog.provide('goog.proto2.Util');
goog.require('goog.asserts');
/**
* @define {boolean} Defines a PBCHECK constant that can be turned off by
* clients of PB2. This for is clients that do not want assertion/checking
* running even in non-COMPILED builds.
*/
goog.proto2.Util.PBCHECK = !COMPILED;
/**
* Asserts that the given condition is true, if and only if the PBCHECK
* flag is on.
*
* @param {*} condition The condition to check.
* @param {string=} opt_message Error message in case of failure.
* @throws {Error} Assertion failed, the condition evaluates to false.
*/
goog.proto2.Util.assert = function(condition, opt_message) {
if (goog.proto2.Util.PBCHECK) {
goog.asserts.assert(condition, opt_message);
}
};
/**
* Returns true if debug assertions (checks) are on.
*
* @return {boolean} The value of the PBCHECK constant.
*/
goog.proto2.Util.conductChecks = function() {
return goog.proto2.Util.PBCHECK;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Protocol Buffer Field Descriptor class.
*/
goog.provide('goog.proto2.FieldDescriptor');
goog.require('goog.proto2.Util');
goog.require('goog.string');
/**
* A class which describes a field in a Protocol Buffer 2 Message.
*
* @param {Function} messageType Constructor for the message
* class to which the field described by this class belongs.
* @param {number|string} tag The field's tag index.
* @param {Object} metadata The metadata about this field that will be used
* to construct this descriptor.
*
* @constructor
*/
goog.proto2.FieldDescriptor = function(messageType, tag, metadata) {
/**
* The message type that contains the field that this
* descriptor describes.
* @type {Function}
* @private
*/
this.parent_ = messageType;
// Ensure that the tag is numeric.
goog.proto2.Util.assert(goog.string.isNumeric(tag));
/**
* The field's tag number.
* @type {number}
* @private
*/
this.tag_ = /** @type {number} */ (tag);
/**
* The field's name.
* @type {string}
* @private
*/
this.name_ = metadata.name;
/** @type {goog.proto2.FieldDescriptor.FieldType} */
metadata.fieldType;
/** @type {*} */
metadata.repeated;
/** @type {*} */
metadata.required;
/**
* If true, this field is a repeating field.
* @type {boolean}
* @private
*/
this.isRepeated_ = !!metadata.repeated;
/**
* If true, this field is required.
* @type {boolean}
* @private
*/
this.isRequired_ = !!metadata.required;
/**
* The field type of this field.
* @type {goog.proto2.FieldDescriptor.FieldType}
* @private
*/
this.fieldType_ = metadata.fieldType;
/**
* If this field is a primitive: The native (ECMAScript) type of this field.
* If an enumeration: The enumeration object.
* If a message or group field: The Message function.
* @type {Function}
* @private
*/
this.nativeType_ = metadata.type;
/**
* Is it permissible on deserialization to convert between numbers and
* well-formed strings? Is true for 64-bit integral field types, false for
* all other field types.
* @type {boolean}
* @private
*/
this.deserializationConversionPermitted_ = false;
switch (this.fieldType_) {
case goog.proto2.FieldDescriptor.FieldType.INT64:
case goog.proto2.FieldDescriptor.FieldType.UINT64:
case goog.proto2.FieldDescriptor.FieldType.FIXED64:
case goog.proto2.FieldDescriptor.FieldType.SFIXED64:
case goog.proto2.FieldDescriptor.FieldType.SINT64:
this.deserializationConversionPermitted_ = true;
break;
}
/**
* The default value of this field, if different from the default, default
* value.
* @type {*}
* @private
*/
this.defaultValue_ = metadata.defaultValue;
};
/**
* An enumeration defining the possible field types.
* Should be a mirror of that defined in descriptor.h.
*
* @enum {number}
*/
goog.proto2.FieldDescriptor.FieldType = {
DOUBLE: 1,
FLOAT: 2,
INT64: 3,
UINT64: 4,
INT32: 5,
FIXED64: 6,
FIXED32: 7,
BOOL: 8,
STRING: 9,
GROUP: 10,
MESSAGE: 11,
BYTES: 12,
UINT32: 13,
ENUM: 14,
SFIXED32: 15,
SFIXED64: 16,
SINT32: 17,
SINT64: 18
};
/**
* Returns the tag of the field that this descriptor represents.
*
* @return {number} The tag number.
*/
goog.proto2.FieldDescriptor.prototype.getTag = function() {
return this.tag_;
};
/**
* Returns the descriptor describing the message that defined this field.
* @return {goog.proto2.Descriptor} The descriptor.
*/
goog.proto2.FieldDescriptor.prototype.getContainingType = function() {
return this.parent_.getDescriptor();
};
/**
* Returns the name of the field that this descriptor represents.
* @return {string} The name.
*/
goog.proto2.FieldDescriptor.prototype.getName = function() {
return this.name_;
};
/**
* Returns the default value of this field.
* @return {*} The default value.
*/
goog.proto2.FieldDescriptor.prototype.getDefaultValue = function() {
if (this.defaultValue_ === undefined) {
// Set the default value based on a new instance of the native type.
// This will be (0, false, "") for (number, boolean, string) and will
// be a new instance of a group/message if the field is a message type.
var nativeType = this.nativeType_;
if (nativeType === Boolean) {
this.defaultValue_ = false;
} else if (nativeType === Number) {
this.defaultValue_ = 0;
} else if (nativeType === String) {
this.defaultValue_ = '';
} else {
this.defaultValue_ = new nativeType;
}
}
return this.defaultValue_;
};
/**
* Returns the field type of the field described by this descriptor.
* @return {goog.proto2.FieldDescriptor.FieldType} The field type.
*/
goog.proto2.FieldDescriptor.prototype.getFieldType = function() {
return this.fieldType_;
};
/**
* Returns the native (i.e. ECMAScript) type of the field described by this
* descriptor.
*
* @return {Object} The native type.
*/
goog.proto2.FieldDescriptor.prototype.getNativeType = function() {
return this.nativeType_;
};
/**
* Returns true if simple conversions between numbers and strings are permitted
* during deserialization for this field.
*
* @return {boolean} Whether conversion is permitted.
*/
goog.proto2.FieldDescriptor.prototype.deserializationConversionPermitted =
function() {
return this.deserializationConversionPermitted_;
};
/**
* Returns the descriptor of the message type of this field. Only valid
* for fields of type GROUP and MESSAGE.
*
* @return {goog.proto2.Descriptor} The message descriptor.
*/
goog.proto2.FieldDescriptor.prototype.getFieldMessageType = function() {
goog.proto2.Util.assert(this.isCompositeType(), 'Expected message or group');
return this.nativeType_.getDescriptor();
};
/**
* @return {boolean} True if the field stores composite data or repeated
* composite data (message or group).
*/
goog.proto2.FieldDescriptor.prototype.isCompositeType = function() {
return this.fieldType_ == goog.proto2.FieldDescriptor.FieldType.MESSAGE ||
this.fieldType_ == goog.proto2.FieldDescriptor.FieldType.GROUP;
};
/**
* Returns whether the field described by this descriptor is repeating.
* @return {boolean} Whether the field is repeated.
*/
goog.proto2.FieldDescriptor.prototype.isRepeated = function() {
return this.isRepeated_;
};
/**
* Returns whether the field described by this descriptor is required.
* @return {boolean} Whether the field is required.
*/
goog.proto2.FieldDescriptor.prototype.isRequired = function() {
return this.isRequired_;
};
/**
* Returns whether the field described by this descriptor is optional.
* @return {boolean} Whether the field is optional.
*/
goog.proto2.FieldDescriptor.prototype.isOptional = function() {
return !this.isRepeated_ && !this.isRequired_;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Protocol Buffer Message base class.
*/
goog.provide('goog.proto2.Message');
goog.require('goog.proto2.Descriptor');
goog.require('goog.proto2.FieldDescriptor');
goog.require('goog.proto2.Util');
goog.require('goog.string');
/**
* Abstract base class for all Protocol Buffer 2 messages. It will be
* subclassed in the code generated by the Protocol Compiler. Any other
* subclasses are prohibited.
* @constructor
*/
goog.proto2.Message = function() {
/**
* Stores the field values in this message. Keyed by the tag of the fields.
* @type {*}
* @private
*/
this.values_ = {};
/**
* Stores the field information (i.e. metadata) about this message.
* @type {Object.<number, !goog.proto2.FieldDescriptor>}
* @private
*/
this.fields_ = this.getDescriptor().getFieldsMap();
/**
* The lazy deserializer for this message instance, if any.
* @type {goog.proto2.LazyDeserializer}
* @private
*/
this.lazyDeserializer_ = null;
/**
* A map of those fields deserialized, from tag number to their deserialized
* value.
* @type {Object}
* @private
*/
this.deserializedFields_ = null;
};
/**
* An enumeration defining the possible field types.
* Should be a mirror of that defined in descriptor.h.
*
* TODO(user): Remove this alias. The code generator generates code that
* references this enum, so it needs to exist until the code generator is
* changed. The enum was moved to from Message to FieldDescriptor to avoid a
* dependency cycle.
*
* Use goog.proto2.FieldDescriptor.FieldType instead.
*
* @enum {number}
*/
goog.proto2.Message.FieldType = {
DOUBLE: 1,
FLOAT: 2,
INT64: 3,
UINT64: 4,
INT32: 5,
FIXED64: 6,
FIXED32: 7,
BOOL: 8,
STRING: 9,
GROUP: 10,
MESSAGE: 11,
BYTES: 12,
UINT32: 13,
ENUM: 14,
SFIXED32: 15,
SFIXED64: 16,
SINT32: 17,
SINT64: 18
};
/**
* All instances of goog.proto2.Message should have a static descriptorObj_
* property. This is a JSON representation of a Descriptor. The real Descriptor
* will be deserialized lazily in the getDescriptor() method.
*
* This declaration is just here for documentation purposes.
* goog.proto2.Message does not have its own descriptor.
*
* @type {undefined}
* @private
*/
goog.proto2.Message.descriptorObj_;
/**
* All instances of goog.proto2.Message should have a static descriptor_
* property. The Descriptor will be deserialized lazily in the getDescriptor()
* method.
*
* This declaration is just here for documentation purposes.
* goog.proto2.Message does not have its own descriptor.
*
* @type {undefined}
* @private
*/
goog.proto2.Message.descriptor_;
/**
* Initializes the message with a lazy deserializer and its associated data.
* This method should be called by internal methods ONLY.
*
* @param {goog.proto2.LazyDeserializer} deserializer The lazy deserializer to
* use to decode the data on the fly.
*
* @param {*} data The data to decode/deserialize.
*/
goog.proto2.Message.prototype.initializeForLazyDeserializer = function(
deserializer, data) {
this.lazyDeserializer_ = deserializer;
this.values_ = data;
this.deserializedFields_ = {};
};
/**
* Sets the value of an unknown field, by tag.
*
* @param {number} tag The tag of an unknown field (must be >= 1).
* @param {*} value The value for that unknown field.
*/
goog.proto2.Message.prototype.setUnknown = function(tag, value) {
goog.proto2.Util.assert(!this.fields_[tag],
'Field is not unknown in this message');
goog.proto2.Util.assert(tag >= 1, 'Tag is not valid');
goog.proto2.Util.assert(value !== null, 'Value cannot be null');
this.values_[tag] = value;
if (this.deserializedFields_) {
delete this.deserializedFields_[tag];
}
};
/**
* Iterates over all the unknown fields in the message.
*
* @param {function(number, *)} callback A callback method
* which gets invoked for each unknown field.
* @param {Object=} opt_scope The scope under which to execute the callback.
* If not given, the current message will be used.
*/
goog.proto2.Message.prototype.forEachUnknown = function(callback, opt_scope) {
var scope = opt_scope || this;
for (var key in this.values_) {
var keyNum = Number(key);
if (!this.fields_[keyNum]) {
callback.call(scope, keyNum, this.values_[key]);
}
}
};
/**
* Returns the descriptor which describes the current message.
*
* This only works if we assume people never subclass protobufs.
*
* @return {!goog.proto2.Descriptor} The descriptor.
*/
goog.proto2.Message.prototype.getDescriptor = function() {
// NOTE(nicksantos): These sorts of indirect references to descriptor
// through this.constructor are fragile. See the comments
// in set$Metadata for more info.
var Ctor = this.constructor;
return Ctor.descriptor_ ||
(Ctor.descriptor_ = goog.proto2.Message.create$Descriptor(
Ctor, Ctor.descriptorObj_));
};
/**
* Returns whether there is a value stored at the field specified by the
* given field descriptor.
*
* @param {goog.proto2.FieldDescriptor} field The field for which to check
* if there is a value.
*
* @return {boolean} True if a value was found.
*/
goog.proto2.Message.prototype.has = function(field) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
return this.has$Value(field.getTag());
};
/**
* Returns the array of values found for the given repeated field.
*
* @param {goog.proto2.FieldDescriptor} field The field for which to
* return the values.
*
* @return {!Array} The values found.
*/
goog.proto2.Message.prototype.arrayOf = function(field) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
return this.array$Values(field.getTag());
};
/**
* Returns the number of values stored in the given field.
*
* @param {goog.proto2.FieldDescriptor} field The field for which to count
* the number of values.
*
* @return {number} The count of the values in the given field.
*/
goog.proto2.Message.prototype.countOf = function(field) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
return this.count$Values(field.getTag());
};
/**
* Returns the value stored at the field specified by the
* given field descriptor.
*
* @param {goog.proto2.FieldDescriptor} field The field for which to get the
* value.
* @param {number=} opt_index If the field is repeated, the index to use when
* looking up the value.
*
* @return {*} The value found or null if none.
*/
goog.proto2.Message.prototype.get = function(field, opt_index) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
return this.get$Value(field.getTag(), opt_index);
};
/**
* Returns the value stored at the field specified by the
* given field descriptor or the default value if none exists.
*
* @param {goog.proto2.FieldDescriptor} field The field for which to get the
* value.
* @param {number=} opt_index If the field is repeated, the index to use when
* looking up the value.
*
* @return {*} The value found or the default if none.
*/
goog.proto2.Message.prototype.getOrDefault = function(field, opt_index) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
return this.get$ValueOrDefault(field.getTag(), opt_index);
};
/**
* Stores the given value to the field specified by the
* given field descriptor. Note that the field must not be repeated.
*
* @param {goog.proto2.FieldDescriptor} field The field for which to set
* the value.
* @param {*} value The new value for the field.
*/
goog.proto2.Message.prototype.set = function(field, value) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
this.set$Value(field.getTag(), value);
};
/**
* Adds the given value to the field specified by the
* given field descriptor. Note that the field must be repeated.
*
* @param {goog.proto2.FieldDescriptor} field The field in which to add the
* the value.
* @param {*} value The new value to add to the field.
*/
goog.proto2.Message.prototype.add = function(field, value) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
this.add$Value(field.getTag(), value);
};
/**
* Clears the field specified.
*
* @param {goog.proto2.FieldDescriptor} field The field to clear.
*/
goog.proto2.Message.prototype.clear = function(field) {
goog.proto2.Util.assert(
field.getContainingType() == this.getDescriptor(),
'The current message does not contain the given field');
this.clear$Field(field.getTag());
};
/**
* Compares this message with another one ignoring the unknown fields.
* @param {*} other The other message.
* @return {boolean} Whether they are equal. Returns false if the {@code other}
* argument is a different type of message or not a message.
*/
goog.proto2.Message.prototype.equals = function(other) {
if (!other || this.constructor != other.constructor) {
return false;
}
var fields = this.getDescriptor().getFields();
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (this.has(field) != other.has(field)) {
return false;
}
if (this.has(field)) {
var isComposite = field.isCompositeType();
var fieldsEqual = function(value1, value2) {
return isComposite ? value1.equals(value2) : value1 == value2;
};
var thisValue = this.getValueForField_(field);
var otherValue = other.getValueForField_(field);
if (field.isRepeated()) {
// In this case thisValue and otherValue are arrays.
if (thisValue.length != otherValue.length) {
return false;
}
for (var j = 0; j < thisValue.length; j++) {
if (!fieldsEqual(thisValue[j], otherValue[j])) {
return false;
}
}
} else if (!fieldsEqual(thisValue, otherValue)) {
return false;
}
}
}
return true;
};
/**
* Recursively copies the known fields from the given message to this message.
* Removes the fields which are not present in the source message.
* @param {!goog.proto2.Message} message The source message.
*/
goog.proto2.Message.prototype.copyFrom = function(message) {
goog.proto2.Util.assert(this.constructor == message.constructor,
'The source message must have the same type.');
if (this != message) {
this.values_ = {};
if (this.deserializedFields_) {
this.deserializedFields_ = {};
}
this.mergeFrom(message);
}
};
/**
* Merges the given message into this message.
*
* Singular fields will be overwritten, except for embedded messages which will
* be merged. Repeated fields will be concatenated.
* @param {!goog.proto2.Message} message The source message.
*/
goog.proto2.Message.prototype.mergeFrom = function(message) {
goog.proto2.Util.assert(this.constructor == message.constructor,
'The source message must have the same type.');
var fields = this.getDescriptor().getFields();
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (message.has(field)) {
if (this.deserializedFields_) {
delete this.deserializedFields_[field.getTag()];
}
var isComposite = field.isCompositeType();
if (field.isRepeated()) {
var values = message.arrayOf(field);
for (var j = 0; j < values.length; j++) {
this.add(field, isComposite ? values[j].clone() : values[j]);
}
} else {
var value = message.getValueForField_(field);
if (isComposite) {
var child = this.getValueForField_(field);
if (child) {
child.mergeFrom(value);
} else {
this.set(field, value.clone());
}
} else {
this.set(field, value);
}
}
}
}
};
/**
* @return {!goog.proto2.Message} Recursive clone of the message only including
* the known fields.
*/
goog.proto2.Message.prototype.clone = function() {
var clone = new this.constructor;
clone.copyFrom(this);
return clone;
};
/**
* Fills in the protocol buffer with default values. Any fields that are
* already set will not be overridden.
* @param {boolean} simpleFieldsToo If true, all fields will be initialized;
* if false, only the nested messages and groups.
*/
goog.proto2.Message.prototype.initDefaults = function(simpleFieldsToo) {
var fields = this.getDescriptor().getFields();
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var tag = field.getTag();
var isComposite = field.isCompositeType();
// Initialize missing fields.
if (!this.has(field) && !field.isRepeated()) {
if (isComposite) {
this.values_[tag] = new /** @type {Function} */ (field.getNativeType());
} else if (simpleFieldsToo) {
this.values_[tag] = field.getDefaultValue();
}
}
// Fill in the existing composite fields recursively.
if (isComposite) {
if (field.isRepeated()) {
var values = this.array$Values(tag);
for (var j = 0; j < values.length; j++) {
values[j].initDefaults(simpleFieldsToo);
}
} else {
this.get$Value(tag).initDefaults(simpleFieldsToo);
}
}
}
};
/**
* Returns the field in this message by the given tag number. If no
* such field exists, throws an exception.
*
* @param {number} tag The field's tag index.
* @return {!goog.proto2.FieldDescriptor} The descriptor for the field.
* @private
*/
goog.proto2.Message.prototype.getFieldByTag_ = function(tag) {
goog.proto2.Util.assert(this.fields_[tag],
'No field found for the given tag');
return this.fields_[tag];
};
/**
* Returns the whether or not the field indicated by the given tag
* has a value.
*
* GENERATED CODE USE ONLY. Basis of the has{Field} methods.
*
* @param {number} tag The tag.
*
* @return {boolean} Whether the message has a value for the field.
*/
goog.proto2.Message.prototype.has$Value = function(tag) {
goog.proto2.Util.assert(this.fields_[tag],
'No field found for the given tag');
return tag in this.values_ && goog.isDef(this.values_[tag]) &&
this.values_[tag] !== null;
};
/**
* Returns the value for the given field. If a lazy deserializer is
* instantiated, lazily deserializes the field if required before returning the
* value.
*
* @param {goog.proto2.FieldDescriptor} field The field.
* @return {*} The field value, if any.
* @private
*/
goog.proto2.Message.prototype.getValueForField_ = function(field) {
// Retrieve the current value, which may still be serialized.
var tag = field.getTag();
if (!tag in this.values_) {
return null;
}
var value = this.values_[tag];
if (value == null) {
return null;
}
// If we have a lazy deserializer, then ensure that the field is
// properly deserialized.
if (this.lazyDeserializer_) {
// If the tag is not deserialized, then we must do so now. Deserialize
// the field's value via the deserializer.
if (!(tag in this.deserializedFields_)) {
var deserializedValue = this.lazyDeserializer_.deserializeField(
this, field, value);
this.deserializedFields_[tag] = deserializedValue;
return deserializedValue;
}
return this.deserializedFields_[tag];
}
// Otherwise, just return the value.
return value;
};
/**
* Gets the value at the field indicated by the given tag.
*
* GENERATED CODE USE ONLY. Basis of the get{Field} methods.
*
* @param {number} tag The field's tag index.
* @param {number=} opt_index If the field is a repeated field, the index
* at which to get the value.
*
* @return {*} The value found or null for none.
* @protected
*/
goog.proto2.Message.prototype.get$Value = function(tag, opt_index) {
var field = this.getFieldByTag_(tag);
var value = this.getValueForField_(field);
if (field.isRepeated()) {
goog.proto2.Util.assert(goog.isArray(value));
var index = opt_index || 0;
goog.proto2.Util.assert(index >= 0 && index < value.length,
'Given index is out of bounds');
return value[index];
}
goog.proto2.Util.assert(!goog.isArray(value));
return value;
};
/**
* Gets the value at the field indicated by the given tag or the default value
* if none.
*
* GENERATED CODE USE ONLY. Basis of the get{Field} methods.
*
* @param {number} tag The field's tag index.
* @param {number=} opt_index If the field is a repeated field, the index
* at which to get the value.
*
* @return {*} The value found or the default value if none set.
* @protected
*/
goog.proto2.Message.prototype.get$ValueOrDefault = function(tag, opt_index) {
if (!this.has$Value(tag)) {
// Return the default value.
var field = this.getFieldByTag_(tag);
return field.getDefaultValue();
}
return this.get$Value(tag, opt_index);
};
/**
* Gets the values at the field indicated by the given tag.
*
* GENERATED CODE USE ONLY. Basis of the {field}Array methods.
*
* @param {number} tag The field's tag index.
*
* @return {!Array} The values found. If none, returns an empty array.
* @protected
*/
goog.proto2.Message.prototype.array$Values = function(tag) {
goog.proto2.Util.assert(this.getFieldByTag_(tag).isRepeated(),
'Cannot call fieldArray on a non-repeated field');
var field = this.getFieldByTag_(tag);
var value = this.getValueForField_(field);
goog.proto2.Util.assert(value == null || goog.isArray(value));
return /** @type {Array} */ (value) || [];
};
/**
* Returns the number of values stored in the field by the given tag.
*
* GENERATED CODE USE ONLY. Basis of the {field}Count methods.
*
* @param {number} tag The tag.
*
* @return {number} The number of values.
* @protected
*/
goog.proto2.Message.prototype.count$Values = function(tag) {
var field = this.getFieldByTag_(tag);
if (field.isRepeated()) {
if (this.has$Value(tag)) {
goog.proto2.Util.assert(goog.isArray(this.values_[tag]));
}
return this.has$Value(tag) ? this.values_[tag].length : 0;
} else {
return this.has$Value(tag) ? 1 : 0;
}
};
/**
* Sets the value of the *non-repeating* field indicated by the given tag.
*
* GENERATED CODE USE ONLY. Basis of the set{Field} methods.
*
* @param {number} tag The field's tag index.
* @param {*} value The field's value.
* @protected
*/
goog.proto2.Message.prototype.set$Value = function(tag, value) {
if (goog.proto2.Util.conductChecks()) {
var field = this.getFieldByTag_(tag);
goog.proto2.Util.assert(!field.isRepeated(),
'Cannot call set on a repeated field');
this.checkFieldType_(field, value);
}
this.values_[tag] = value;
if (this.deserializedFields_) {
this.deserializedFields_[tag] = value;
}
};
/**
* Adds the value to the *repeating* field indicated by the given tag.
*
* GENERATED CODE USE ONLY. Basis of the add{Field} methods.
*
* @param {number} tag The field's tag index.
* @param {*} value The value to add.
* @protected
*/
goog.proto2.Message.prototype.add$Value = function(tag, value) {
if (goog.proto2.Util.conductChecks()) {
var field = this.getFieldByTag_(tag);
goog.proto2.Util.assert(field.isRepeated(),
'Cannot call add on a non-repeated field');
this.checkFieldType_(field, value);
}
if (!this.values_[tag]) {
this.values_[tag] = [];
}
this.values_[tag].push(value);
if (this.deserializedFields_) {
delete this.deserializedFields_[tag];
}
};
/**
* Ensures that the value being assigned to the given field
* is valid.
*
* @param {!goog.proto2.FieldDescriptor} field The field being assigned.
* @param {*} value The value being assigned.
* @private
*/
goog.proto2.Message.prototype.checkFieldType_ = function(field, value) {
goog.proto2.Util.assert(value !== null);
var nativeType = field.getNativeType();
if (nativeType === String) {
goog.proto2.Util.assert(typeof value === 'string',
'Expected value of type string');
} else if (nativeType === Boolean) {
goog.proto2.Util.assert(typeof value === 'boolean',
'Expected value of type boolean');
} else if (nativeType === Number) {
goog.proto2.Util.assert(typeof value === 'number',
'Expected value of type number');
} else if (field.getFieldType() ==
goog.proto2.FieldDescriptor.FieldType.ENUM) {
goog.proto2.Util.assert(typeof value === 'number',
'Expected an enum value, which is a number');
} else {
goog.proto2.Util.assert(value instanceof nativeType,
'Expected a matching message type');
}
};
/**
* Clears the field specified by tag.
*
* GENERATED CODE USE ONLY. Basis of the clear{Field} methods.
*
* @param {number} tag The tag of the field to clear.
* @protected
*/
goog.proto2.Message.prototype.clear$Field = function(tag) {
goog.proto2.Util.assert(this.getFieldByTag_(tag), 'Unknown field');
delete this.values_[tag];
if (this.deserializedFields_) {
delete this.deserializedFields_[tag];
}
};
/**
* Creates the metadata descriptor representing the definition of this message.
*
* GENERATED CODE USE ONLY. Called when constructing message classes.
*
* @param {function(new:goog.proto2.Message)} messageType Constructor for the
* message type to which this metadata applies.
* @param {Object} metadataObj The object containing the metadata.
* @return {!goog.proto2.Descriptor} The new descriptor.
*/
goog.proto2.Message.create$Descriptor = function(messageType, metadataObj) {
var fields = [];
var descriptorInfo;
for (var key in metadataObj) {
if (!metadataObj.hasOwnProperty(key)) {
continue;
}
goog.proto2.Util.assert(goog.string.isNumeric(key), 'Keys must be numeric');
if (key == 0) {
descriptorInfo = metadataObj[0];
continue;
}
// Create the field descriptor.
fields.push(
new goog.proto2.FieldDescriptor(messageType, key, metadataObj[key]));
}
goog.proto2.Util.assert(descriptorInfo);
return new goog.proto2.Descriptor(messageType, descriptorInfo, fields);
};
/**
* Sets the metadata that represents the definition of this message.
*
* GENERATED CODE USE ONLY. Called when constructing message classes.
*
* @param {!Function} messageType Constructor for the
* message type to which this metadata applies.
* @param {Object} metadataObj The object containing the metadata.
*/
goog.proto2.Message.set$Metadata = function(messageType, metadataObj) {
// NOTE(nicksantos): JSCompiler's type-based optimizations really do not
// like indirectly defined methods (both prototype methods and
// static methods). This is very fragile in compiled code. I think it only
// really works by accident, and is highly likely to break in the future.
messageType.descriptorObj_ = metadataObj;
messageType.getDescriptor = function() {
// The descriptor is created lazily when we instantiate a new instance.
return messageType.descriptor_ ||
(new messageType()).getDescriptor();
};
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Base class for all PB2 lazy deserializer. A lazy deserializer
* is a serializer whose deserialization occurs on the fly as data is
* requested. In order to use a lazy deserializer, the serialized form
* of the data must be an object or array that can be indexed by the tag
* number.
*
*/
goog.provide('goog.proto2.LazyDeserializer');
goog.require('goog.proto2.Message');
goog.require('goog.proto2.Serializer');
goog.require('goog.proto2.Util');
/**
* Base class for all lazy deserializers.
*
* @constructor
* @extends {goog.proto2.Serializer}
*/
goog.proto2.LazyDeserializer = function() {};
goog.inherits(goog.proto2.LazyDeserializer, goog.proto2.Serializer);
/** @override */
goog.proto2.LazyDeserializer.prototype.deserialize =
function(descriptor, data) {
var message = descriptor.createMessageInstance();
message.initializeForLazyDeserializer(this, data);
goog.proto2.Util.assert(message instanceof goog.proto2.Message);
return message;
};
/** @override */
goog.proto2.LazyDeserializer.prototype.deserializeTo = function(message, data) {
throw new Error('Unimplemented');
};
/**
* Deserializes a message field from the expected format and places the
* data in the given message
*
* @param {goog.proto2.Message} message The message in which to
* place the information.
* @param {goog.proto2.FieldDescriptor} field The field for which to set the
* message value.
* @param {*} data The serialized data for the field.
*
* @return {*} The deserialized data or null for no value found.
*/
goog.proto2.LazyDeserializer.prototype.deserializeField = goog.abstractMethod;
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Protocol Buffer 2 Serializer which serializes messages
* into PB-Lite ("JsPbLite") format.
*
* PB-Lite format is an array where each index corresponds to the associated tag
* number. For example, a message like so:
*
* message Foo {
* optional int bar = 1;
* optional int baz = 2;
* optional int bop = 4;
* }
*
* would be represented as such:
*
* [, (bar data), (baz data), (nothing), (bop data)]
*
* Note that since the array index is used to represent the tag number, sparsely
* populated messages with tag numbers that are not continuous (and/or are very
* large) will have many (empty) spots and thus, are inefficient.
*
*
*/
goog.provide('goog.proto2.PbLiteSerializer');
goog.require('goog.proto2.LazyDeserializer');
goog.require('goog.proto2.Util');
/**
* PB-Lite serializer.
*
* @constructor
* @extends {goog.proto2.LazyDeserializer}
*/
goog.proto2.PbLiteSerializer = function() {};
goog.inherits(goog.proto2.PbLiteSerializer, goog.proto2.LazyDeserializer);
/**
* If true, fields will be serialized with 0-indexed tags (i.e., the proto
* field with tag id 1 will have index 0 in the array).
* @type {boolean}
* @private
*/
goog.proto2.PbLiteSerializer.prototype.zeroIndexing_ = false;
/**
* By default, the proto tag with id 1 will have index 1 in the serialized
* array.
*
* If the serializer is set to use zero-indexing, the tag with id 1 will have
* index 0.
*
* @param {boolean} zeroIndexing Whether this serializer should deal with
* 0-indexed protos.
*/
goog.proto2.PbLiteSerializer.prototype.setZeroIndexed = function(zeroIndexing) {
this.zeroIndexing_ = zeroIndexing;
};
/**
* Serializes a message to a PB-Lite object.
*
* @param {goog.proto2.Message} message The message to be serialized.
* @return {!Array} The serialized form of the message.
* @override
*/
goog.proto2.PbLiteSerializer.prototype.serialize = function(message) {
var descriptor = message.getDescriptor();
var fields = descriptor.getFields();
var serialized = [];
var zeroIndexing = this.zeroIndexing_;
// Add the known fields.
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (!message.has(field)) {
continue;
}
var tag = field.getTag();
var index = zeroIndexing ? tag - 1 : tag;
if (field.isRepeated()) {
serialized[index] = [];
for (var j = 0; j < message.countOf(field); j++) {
serialized[index][j] =
this.getSerializedValue(field, message.get(field, j));
}
} else {
serialized[index] = this.getSerializedValue(field, message.get(field));
}
}
// Add any unknown fields.
message.forEachUnknown(function(tag, value) {
var index = zeroIndexing ? tag - 1 : tag;
serialized[index] = value;
});
return serialized;
};
/** @override */
goog.proto2.PbLiteSerializer.prototype.deserializeField =
function(message, field, value) {
if (value == null) {
// Since value double-equals null, it may be either null or undefined.
// Ensure we return the same one, since they have different meanings.
return value;
}
if (field.isRepeated()) {
var data = [];
goog.proto2.Util.assert(goog.isArray(value));
for (var i = 0; i < value.length; i++) {
data[i] = this.getDeserializedValue(field, value[i]);
}
return data;
} else {
return this.getDeserializedValue(field, value);
}
};
/** @override */
goog.proto2.PbLiteSerializer.prototype.getSerializedValue =
function(field, value) {
if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.BOOL) {
// Booleans are serialized in numeric form.
return value ? 1 : 0;
}
return goog.proto2.Serializer.prototype.getSerializedValue.apply(this,
arguments);
};
/** @override */
goog.proto2.PbLiteSerializer.prototype.getDeserializedValue =
function(field, value) {
if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.BOOL) {
// Booleans are serialized in numeric form.
return value === 1;
}
return goog.proto2.Serializer.prototype.getDeserializedValue.apply(this,
arguments);
};
/** @override */
goog.proto2.PbLiteSerializer.prototype.deserialize =
function(descriptor, data) {
var toConvert = data;
if (this.zeroIndexing_) {
// Make the data align with tag-IDs (1-indexed) by shifting everything
// up one.
toConvert = [];
for (var key in data) {
toConvert[parseInt(key, 10) + 1] = data[key];
}
}
return goog.base(this, 'deserialize', descriptor, toConvert);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Protocol Buffer (Message) Descriptor class.
*/
goog.provide('goog.proto2.Descriptor');
goog.provide('goog.proto2.Metadata');
goog.require('goog.array');
goog.require('goog.object');
goog.require('goog.proto2.Util');
/**
* @typedef {{name: (string|undefined),
* fullName: (string|undefined),
* containingType: (goog.proto2.Message|undefined)}}
*/
goog.proto2.Metadata;
/**
* A class which describes a Protocol Buffer 2 Message.
*
* @param {function(new:goog.proto2.Message)} messageType Constructor for
* the message class that this descriptor describes.
* @param {!goog.proto2.Metadata} metadata The metadata about the message that
* will be used to construct this descriptor.
* @param {Array.<!goog.proto2.FieldDescriptor>} fields The fields of the
* message described by this descriptor.
*
* @constructor
*/
goog.proto2.Descriptor = function(messageType, metadata, fields) {
/**
* @type {function(new:goog.proto2.Message)}
* @private
*/
this.messageType_ = messageType;
/**
* @type {?string}
* @private
*/
this.name_ = metadata.name || null;
/**
* @type {?string}
* @private
*/
this.fullName_ = metadata.fullName || null;
/**
* @type {goog.proto2.Message|undefined}
* @private
*/
this.containingType_ = metadata.containingType;
/**
* The fields of the message described by this descriptor.
* @type {!Object.<number, !goog.proto2.FieldDescriptor>}
* @private
*/
this.fields_ = {};
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
this.fields_[field.getTag()] = field;
}
};
/**
* Returns the name of the message, if any.
*
* @return {?string} The name.
*/
goog.proto2.Descriptor.prototype.getName = function() {
return this.name_;
};
/**
* Returns the full name of the message, if any.
*
* @return {?string} The name.
*/
goog.proto2.Descriptor.prototype.getFullName = function() {
return this.fullName_;
};
/**
* Returns the descriptor of the containing message type or null if none.
*
* @return {goog.proto2.Descriptor} The descriptor.
*/
goog.proto2.Descriptor.prototype.getContainingType = function() {
if (!this.containingType_) {
return null;
}
return this.containingType_.getDescriptor();
};
/**
* Returns the fields in the message described by this descriptor ordered by
* tag.
*
* @return {!Array.<!goog.proto2.FieldDescriptor>} The array of field
* descriptors.
*/
goog.proto2.Descriptor.prototype.getFields = function() {
/**
* @param {!goog.proto2.FieldDescriptor} fieldA First field.
* @param {!goog.proto2.FieldDescriptor} fieldB Second field.
* @return {number} Negative if fieldA's tag number is smaller, positive
* if greater, zero if the same.
*/
function tagComparator(fieldA, fieldB) {
return fieldA.getTag() - fieldB.getTag();
};
var fields = goog.object.getValues(this.fields_);
goog.array.sort(fields, tagComparator);
return fields;
};
/**
* Returns the fields in the message as a key/value map, where the key is
* the tag number of the field. DO NOT MODIFY THE RETURNED OBJECT. We return
* the actual, internal, fields map for performance reasons, and changing the
* map can result in undefined behavior of this library.
*
* @return {!Object.<number, !goog.proto2.FieldDescriptor>} The field map.
*/
goog.proto2.Descriptor.prototype.getFieldsMap = function() {
return this.fields_;
};
/**
* Returns the field matching the given name, if any. Note that
* this method searches over the *original* name of the field,
* not the camelCase version.
*
* @param {string} name The field name for which to search.
*
* @return {goog.proto2.FieldDescriptor} The field found, if any.
*/
goog.proto2.Descriptor.prototype.findFieldByName = function(name) {
var valueFound = goog.object.findValue(this.fields_,
function(field, key, obj) {
return field.getName() == name;
});
return /** @type {goog.proto2.FieldDescriptor} */ (valueFound) || null;
};
/**
* Returns the field matching the given tag number, if any.
*
* @param {number|string} tag The field tag number for which to search.
*
* @return {goog.proto2.FieldDescriptor} The field found, if any.
*/
goog.proto2.Descriptor.prototype.findFieldByTag = function(tag) {
goog.proto2.Util.assert(goog.string.isNumeric(tag));
return this.fields_[parseInt(tag, 10)] || null;
};
/**
* Creates an instance of the message type that this descriptor
* describes.
*
* @return {!goog.proto2.Message} The instance of the message.
*/
goog.proto2.Descriptor.prototype.createMessageInstance = function() {
return new this.messageType_;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Protocol Buffer 2 Serializer which serializes messages
* into anonymous, simplified JSON objects.
*
*/
goog.provide('goog.proto2.ObjectSerializer');
goog.require('goog.proto2.Serializer');
goog.require('goog.proto2.Util');
goog.require('goog.string');
/**
* ObjectSerializer, a serializer which turns Messages into simplified
* ECMAScript objects.
*
* @param {goog.proto2.ObjectSerializer.KeyOption=} opt_keyOption If specified,
* which key option to use when serializing/deserializing.
* @constructor
* @extends {goog.proto2.Serializer}
*/
goog.proto2.ObjectSerializer = function(opt_keyOption) {
this.keyOption_ = opt_keyOption;
};
goog.inherits(goog.proto2.ObjectSerializer, goog.proto2.Serializer);
/**
* An enumeration of the options for how to emit the keys in
* the generated simplified object.
*
* @enum {number}
*/
goog.proto2.ObjectSerializer.KeyOption = {
/**
* Use the tag of the field as the key (default)
*/
TAG: 0,
/**
* Use the name of the field as the key. Unknown fields
* will still use their tags as keys.
*/
NAME: 1
};
/**
* Serializes a message to an object.
*
* @param {goog.proto2.Message} message The message to be serialized.
* @return {Object} The serialized form of the message.
* @override
*/
goog.proto2.ObjectSerializer.prototype.serialize = function(message) {
var descriptor = message.getDescriptor();
var fields = descriptor.getFields();
var objectValue = {};
// Add the defined fields, recursively.
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var key =
this.keyOption_ == goog.proto2.ObjectSerializer.KeyOption.NAME ?
field.getName() : field.getTag();
if (message.has(field)) {
if (field.isRepeated()) {
var array = [];
objectValue[key] = array;
for (var j = 0; j < message.countOf(field); j++) {
array.push(this.getSerializedValue(field, message.get(field, j)));
}
} else {
objectValue[key] = this.getSerializedValue(field, message.get(field));
}
}
}
// Add the unknown fields, if any.
message.forEachUnknown(function(tag, value) {
objectValue[tag] = value;
});
return objectValue;
};
/**
* Deserializes a message from an object and places the
* data in the message.
*
* @param {goog.proto2.Message} message The message in which to
* place the information.
* @param {*} data The data of the message.
* @override
*/
goog.proto2.ObjectSerializer.prototype.deserializeTo = function(message, data) {
var descriptor = message.getDescriptor();
for (var key in data) {
var field;
var value = data[key];
var isNumeric = goog.string.isNumeric(key);
if (isNumeric) {
field = descriptor.findFieldByTag(key);
} else {
// We must be in Key == NAME mode to lookup by name.
goog.proto2.Util.assert(
this.keyOption_ == goog.proto2.ObjectSerializer.KeyOption.NAME);
field = descriptor.findFieldByName(key);
}
if (field) {
if (field.isRepeated()) {
goog.proto2.Util.assert(goog.isArray(value));
for (var j = 0; j < value.length; j++) {
message.add(field, this.getDeserializedValue(field, value[j]));
}
} else {
goog.proto2.Util.assert(!goog.isArray(value));
message.set(field, this.getDeserializedValue(field, value));
}
} else {
if (isNumeric) {
// We have an unknown field.
message.setUnknown(Number(key), value);
} else {
// Named fields must be present.
goog.proto2.Util.assert(field);
}
}
}
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tool for caching the result of expensive deterministic
* functions.
*
* @see http://en.wikipedia.org/wiki/Memoization
*
*/
goog.provide('goog.memoize');
/**
* Decorator around functions that caches the inner function's return values.
* @param {Function} f The function to wrap. Its return value may only depend
* on its arguments and 'this' context. There may be further restrictions
* on the arguments depending on the capabilities of the serializer used.
* @param {function(number, Object): string=} opt_serializer A function to
* serialize f's arguments. It must have the same signature as
* goog.memoize.simpleSerializer. It defaults to that function.
* @this {Object} The object whose function is being wrapped.
* @return {!Function} The wrapped function.
*/
goog.memoize = function(f, opt_serializer) {
var functionUid = goog.getUid(f);
var serializer = opt_serializer || goog.memoize.simpleSerializer;
return function() {
if (goog.memoize.ENABLE_MEMOIZE) {
// In the strict mode, when this function is called as a global function,
// the value of 'this' is undefined instead of a global object. See:
// https://developer.mozilla.org/en/JavaScript/Strict_mode
var thisOrGlobal = this || goog.global;
// Maps the serialized list of args to the corresponding return value.
var cache = thisOrGlobal[goog.memoize.CACHE_PROPERTY_] ||
(thisOrGlobal[goog.memoize.CACHE_PROPERTY_] = {});
var key = serializer(functionUid, arguments);
return cache.hasOwnProperty(key) ? cache[key] :
(cache[key] = f.apply(this, arguments));
} else {
return f.apply(this, arguments);
}
};
};
/**
* @define {boolean} Flag to disable memoization in unit tests.
*/
goog.memoize.ENABLE_MEMOIZE = true;
/**
* Clears the memoization cache on the given object.
* @param {Object} cacheOwner The owner of the cache. This is the {@code this}
* context of the memoized function.
*/
goog.memoize.clearCache = function(cacheOwner) {
cacheOwner[goog.memoize.CACHE_PROPERTY_] = {};
};
/**
* Name of the property used by goog.memoize as cache.
* @type {string}
* @private
*/
goog.memoize.CACHE_PROPERTY_ = 'closure_memoize_cache_';
/**
* Simple and fast argument serializer function for goog.memoize.
* Supports string, number, boolean, null and undefined arguments. Doesn't
* support \x0B characters in the strings.
* @param {number} functionUid Unique identifier of the function whose result
* is cached.
* @param {Object} args The arguments that the function to memoize is called
* with. Note: it is an array-like object, because supports indexing and
* has the length property.
* @return {string} The list of arguments with type information concatenated
* with the functionUid argument, serialized as \x0B-separated string.
*/
goog.memoize.simpleSerializer = function(functionUid, args) {
var context = [functionUid];
for (var i = args.length - 1; i >= 0; --i) {
context.push(typeof args[i], args[i]);
}
return context.join('\x0B');
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities to check the preconditions, postconditions and
* invariants runtime.
*
* Methods in this package should be given special treatment by the compiler
* for type-inference. For example, <code>goog.asserts.assert(foo)</code>
* will restrict <code>foo</code> to a truthy value.
*
* The compiler has an option to disable asserts. So code like:
* <code>
* var x = goog.asserts.assert(foo()); goog.asserts.assert(bar());
* </code>
* will be transformed into:
* <code>
* var x = foo();
* </code>
* The compiler will leave in foo() (because its return value is used),
* but it will remove bar() because it assumes it does not have side-effects.
*
*/
goog.provide('goog.asserts');
goog.provide('goog.asserts.AssertionError');
goog.require('goog.debug.Error');
goog.require('goog.string');
/**
* @define {boolean} Whether to strip out asserts or to leave them in.
*/
goog.asserts.ENABLE_ASSERTS = goog.DEBUG;
/**
* Error object for failed assertions.
* @param {string} messagePattern The pattern that was used to form message.
* @param {!Array.<*>} messageArgs The items to substitute into the pattern.
* @constructor
* @extends {goog.debug.Error}
*/
goog.asserts.AssertionError = function(messagePattern, messageArgs) {
messageArgs.unshift(messagePattern);
goog.debug.Error.call(this, goog.string.subs.apply(null, messageArgs));
// Remove the messagePattern afterwards to avoid permenantly modifying the
// passed in array.
messageArgs.shift();
/**
* The message pattern used to format the error message. Error handlers can
* use this to uniquely identify the assertion.
* @type {string}
*/
this.messagePattern = messagePattern;
};
goog.inherits(goog.asserts.AssertionError, goog.debug.Error);
/** @override */
goog.asserts.AssertionError.prototype.name = 'AssertionError';
/**
* Throws an exception with the given message and "Assertion failed" prefixed
* onto it.
* @param {string} defaultMessage The message to use if givenMessage is empty.
* @param {Array.<*>} defaultArgs The substitution arguments for defaultMessage.
* @param {string|undefined} givenMessage Message supplied by the caller.
* @param {Array.<*>} givenArgs The substitution arguments for givenMessage.
* @throws {goog.asserts.AssertionError} When the value is not a number.
* @private
*/
goog.asserts.doAssertFailure_ =
function(defaultMessage, defaultArgs, givenMessage, givenArgs) {
var message = 'Assertion failed';
if (givenMessage) {
message += ': ' + givenMessage;
var args = givenArgs;
} else if (defaultMessage) {
message += ': ' + defaultMessage;
args = defaultArgs;
}
// The '' + works around an Opera 10 bug in the unit tests. Without it,
// a stack trace is added to var message above. With this, a stack trace is
// not added until this line (it causes the extra garbage to be added after
// the assertion message instead of in the middle of it).
throw new goog.asserts.AssertionError('' + message, args || []);
};
/**
* Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is
* true.
* @param {*} condition The condition to check.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @return {*} The value of the condition.
* @throws {goog.asserts.AssertionError} When the condition evaluates to false.
*/
goog.asserts.assert = function(condition, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !condition) {
goog.asserts.doAssertFailure_('', null, opt_message,
Array.prototype.slice.call(arguments, 2));
}
return condition;
};
/**
* Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case
* when we want to add a check in the unreachable area like switch-case
* statement:
*
* <pre>
* switch(type) {
* case FOO: doSomething(); break;
* case BAR: doSomethingElse(); break;
* default: goog.assert.fail('Unrecognized type: ' + type);
* // We have only 2 types - "default:" section is unreachable code.
* }
* </pre>
*
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @throws {goog.asserts.AssertionError} Failure.
*/
goog.asserts.fail = function(opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS) {
throw new goog.asserts.AssertionError(
'Failure' + (opt_message ? ': ' + opt_message : ''),
Array.prototype.slice.call(arguments, 1));
}
};
/**
* Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.
* @param {*} value The value to check.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @return {number} The value, guaranteed to be a number when asserts enabled.
* @throws {goog.asserts.AssertionError} When the value is not a number.
*/
goog.asserts.assertNumber = function(value, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) {
goog.asserts.doAssertFailure_('Expected number but got %s: %s.',
[goog.typeOf(value), value], opt_message,
Array.prototype.slice.call(arguments, 2));
}
return /** @type {number} */ (value);
};
/**
* Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.
* @param {*} value The value to check.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @return {string} The value, guaranteed to be a string when asserts enabled.
* @throws {goog.asserts.AssertionError} When the value is not a string.
*/
goog.asserts.assertString = function(value, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) {
goog.asserts.doAssertFailure_('Expected string but got %s: %s.',
[goog.typeOf(value), value], opt_message,
Array.prototype.slice.call(arguments, 2));
}
return /** @type {string} */ (value);
};
/**
* Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.
* @param {*} value The value to check.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @return {!Function} The value, guaranteed to be a function when asserts
* enabled.
* @throws {goog.asserts.AssertionError} When the value is not a function.
*/
goog.asserts.assertFunction = function(value, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {
goog.asserts.doAssertFailure_('Expected function but got %s: %s.',
[goog.typeOf(value), value], opt_message,
Array.prototype.slice.call(arguments, 2));
}
return /** @type {!Function} */ (value);
};
/**
* Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.
* @param {*} value The value to check.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @return {!Object} The value, guaranteed to be a non-null object.
* @throws {goog.asserts.AssertionError} When the value is not an object.
*/
goog.asserts.assertObject = function(value, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {
goog.asserts.doAssertFailure_('Expected object but got %s: %s.',
[goog.typeOf(value), value],
opt_message, Array.prototype.slice.call(arguments, 2));
}
return /** @type {!Object} */ (value);
};
/**
* Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.
* @param {*} value The value to check.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @return {!Array} The value, guaranteed to be a non-null array.
* @throws {goog.asserts.AssertionError} When the value is not an array.
*/
goog.asserts.assertArray = function(value, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) {
goog.asserts.doAssertFailure_('Expected array but got %s: %s.',
[goog.typeOf(value), value], opt_message,
Array.prototype.slice.call(arguments, 2));
}
return /** @type {!Array} */ (value);
};
/**
* Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.
* @param {*} value The value to check.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @return {boolean} The value, guaranteed to be a boolean when asserts are
* enabled.
* @throws {goog.asserts.AssertionError} When the value is not a boolean.
*/
goog.asserts.assertBoolean = function(value, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) {
goog.asserts.doAssertFailure_('Expected boolean but got %s: %s.',
[goog.typeOf(value), value], opt_message,
Array.prototype.slice.call(arguments, 2));
}
return /** @type {boolean} */ (value);
};
/**
* Checks if the value is an instance of the user-defined type if
* goog.asserts.ENABLE_ASSERTS is true.
*
* The compiler may tighten the type returned by this function.
*
* @param {*} value The value to check.
* @param {!Function} type A user-defined constructor.
* @param {string=} opt_message Error message in case of failure.
* @param {...*} var_args The items to substitute into the failure message.
* @throws {goog.asserts.AssertionError} When the value is not an instance of
* type.
* @return {!Object}
*/
goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {
if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {
goog.asserts.doAssertFailure_('instanceof check failed.', null,
opt_message, Array.prototype.slice.call(arguments, 3));
}
return /** @type {!Object} */(value);
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview WARNING: DEPRECATED. Use Mat3 instead.
* Implements 3x3 matrices and their related functions which are
* compatible with WebGL. The API is structured to avoid unnecessary memory
* allocations. The last parameter will typically be the output vector and
* an object can be both an input and output parameter to all methods except
* where noted. Matrix operations follow the mathematical form when multiplying
* vectors as follows: resultVec = matrix * vec.
*
*/
goog.provide('goog.vec.Matrix3');
goog.require('goog.vec');
/**
* @typedef {goog.vec.ArrayType}
*/
goog.vec.Matrix3.Type;
/**
* Creates the array representation of a 3x3 matrix. The use of the array
* directly eliminates any overhead associated with the class representation
* defined above. The returned matrix is cleared to all zeros.
*
* @return {goog.vec.Matrix3.Type} The new, nine element array.
*/
goog.vec.Matrix3.create = function() {
return new Float32Array(9);
};
/**
* Creates the array representation of a 3x3 matrix. The use of the array
* directly eliminates any overhead associated with the class representation
* defined above. The returned matrix is initialized with the identity.
*
* @return {goog.vec.Matrix3.Type} The new, nine element array.
*/
goog.vec.Matrix3.createIdentity = function() {
var mat = goog.vec.Matrix3.create();
mat[0] = mat[4] = mat[8] = 1;
return mat;
};
/**
* Creates a 3x3 matrix initialized from the given array.
*
* @param {goog.vec.ArrayType} matrix The array containing the
* matrix values in column major order.
* @return {goog.vec.Matrix3.Type} The new, nine element array.
*/
goog.vec.Matrix3.createFromArray = function(matrix) {
var newMatrix = goog.vec.Matrix3.create();
goog.vec.Matrix3.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 3x3 matrix initialized from the given values.
*
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @return {goog.vec.Matrix3.Type} The new, nine element array.
*/
goog.vec.Matrix3.createFromValues = function(
v00, v10, v20, v01, v11, v21, v02, v12, v22) {
var newMatrix = goog.vec.Matrix3.create();
goog.vec.Matrix3.setFromValues(
newMatrix, v00, v10, v20, v01, v11, v21, v02, v12, v22);
return newMatrix;
};
/**
* Creates a clone of a 3x3 matrix.
*
* @param {goog.vec.Matrix3.Type} matrix The source 3x3 matrix.
* @return {goog.vec.Matrix3.Type} The new 3x3 element matrix.
*/
goog.vec.Matrix3.clone =
goog.vec.Matrix3.createFromArray;
/**
* Retrieves the element at the requested row and column.
*
* @param {goog.vec.ArrayType} mat The matrix containing the
* value to retrieve.
* @param {number} row The row index.
* @param {number} column The column index.
* @return {number} The element value at the requested row, column indices.
*/
goog.vec.Matrix3.getElement = function(mat, row, column) {
return mat[row + column * 3];
};
/**
* Sets the element at the requested row and column.
*
* @param {goog.vec.ArrayType} mat The matrix containing the
* value to retrieve.
* @param {number} row The row index.
* @param {number} column The column index.
* @param {number} value The value to set at the requested row, column.
*/
goog.vec.Matrix3.setElement = function(mat, row, column, value) {
mat[row + column * 3] = value;
};
/**
* Initializes the matrix from the set of values. Note the values supplied are
* in column major order.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
*/
goog.vec.Matrix3.setFromValues = function(
mat, v00, v10, v20, v01, v11, v21, v02, v12, v22) {
mat[0] = v00;
mat[1] = v10;
mat[2] = v20;
mat[3] = v01;
mat[4] = v11;
mat[5] = v21;
mat[6] = v02;
mat[7] = v12;
mat[8] = v22;
};
/**
* Sets the matrix from the array of values stored in column major order.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} values The column major ordered
* array of values to store in the matrix.
*/
goog.vec.Matrix3.setFromArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[1];
mat[2] = values[2];
mat[3] = values[3];
mat[4] = values[4];
mat[5] = values[5];
mat[6] = values[6];
mat[7] = values[7];
mat[8] = values[8];
};
/**
* Sets the matrix from the array of values stored in row major order.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} values The row major ordered array
* of values to store in the matrix.
*/
goog.vec.Matrix3.setFromRowMajorArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[3];
mat[2] = values[6];
mat[3] = values[1];
mat[4] = values[4];
mat[5] = values[7];
mat[6] = values[2];
mat[7] = values[5];
mat[8] = values[8];
};
/**
* Sets the diagonal values of the matrix from the given values.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} v00 The values for (0, 0).
* @param {number} v11 The values for (1, 1).
* @param {number} v22 The values for (2, 2).
*/
goog.vec.Matrix3.setDiagonalValues = function(mat, v00, v11, v22) {
mat[0] = v00;
mat[4] = v11;
mat[8] = v22;
};
/**
* Sets the diagonal values of the matrix from the given vector.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} vec The vector containing the
* values.
*/
goog.vec.Matrix3.setDiagonal = function(mat, vec) {
mat[0] = vec[0];
mat[4] = vec[1];
mat[8] = vec[2];
};
/**
* Sets the specified column with the supplied values.
*
* @param {goog.vec.ArrayType} mat The matrix to recieve the
* values.
* @param {number} column The column index to set the values on.
* @param {number} v0 The value for row 0.
* @param {number} v1 The value for row 1.
* @param {number} v2 The value for row 2.
*/
goog.vec.Matrix3.setColumnValues = function(
mat, column, v0, v1, v2) {
var i = column * 3;
mat[i] = v0;
mat[i + 1] = v1;
mat[i + 2] = v2;
};
/**
* Sets the specified column with the value from the supplied array.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} column The column index to set the values on.
* @param {goog.vec.ArrayType} vec The vector elements for the
* column.
*/
goog.vec.Matrix3.setColumn = function(mat, column, vec) {
var i = column * 3;
mat[i] = vec[0];
mat[i + 1] = vec[1];
mat[i + 2] = vec[2];
};
/**
* Retrieves the specified column from the matrix into the given vector
* array.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* values.
* @param {number} column The column to get the values from.
* @param {goog.vec.ArrayType} vec The vector elements to receive
* the column.
*/
goog.vec.Matrix3.getColumn = function(mat, column, vec) {
var i = column * 3;
vec[0] = mat[i];
vec[1] = mat[i + 1];
vec[2] = mat[i + 2];
};
/**
* Sets the columns of the matrix from the set of vector elements.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} vec0 The values for column 0.
* @param {goog.vec.ArrayType} vec1 The values for column 1.
* @param {goog.vec.ArrayType} vec2 The values for column 2.
*/
goog.vec.Matrix3.setColumns = function(
mat, vec0, vec1, vec2) {
goog.vec.Matrix3.setColumn(mat, 0, vec0);
goog.vec.Matrix3.setColumn(mat, 1, vec1);
goog.vec.Matrix3.setColumn(mat, 2, vec2);
};
/**
* Retrieves the column values from the given matrix into the given vector
* elements.
*
* @param {goog.vec.ArrayType} mat The matrix containing the
* columns to retrieve.
* @param {goog.vec.ArrayType} vec0 The vector elements to receive
* column 0.
* @param {goog.vec.ArrayType} vec1 The vector elements to receive
* column 1.
* @param {goog.vec.ArrayType} vec2 The vector elements to receive
* column 2.
*/
goog.vec.Matrix3.getColumns = function(
mat, vec0, vec1, vec2) {
goog.vec.Matrix3.getColumn(mat, 0, vec0);
goog.vec.Matrix3.getColumn(mat, 1, vec1);
goog.vec.Matrix3.getColumn(mat, 2, vec2);
};
/**
* Sets the row values from the supplied values.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} row The index of the row to receive the values.
* @param {number} v0 The value for column 0.
* @param {number} v1 The value for column 1.
* @param {number} v2 The value for column 2.
*/
goog.vec.Matrix3.setRowValues = function(mat, row, v0, v1, v2) {
mat[row] = v0;
mat[row + 3] = v1;
mat[row + 6] = v2;
};
/**
* Sets the row values from the supplied vector.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* row values.
* @param {number} row The index of the row.
* @param {goog.vec.ArrayType} vec The vector containing the values.
*/
goog.vec.Matrix3.setRow = function(mat, row, vec) {
mat[row] = vec[0];
mat[row + 3] = vec[1];
mat[row + 6] = vec[2];
};
/**
* Retrieves the row values into the given vector.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* values.
* @param {number} row The index of the row supplying the values.
* @param {goog.vec.ArrayType} vec The vector to receive the row.
*/
goog.vec.Matrix3.getRow = function(mat, row, vec) {
vec[0] = mat[row];
vec[1] = mat[row + 3];
vec[2] = mat[row + 6];
};
/**
* Sets the rows of the matrix from the supplied vectors.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} vec0 The values for row 0.
* @param {goog.vec.ArrayType} vec1 The values for row 1.
* @param {goog.vec.ArrayType} vec2 The values for row 2.
*/
goog.vec.Matrix3.setRows = function(
mat, vec0, vec1, vec2) {
goog.vec.Matrix3.setRow(mat, 0, vec0);
goog.vec.Matrix3.setRow(mat, 1, vec1);
goog.vec.Matrix3.setRow(mat, 2, vec2);
};
/**
* Retrieves the rows of the matrix into the supplied vectors.
*
* @param {goog.vec.ArrayType} mat The matrix to supplying
* the values.
* @param {goog.vec.ArrayType} vec0 The vector to receive row 0.
* @param {goog.vec.ArrayType} vec1 The vector to receive row 1.
* @param {goog.vec.ArrayType} vec2 The vector to receive row 2.
*/
goog.vec.Matrix3.getRows = function(
mat, vec0, vec1, vec2) {
goog.vec.Matrix3.getRow(mat, 0, vec0);
goog.vec.Matrix3.getRow(mat, 1, vec1);
goog.vec.Matrix3.getRow(mat, 2, vec2);
};
/**
* Clears the given matrix to zero.
*
* @param {goog.vec.ArrayType} mat The matrix to clear.
*/
goog.vec.Matrix3.setZero = function(mat) {
mat[0] = 0;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 0;
mat[5] = 0;
mat[6] = 0;
mat[7] = 0;
mat[8] = 0;
};
/**
* Sets the given matrix to the identity matrix.
*
* @param {goog.vec.ArrayType} mat The matrix to set.
*/
goog.vec.Matrix3.setIdentity = function(mat) {
mat[0] = 1;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 1;
mat[5] = 0;
mat[6] = 0;
mat[7] = 0;
mat[8] = 1;
};
/**
* Performs a per-component addition of the matrices mat0 and mat1, storing
* the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The first addend.
* @param {goog.vec.ArrayType} mat1 The second addend.
* @param {goog.vec.ArrayType} resultMat The matrix to
* receive the results (may be either mat0 or mat1).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix3.add = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] + mat1[0];
resultMat[1] = mat0[1] + mat1[1];
resultMat[2] = mat0[2] + mat1[2];
resultMat[3] = mat0[3] + mat1[3];
resultMat[4] = mat0[4] + mat1[4];
resultMat[5] = mat0[5] + mat1[5];
resultMat[6] = mat0[6] + mat1[6];
resultMat[7] = mat0[7] + mat1[7];
resultMat[8] = mat0[8] + mat1[8];
return resultMat;
};
/**
* Performs a per-component subtraction of the matrices mat0 and mat1,
* storing the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The minuend.
* @param {goog.vec.ArrayType} mat1 The subtrahend.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix3.subtract = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] - mat1[0];
resultMat[1] = mat0[1] - mat1[1];
resultMat[2] = mat0[2] - mat1[2];
resultMat[3] = mat0[3] - mat1[3];
resultMat[4] = mat0[4] - mat1[4];
resultMat[5] = mat0[5] - mat1[5];
resultMat[6] = mat0[6] - mat1[6];
resultMat[7] = mat0[7] - mat1[7];
resultMat[8] = mat0[8] - mat1[8];
return resultMat;
};
/**
* Performs a component-wise multiplication of mat0 with the given scalar
* storing the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The matrix to scale.
* @param {number} scalar The scalar value to multiple to each element of mat0.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be mat0).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix3.scale = function(mat0, scalar, resultMat) {
resultMat[0] = mat0[0] * scalar;
resultMat[1] = mat0[1] * scalar;
resultMat[2] = mat0[2] * scalar;
resultMat[3] = mat0[3] * scalar;
resultMat[4] = mat0[4] * scalar;
resultMat[5] = mat0[5] * scalar;
resultMat[6] = mat0[6] * scalar;
resultMat[7] = mat0[7] * scalar;
resultMat[8] = mat0[8] * scalar;
return resultMat;
};
/**
* Multiplies the two matrices mat0 and mat1 using matrix multiplication,
* storing the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The first (left hand) matrix.
* @param {goog.vec.ArrayType} mat1 The second (right hand)
* matrix.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix3.multMat = function(mat0, mat1, resultMat) {
var a00 = mat0[0], a10 = mat0[1], a20 = mat0[2];
var a01 = mat0[3], a11 = mat0[4], a21 = mat0[5];
var a02 = mat0[6], a12 = mat0[7], a22 = mat0[8];
var b00 = mat1[0], b10 = mat1[1], b20 = mat1[2];
var b01 = mat1[3], b11 = mat1[4], b21 = mat1[5];
var b02 = mat1[6], b12 = mat1[7], b22 = mat1[8];
resultMat[0] = a00 * b00 + a01 * b10 + a02 * b20;
resultMat[1] = a10 * b00 + a11 * b10 + a12 * b20;
resultMat[2] = a20 * b00 + a21 * b10 + a22 * b20;
resultMat[3] = a00 * b01 + a01 * b11 + a02 * b21;
resultMat[4] = a10 * b01 + a11 * b11 + a12 * b21;
resultMat[5] = a20 * b01 + a21 * b11 + a22 * b21;
resultMat[6] = a00 * b02 + a01 * b12 + a02 * b22;
resultMat[7] = a10 * b02 + a11 * b12 + a12 * b22;
resultMat[8] = a20 * b02 + a21 * b12 + a22 * b22;
return resultMat;
};
/**
* Transposes the given matrix mat storing the result into resultMat.
* @param {goog.vec.ArrayType} mat The matrix to transpose.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be mat).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix3.transpose = function(mat, resultMat) {
if (resultMat == mat) {
var a10 = mat[1], a20 = mat[2], a21 = mat[5];
resultMat[1] = mat[3];
resultMat[2] = mat[6];
resultMat[3] = a10;
resultMat[5] = mat[7];
resultMat[6] = a20;
resultMat[7] = a21;
} else {
resultMat[0] = mat[0];
resultMat[1] = mat[3];
resultMat[2] = mat[6];
resultMat[3] = mat[1];
resultMat[4] = mat[4];
resultMat[5] = mat[7];
resultMat[6] = mat[2];
resultMat[7] = mat[5];
resultMat[8] = mat[8];
}
return resultMat;
};
/**
* Computes the inverse of mat0 storing the result into resultMat. If the
* inverse is defined, this function returns true, false otherwise.
* @param {goog.vec.ArrayType} mat0 The matrix to invert.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the result (may be mat0).
* @return {boolean} True if the inverse is defined. If false is returned,
* resultMat is not modified.
*/
goog.vec.Matrix3.invert = function(mat0, resultMat) {
var a00 = mat0[0], a10 = mat0[1], a20 = mat0[2];
var a01 = mat0[3], a11 = mat0[4], a21 = mat0[5];
var a02 = mat0[6], a12 = mat0[7], a22 = mat0[8];
var t00 = a11 * a22 - a12 * a21;
var t10 = a12 * a20 - a10 * a22;
var t20 = a10 * a21 - a11 * a20;
var det = a00 * t00 + a01 * t10 + a02 * t20;
if (det == 0) {
return false;
}
var idet = 1 / det;
resultMat[0] = t00 * idet;
resultMat[3] = (a02 * a21 - a01 * a22) * idet;
resultMat[6] = (a01 * a12 - a02 * a11) * idet;
resultMat[1] = t10 * idet;
resultMat[4] = (a00 * a22 - a02 * a20) * idet;
resultMat[7] = (a02 * a10 - a00 * a12) * idet;
resultMat[2] = t20 * idet;
resultMat[5] = (a01 * a20 - a00 * a21) * idet;
resultMat[8] = (a00 * a11 - a01 * a10) * idet;
return true;
};
/**
* Returns true if the components of mat0 are equal to the components of mat1.
*
* @param {goog.vec.ArrayType} mat0 The first matrix.
* @param {goog.vec.ArrayType} mat1 The second matrix.
* @return {boolean} True if the the two matrices are equivalent.
*/
goog.vec.Matrix3.equals = function(mat0, mat1) {
return mat0.length == mat1.length &&
mat0[0] == mat1[0] && mat0[1] == mat1[1] && mat0[2] == mat1[2] &&
mat0[3] == mat1[3] && mat0[4] == mat1[4] && mat0[5] == mat1[5] &&
mat0[6] == mat1[6] && mat0[7] == mat1[7] && mat0[8] == mat1[8];
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed matrix into resultVec.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* transformation.
* @param {goog.vec.ArrayType} vec The vector to transform.
* @param {goog.vec.ArrayType} resultVec The vector to
* receive the results (may be vec).
* @return {goog.vec.ArrayType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Matrix3.multVec3 = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
resultVec[0] = x * mat[0] + y * mat[3] + z * mat[6];
resultVec[1] = x * mat[1] + y * mat[4] + z * mat[7];
resultVec[2] = x * mat[2] + y * mat[5] + z * mat[8];
return resultVec;
};
/**
* Initializes the given 3x3 matrix as a translation matrix with x and y
* translation values.
*
* @param {goog.vec.ArrayType} mat The 3x3 (9-element) matrix
* array to receive the new translation matrix.
* @param {number} x The translation along the x axis.
* @param {number} y The translation along the y axis.
*/
goog.vec.Matrix3.makeTranslate = function(mat, x, y) {
goog.vec.Matrix3.setIdentity(mat);
goog.vec.Matrix3.setColumnValues(mat, 2, x, y, 1);
};
/**
* Initializes the given 3x3 matrix as a scale matrix with x, y and z scale
* factors.
* @param {goog.vec.ArrayType} mat The 3x3 (9-element) matrix
* array to receive the new scale matrix.
* @param {number} x The scale along the x axis.
* @param {number} y The scale along the y axis.
* @param {number} z The scale along the z axis.
*/
goog.vec.Matrix3.makeScale = function(mat, x, y, z) {
goog.vec.Matrix3.setIdentity(mat);
goog.vec.Matrix3.setDiagonalValues(mat, x, y, z);
};
/**
* Initializes the given 3x3 matrix as a rotation matrix with the given rotation
* angle about the axis defined by the vector (ax, ay, az).
* @param {goog.vec.ArrayType} mat The 3x3 (9-element) matrix
* array to receive the new scale matrix.
* @param {number} angle The rotation angle in radians.
* @param {number} ax The x component of the rotation axis.
* @param {number} ay The y component of the rotation axis.
* @param {number} az The z component of the rotation axis.
*/
goog.vec.Matrix3.makeAxisAngleRotate = function(
mat, angle, ax, ay, az) {
var c = Math.cos(angle);
var d = 1 - c;
var s = Math.sin(angle);
goog.vec.Matrix3.setFromValues(mat,
ax * ax * d + c,
ax * ay * d + az * s,
ax * az * d - ay * s,
ax * ay * d - az * s,
ay * ay * d + c,
ay * az * d + ax * s,
ax * az * d + ay * s,
ay * az * d - ax * s,
az * az * d + c);
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Supplies 3 element vectors that are compatible with WebGL.
* Each element is a float32 since that is typically the desired size of a
* 3-vector in the GPU. The API is structured to avoid unnecessary memory
* allocations. The last parameter will typically be the output vector and
* an object can be both an input and output parameter to all methods except
* where noted.
*
*/
goog.provide('goog.vec.Vec3');
goog.require('goog.vec');
/** @typedef {goog.vec.Float32} */ goog.vec.Vec3.Float32;
/** @typedef {goog.vec.Float64} */ goog.vec.Vec3.Float64;
/** @typedef {goog.vec.Number} */ goog.vec.Vec3.Number;
/** @typedef {goog.vec.AnyType} */ goog.vec.Vec3.AnyType;
// The following two types are deprecated - use the above types instead.
/** @typedef {Float32Array} */ goog.vec.Vec3.Type;
/** @typedef {goog.vec.ArrayType} */ goog.vec.Vec3.Vec3Like;
/**
* Creates a 3 element vector of Float32. The array is initialized to zero.
*
* @return {!goog.vec.Vec3.Float32} The new 3 element array.
*/
goog.vec.Vec3.createFloat32 = function() {
return new Float32Array(3);
};
/**
* Creates a 3 element vector of Float64. The array is initialized to zero.
*
* @return {!goog.vec.Vec3.Float64} The new 3 element array.
*/
goog.vec.Vec3.createFloat64 = function() {
return new Float64Array(3);
};
/**
* Creates a 3 element vector of Number. The array is initialized to zero.
*
* @return {!goog.vec.Vec3.Number} The new 3 element array.
*/
goog.vec.Vec3.createNumber = function() {
var a = new Array(3);
goog.vec.Vec3.setFromValues(a, 0, 0, 0);
return a;
};
/**
* Creates a 3 element vector of Float32Array. The array is initialized to zero.
*
* @deprecated Use createFloat32.
* @return {!goog.vec.Vec3.Type} The new 3 element array.
*/
goog.vec.Vec3.create = function() {
return new Float32Array(3);
};
/**
* Creates a new 3 element FLoat32 vector initialized with the value from the
* given array.
*
* @param {goog.vec.Vec3.AnyType} vec The source 3 element array.
* @return {!goog.vec.Vec3.Float32} The new 3 element array.
*/
goog.vec.Vec3.createFloat32FromArray = function(vec) {
var newVec = goog.vec.Vec3.createFloat32();
goog.vec.Vec3.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 3 element Float32 vector initialized with the supplied values.
*
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @return {!goog.vec.Vec3.Float32} The new vector.
*/
goog.vec.Vec3.createFloat32FromValues = function(v0, v1, v2) {
var a = goog.vec.Vec3.createFloat32();
goog.vec.Vec3.setFromValues(a, v0, v1, v2);
return a;
};
/**
* Creates a clone of the given 3 element Float32 vector.
*
* @param {goog.vec.Vec3.Float32} vec The source 3 element vector.
* @return {!goog.vec.Vec3.Float32} The new cloned vector.
*/
goog.vec.Vec3.cloneFloat32 = goog.vec.Vec3.createFloat32FromArray;
/**
* Creates a new 3 element Float64 vector initialized with the value from the
* given array.
*
* @param {goog.vec.Vec3.AnyType} vec The source 3 element array.
* @return {!goog.vec.Vec3.Float64} The new 3 element array.
*/
goog.vec.Vec3.createFloat64FromArray = function(vec) {
var newVec = goog.vec.Vec3.createFloat64();
goog.vec.Vec3.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 3 element Float64 vector initialized with the supplied values.
*
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @return {!goog.vec.Vec3.Float64} The new vector.
*/
goog.vec.Vec3.createFloat64FromValues = function(v0, v1, v2) {
var vec = goog.vec.Vec3.createFloat64();
goog.vec.Vec3.setFromValues(vec, v0, v1, v2);
return vec;
};
/**
* Creates a clone of the given 3 element vector.
*
* @param {goog.vec.Vec3.Float64} vec The source 3 element vector.
* @return {!goog.vec.Vec3.Float64} The new cloned vector.
*/
goog.vec.Vec3.cloneFloat64 = goog.vec.Vec3.createFloat64FromArray;
/**
* Creates a new 3 element vector initialized with the value from the given
* array.
*
* @deprecated Use createFloat32FromArray.
* @param {goog.vec.Vec3.Vec3Like} vec The source 3 element array.
* @return {!goog.vec.Vec3.Type} The new 3 element array.
*/
goog.vec.Vec3.createFromArray = function(vec) {
var newVec = goog.vec.Vec3.create();
goog.vec.Vec3.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 3 element vector initialized with the supplied values.
*
* @deprecated Use createFloat32FromValues.
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @return {!goog.vec.Vec3.Type} The new vector.
*/
goog.vec.Vec3.createFromValues = function(v0, v1, v2) {
var vec = goog.vec.Vec3.create();
goog.vec.Vec3.setFromValues(vec, v0, v1, v2);
return vec;
};
/**
* Creates a clone of the given 3 element vector.
*
* @deprecated Use cloneFloat32.
* @param {goog.vec.Vec3.Vec3Like} vec The source 3 element vector.
* @return {!goog.vec.Vec3.Type} The new cloned vector.
*/
goog.vec.Vec3.clone = function(vec) {
var newVec = goog.vec.Vec3.create();
goog.vec.Vec3.setFromArray(newVec, vec);
return newVec;
};
/**
* Initializes the vector with the given values.
*
* @param {goog.vec.Vec3.AnyType} vec The vector to receive the values.
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @return {!goog.vec.Vec3.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Vec3.setFromValues = function(vec, v0, v1, v2) {
vec[0] = v0;
vec[1] = v1;
vec[2] = v2;
return vec;
};
/**
* Initializes the vector with the given array of values.
*
* @param {goog.vec.Vec3.AnyType} vec The vector to receive the
* values.
* @param {goog.vec.Vec3.AnyType} values The array of values.
* @return {!goog.vec.Vec3.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Vec3.setFromArray = function(vec, values) {
vec[0] = values[0];
vec[1] = values[1];
vec[2] = values[2];
return vec;
};
/**
* Performs a component-wise addition of vec0 and vec1 together storing the
* result into resultVec.
*
* @param {goog.vec.Vec3.AnyType} vec0 The first addend.
* @param {goog.vec.Vec3.AnyType} vec1 The second addend.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to
* receive the result. May be vec0 or vec1.
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.add = function(vec0, vec1, resultVec) {
resultVec[0] = vec0[0] + vec1[0];
resultVec[1] = vec0[1] + vec1[1];
resultVec[2] = vec0[2] + vec1[2];
return resultVec;
};
/**
* Performs a component-wise subtraction of vec1 from vec0 storing the
* result into resultVec.
*
* @param {goog.vec.Vec3.AnyType} vec0 The minuend.
* @param {goog.vec.Vec3.AnyType} vec1 The subtrahend.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to
* receive the result. May be vec0 or vec1.
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.subtract = function(vec0, vec1, resultVec) {
resultVec[0] = vec0[0] - vec1[0];
resultVec[1] = vec0[1] - vec1[1];
resultVec[2] = vec0[2] - vec1[2];
return resultVec;
};
/**
* Negates vec0, storing the result into resultVec.
*
* @param {goog.vec.Vec3.AnyType} vec0 The vector to negate.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.negate = function(vec0, resultVec) {
resultVec[0] = -vec0[0];
resultVec[1] = -vec0[1];
resultVec[2] = -vec0[2];
return resultVec;
};
/**
* Multiplies each component of vec0 with scalar storing the product into
* resultVec.
*
* @param {goog.vec.Vec3.AnyType} vec0 The source vector.
* @param {number} scalar The value to multiply with each component of vec0.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.scale = function(vec0, scalar, resultVec) {
resultVec[0] = vec0[0] * scalar;
resultVec[1] = vec0[1] * scalar;
resultVec[2] = vec0[2] * scalar;
return resultVec;
};
/**
* Returns the magnitudeSquared of the given vector.
*
* @param {goog.vec.Vec3.AnyType} vec0 The vector.
* @return {number} The magnitude of the vector.
*/
goog.vec.Vec3.magnitudeSquared = function(vec0) {
var x = vec0[0], y = vec0[1], z = vec0[2];
return x * x + y * y + z * z;
};
/**
* Returns the magnitude of the given vector.
*
* @param {goog.vec.Vec3.AnyType} vec0 The vector.
* @return {number} The magnitude of the vector.
*/
goog.vec.Vec3.magnitude = function(vec0) {
var x = vec0[0], y = vec0[1], z = vec0[2];
return Math.sqrt(x * x + y * y + z * z);
};
/**
* Normalizes the given vector storing the result into resultVec.
*
* @param {goog.vec.Vec3.AnyType} vec0 The vector to normalize.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.normalize = function(vec0, resultVec) {
var ilen = 1 / goog.vec.Vec3.magnitude(vec0);
resultVec[0] = vec0[0] * ilen;
resultVec[1] = vec0[1] * ilen;
resultVec[2] = vec0[2] * ilen;
return resultVec;
};
/**
* Returns the scalar product of vectors v0 and v1.
*
* @param {goog.vec.Vec3.AnyType} v0 The first vector.
* @param {goog.vec.Vec3.AnyType} v1 The second vector.
* @return {number} The scalar product.
*/
goog.vec.Vec3.dot = function(v0, v1) {
return v0[0] * v1[0] + v0[1] * v1[1] + v0[2] * v1[2];
};
/**
* Computes the vector (cross) product of v0 and v1 storing the result into
* resultVec.
*
* @param {goog.vec.Vec3.AnyType} v0 The first vector.
* @param {goog.vec.Vec3.AnyType} v1 The second vector.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
* results. May be either v0 or v1.
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.cross = function(v0, v1, resultVec) {
var x0 = v0[0], y0 = v0[1], z0 = v0[2];
var x1 = v1[0], y1 = v1[1], z1 = v1[2];
resultVec[0] = y0 * z1 - z0 * y1;
resultVec[1] = z0 * x1 - x0 * z1;
resultVec[2] = x0 * y1 - y0 * x1;
return resultVec;
};
/**
* Returns the squared distance between two points.
*
* @param {goog.vec.Vec3.AnyType} vec0 First point.
* @param {goog.vec.Vec3.AnyType} vec1 Second point.
* @return {number} The squared distance between the points.
*/
goog.vec.Vec3.distanceSquared = function(vec0, vec1) {
var x = vec0[0] - vec1[0];
var y = vec0[1] - vec1[1];
var z = vec0[2] - vec1[2];
return x * x + y * y + z * z;
};
/**
* Returns the distance between two points.
*
* @param {goog.vec.Vec3.AnyType} vec0 First point.
* @param {goog.vec.Vec3.AnyType} vec1 Second point.
* @return {number} The distance between the points.
*/
goog.vec.Vec3.distance = function(vec0, vec1) {
return Math.sqrt(goog.vec.Vec3.distanceSquared(vec0, vec1));
};
/**
* Returns a unit vector pointing from one point to another.
* If the input points are equal then the result will be all zeros.
*
* @param {goog.vec.Vec3.AnyType} vec0 Origin point.
* @param {goog.vec.Vec3.AnyType} vec1 Target point.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
* results (may be vec0 or vec1).
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.direction = function(vec0, vec1, resultVec) {
var x = vec1[0] - vec0[0];
var y = vec1[1] - vec0[1];
var z = vec1[2] - vec0[2];
var d = Math.sqrt(x * x + y * y + z * z);
if (d) {
d = 1 / d;
resultVec[0] = x * d;
resultVec[1] = y * d;
resultVec[2] = z * d;
} else {
resultVec[0] = resultVec[1] = resultVec[2] = 0;
}
return resultVec;
};
/**
* Linearly interpolate from vec0 to v1 according to f. The value of f should be
* in the range [0..1] otherwise the results are undefined.
*
* @param {goog.vec.Vec3.AnyType} v0 The first vector.
* @param {goog.vec.Vec3.AnyType} v1 The second vector.
* @param {number} f The interpolation factor.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
* results (may be v0 or v1).
* @return {!goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec3.lerp = function(v0, v1, f, resultVec) {
var x = v0[0], y = v0[1], z = v0[2];
resultVec[0] = (v1[0] - x) * f + x;
resultVec[1] = (v1[1] - y) * f + y;
resultVec[2] = (v1[2] - z) * f + z;
return resultVec;
};
/**
* Returns true if the components of v0 are equal to the components of v1.
*
* @param {goog.vec.Vec3.AnyType} v0 The first vector.
* @param {goog.vec.Vec3.AnyType} v1 The second vector.
* @return {boolean} True if the vectors are equal, false otherwise.
*/
goog.vec.Vec3.equals = function(v0, v1) {
return v0.length == v1.length &&
v0[0] == v1[0] && v0[1] == v1[1] && v0[2] == v1[2];
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Supplies a Float64Array implementation that implements
* most of the Float64Array spec and that can be used when a built-in
* implementation is not available.
*
* Note that if no existing Float64Array implementation is found then this
* class and all its public properties are exported as Float64Array.
*
* Adding support for the other TypedArray classes here does not make sense
* since this vector math library only needs Float32Array and Float64Array.
*
*/
goog.provide('goog.vec.Float64Array');
/**
* Constructs a new Float64Array. The new array is initialized to all zeros.
*
* @param {goog.vec.Float64Array|Array|ArrayBuffer|number} p0
* The length of the array, or an array to initialize the contents of the
* new Float64Array.
* @constructor
*/
goog.vec.Float64Array = function(p0) {
this.length = p0.length || p0;
for (var i = 0; i < this.length; i++) {
this[i] = p0[i] || 0;
}
};
/**
* The number of bytes in an element (as defined by the Typed Array
* specification).
*
* @type {number}
*/
goog.vec.Float64Array.BYTES_PER_ELEMENT = 8;
/**
* The number of bytes in an element (as defined by the Typed Array
* specification).
*
* @type {number}
*/
goog.vec.Float64Array.prototype.BYTES_PER_ELEMENT = 8;
/**
* Sets elements of the array.
* @param {Array.<number>|Float64Array} values The array of values.
* @param {number=} opt_offset The offset in this array to start.
*/
goog.vec.Float64Array.prototype.set = function(values, opt_offset) {
opt_offset = opt_offset || 0;
for (var i = 0; i < values.length && opt_offset + i < this.length; i++) {
this[opt_offset + i] = values[i];
}
};
/**
* Creates a string representation of this array.
* @return {string} The string version of this array.
* @override
*/
goog.vec.Float64Array.prototype.toString = Array.prototype.join;
/**
* Note that we cannot implement the subarray() or (deprecated) slice()
* methods properly since doing so would require being able to overload
* the [] operator which is not possible in javascript. So we leave
* them unimplemented. Any attempt to call these methods will just result
* in a javascript error since we leave them undefined.
*/
/**
* If no existing Float64Array implementation is found then we export
* goog.vec.Float64Array as Float64Array.
*/
if (typeof Float64Array == 'undefined') {
try {
goog.exportProperty(goog.vec.Float64Array, 'BYTES_PER_ELEMENT',
goog.vec.Float64Array.BYTES_PER_ELEMENT);
} catch (float64ArrayError) {
// Do nothing. This code is in place to fix b/7225850, in which an error
// is incorrectly thrown for Google TV on an old Chrome.
// TODO(user): remove after that version is retired.
}
goog.exportProperty(goog.vec.Float64Array.prototype, 'BYTES_PER_ELEMENT',
goog.vec.Float64Array.prototype.BYTES_PER_ELEMENT);
goog.exportProperty(goog.vec.Float64Array.prototype, 'set',
goog.vec.Float64Array.prototype.set);
goog.exportProperty(goog.vec.Float64Array.prototype, 'toString',
goog.vec.Float64Array.prototype.toString);
goog.exportSymbol('Float64Array', goog.vec.Float64Array);
}
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Implements 3x3 matrices and their related functions which are
* compatible with WebGL. The API is structured to avoid unnecessary memory
* allocations. The last parameter will typically be the output vector and
* an object can be both an input and output parameter to all methods except
* where noted. Matrix operations follow the mathematical form when multiplying
* vectors as follows: resultVec = matrix * vec.
*
* The matrices are stored in column-major order.
*
*/
goog.provide('goog.vec.Mat3');
goog.require('goog.vec');
goog.require('goog.vec.Vec3');
/** @typedef {goog.vec.Float32} */ goog.vec.Mat3.Float32;
/** @typedef {goog.vec.Float64} */ goog.vec.Mat3.Float64;
/** @typedef {goog.vec.Number} */ goog.vec.Mat3.Number;
/** @typedef {goog.vec.AnyType} */ goog.vec.Mat3.AnyType;
// The following two types are deprecated - use the above types instead.
/** @typedef {Float32Array} */ goog.vec.Mat3.Type;
/** @typedef {goog.vec.ArrayType} */ goog.vec.Mat3.Mat3Like;
/**
* Creates the array representation of a 3x3 matrix of Float32.
* The use of the array directly instead of a class reduces overhead.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat3.Float32} The new matrix.
*/
goog.vec.Mat3.createFloat32 = function() {
return new Float32Array(9);
};
/**
* Creates the array representation of a 3x3 matrix of Float64.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat3.Float64} The new matrix.
*/
goog.vec.Mat3.createFloat64 = function() {
return new Float64Array(9);
};
/**
* Creates the array representation of a 3x3 matrix of Number.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat3.Number} The new matrix.
*/
goog.vec.Mat3.createNumber = function() {
var a = new Array(9);
goog.vec.Mat3.setFromValues(a,
0, 0, 0,
0, 0, 0,
0, 0, 0);
return a;
};
/**
* Creates the array representation of a 3x3 matrix of Float32.
* The returned matrix is cleared to all zeros.
*
* @deprecated Use createFloat32.
* @return {!goog.vec.Mat3.Type} The new matrix.
*/
goog.vec.Mat3.create = function() {
return goog.vec.Mat3.createFloat32();
};
/**
* Creates a 3x3 identity matrix of Float32.
*
* @return {!goog.vec.Mat3.Float32} The new 9 element array.
*/
goog.vec.Mat3.createFloat32Identity = function() {
var mat = goog.vec.Mat3.createFloat32();
mat[0] = mat[4] = mat[8] = 1;
return mat;
};
/**
* Creates a 3x3 identity matrix of Float64.
*
* @return {!goog.vec.Mat3.Float64} The new 9 element array.
*/
goog.vec.Mat3.createFloat64Identity = function() {
var mat = goog.vec.Mat3.createFloat64();
mat[0] = mat[4] = mat[8] = 1;
return mat;
};
/**
* Creates a 3x3 identity matrix of Number.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat3.Number} The new 9 element array.
*/
goog.vec.Mat3.createNumberIdentity = function() {
var a = new Array(9);
goog.vec.Mat3.setFromValues(a,
1, 0, 0,
0, 1, 0,
0, 0, 1);
return a;
};
/**
* Creates the array representation of a 3x3 matrix of Float32.
* The returned matrix is cleared to all zeros.
*
* @deprecated Use createFloat32Identity.
* @return {!goog.vec.Mat3.Type} The new 9 element array.
*/
goog.vec.Mat3.createIdentity = function() {
return goog.vec.Mat3.createFloat32Identity();
};
/**
* Creates a 3x3 matrix of Float32 initialized from the given array.
*
* @param {goog.vec.Mat3.AnyType} matrix The array containing the
* matrix values in column major order.
* @return {!goog.vec.Mat3.Float32} The new, nine element array.
*/
goog.vec.Mat3.createFloat32FromArray = function(matrix) {
var newMatrix = goog.vec.Mat3.createFloat32();
goog.vec.Mat3.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 3x3 matrix of Float32 initialized from the given values.
*
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @return {!goog.vec.Mat3.Float32} The new, nine element array.
*/
goog.vec.Mat3.createFloat32FromValues = function(
v00, v10, v20, v01, v11, v21, v02, v12, v22) {
var newMatrix = goog.vec.Mat3.createFloat32();
goog.vec.Mat3.setFromValues(
newMatrix, v00, v10, v20, v01, v11, v21, v02, v12, v22);
return newMatrix;
};
/**
* Creates a clone of a 3x3 matrix of Float32.
*
* @param {goog.vec.Mat3.Float32} matrix The source 3x3 matrix.
* @return {!goog.vec.Mat3.Float32} The new 3x3 element matrix.
*/
goog.vec.Mat3.cloneFloat32 = goog.vec.Mat3.createFloat32FromArray;
/**
* Creates a 3x3 matrix of Float64 initialized from the given array.
*
* @param {goog.vec.Mat3.AnyType} matrix The array containing the
* matrix values in column major order.
* @return {!goog.vec.Mat3.Float64} The new, nine element array.
*/
goog.vec.Mat3.createFloat64FromArray = function(matrix) {
var newMatrix = goog.vec.Mat3.createFloat64();
goog.vec.Mat3.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 3x3 matrix of Float64 initialized from the given values.
*
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @return {!goog.vec.Mat3.Float64} The new, nine element array.
*/
goog.vec.Mat3.createFloat64FromValues = function(
v00, v10, v20, v01, v11, v21, v02, v12, v22) {
var newMatrix = goog.vec.Mat3.createFloat64();
goog.vec.Mat3.setFromValues(
newMatrix, v00, v10, v20, v01, v11, v21, v02, v12, v22);
return newMatrix;
};
/**
* Creates a clone of a 3x3 matrix of Float64.
*
* @param {goog.vec.Mat3.Float64} matrix The source 3x3 matrix.
* @return {!goog.vec.Mat3.Float64} The new 3x3 element matrix.
*/
goog.vec.Mat3.cloneFloat64 = goog.vec.Mat3.createFloat64FromArray;
/**
* Creates a 3x3 matrix of Float32 initialized from the given array.
*
* @deprecated Use createFloat32FromArray.
* @param {goog.vec.Mat3.Mat3Like} matrix The array containing the
* matrix values in column major order.
* @return {!goog.vec.Mat3.Type} The new, nine element array.
*/
goog.vec.Mat3.createFromArray = function(matrix) {
var newMatrix = goog.vec.Mat3.createFloat32();
goog.vec.Mat3.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 3x3 matrix of Float32 initialized from the given values.
*
* @deprecated Use createFloat32FromValues.
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @return {!goog.vec.Mat3.Type} The new, nine element array.
*/
goog.vec.Mat3.createFromValues = function(
v00, v10, v20, v01, v11, v21, v02, v12, v22) {
var newMatrix = goog.vec.Mat3.create();
goog.vec.Mat3.setFromValues(
newMatrix, v00, v10, v20, v01, v11, v21, v02, v12, v22);
return newMatrix;
};
/**
* Creates a clone of a 3x3 matrix of Float32.
*
* @deprecated Use cloneFloat32.
* @param {goog.vec.Mat3.Mat3Like} matrix The source 3x3 matrix.
* @return {!goog.vec.Mat3.Type} The new 3x3 element matrix.
*/
goog.vec.Mat3.clone = goog.vec.Mat3.createFromArray;
/**
* Retrieves the element at the requested row and column.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix containing the value to
* retrieve.
* @param {number} row The row index.
* @param {number} column The column index.
* @return {number} The element value at the requested row, column indices.
*/
goog.vec.Mat3.getElement = function(mat, row, column) {
return mat[row + column * 3];
};
/**
* Sets the element at the requested row and column.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix containing the value to
* retrieve.
* @param {number} row The row index.
* @param {number} column The column index.
* @param {number} value The value to set at the requested row, column.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setElement = function(mat, row, column, value) {
mat[row + column * 3] = value;
return mat;
};
/**
* Initializes the matrix from the set of values. Note the values supplied are
* in column major order.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the
* values.
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setFromValues = function(
mat, v00, v10, v20, v01, v11, v21, v02, v12, v22) {
mat[0] = v00;
mat[1] = v10;
mat[2] = v20;
mat[3] = v01;
mat[4] = v11;
mat[5] = v21;
mat[6] = v02;
mat[7] = v12;
mat[8] = v22;
return mat;
};
/**
* Sets the matrix from the array of values stored in column major order.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Mat3.AnyType} values The column major ordered
* array of values to store in the matrix.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setFromArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[1];
mat[2] = values[2];
mat[3] = values[3];
mat[4] = values[4];
mat[5] = values[5];
mat[6] = values[6];
mat[7] = values[7];
mat[8] = values[8];
return mat;
};
/**
* Sets the matrix from the array of values stored in row major order.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Mat3.AnyType} values The row major ordered array
* of values to store in the matrix.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setFromRowMajorArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[3];
mat[2] = values[6];
mat[3] = values[1];
mat[4] = values[4];
mat[5] = values[7];
mat[6] = values[2];
mat[7] = values[5];
mat[8] = values[8];
return mat;
};
/**
* Sets the diagonal values of the matrix from the given values.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {number} v00 The values for (0, 0).
* @param {number} v11 The values for (1, 1).
* @param {number} v22 The values for (2, 2).
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setDiagonalValues = function(mat, v00, v11, v22) {
mat[0] = v00;
mat[4] = v11;
mat[8] = v22;
return mat;
};
/**
* Sets the diagonal values of the matrix from the given vector.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Vec3.AnyType} vec The vector containing the values.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setDiagonal = function(mat, vec) {
mat[0] = vec[0];
mat[4] = vec[1];
mat[8] = vec[2];
return mat;
};
/**
* Sets the specified column with the supplied values.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to recieve the values.
* @param {number} column The column index to set the values on.
* @param {number} v0 The value for row 0.
* @param {number} v1 The value for row 1.
* @param {number} v2 The value for row 2.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setColumnValues = function(mat, column, v0, v1, v2) {
var i = column * 3;
mat[i] = v0;
mat[i + 1] = v1;
mat[i + 2] = v2;
return mat;
};
/**
* Sets the specified column with the value from the supplied array.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {number} column The column index to set the values on.
* @param {goog.vec.Vec3.AnyType} vec The vector elements for the column.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setColumn = function(mat, column, vec) {
var i = column * 3;
mat[i] = vec[0];
mat[i + 1] = vec[1];
mat[i + 2] = vec[2];
return mat;
};
/**
* Retrieves the specified column from the matrix into the given vector
* array.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix supplying the values.
* @param {number} column The column to get the values from.
* @param {goog.vec.Vec3.AnyType} vec The vector elements to receive the
* column.
* @return {goog.vec.Vec3.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Mat3.getColumn = function(mat, column, vec) {
var i = column * 3;
vec[0] = mat[i];
vec[1] = mat[i + 1];
vec[2] = mat[i + 2];
return vec;
};
/**
* Sets the columns of the matrix from the set of vector elements.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Vec3.AnyType} vec0 The values for column 0.
* @param {goog.vec.Vec3.AnyType} vec1 The values for column 1.
* @param {goog.vec.Vec3.AnyType} vec2 The values for column 2.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setColumns = function(mat, vec0, vec1, vec2) {
goog.vec.Mat3.setColumn(mat, 0, vec0);
goog.vec.Mat3.setColumn(mat, 1, vec1);
goog.vec.Mat3.setColumn(mat, 2, vec2);
return mat;
};
/**
* Retrieves the column values from the given matrix into the given vector
* elements.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix supplying the columns.
* @param {goog.vec.Vec3.AnyType} vec0 The vector to receive column 0.
* @param {goog.vec.Vec3.AnyType} vec1 The vector to receive column 1.
* @param {goog.vec.Vec3.AnyType} vec2 The vector to receive column 2.
*/
goog.vec.Mat3.getColumns = function(mat, vec0, vec1, vec2) {
goog.vec.Mat3.getColumn(mat, 0, vec0);
goog.vec.Mat3.getColumn(mat, 1, vec1);
goog.vec.Mat3.getColumn(mat, 2, vec2);
};
/**
* Sets the row values from the supplied values.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {number} row The index of the row to receive the values.
* @param {number} v0 The value for column 0.
* @param {number} v1 The value for column 1.
* @param {number} v2 The value for column 2.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setRowValues = function(mat, row, v0, v1, v2) {
mat[row] = v0;
mat[row + 3] = v1;
mat[row + 6] = v2;
return mat;
};
/**
* Sets the row values from the supplied vector.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the row values.
* @param {number} row The index of the row.
* @param {goog.vec.Vec3.AnyType} vec The vector containing the values.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setRow = function(mat, row, vec) {
mat[row] = vec[0];
mat[row + 3] = vec[1];
mat[row + 6] = vec[2];
return mat;
};
/**
* Retrieves the row values into the given vector.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix supplying the values.
* @param {number} row The index of the row supplying the values.
* @param {goog.vec.Vec3.AnyType} vec The vector to receive the row.
* @return {goog.vec.Vec3.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Mat3.getRow = function(mat, row, vec) {
vec[0] = mat[row];
vec[1] = mat[row + 3];
vec[2] = mat[row + 6];
return vec;
};
/**
* Sets the rows of the matrix from the supplied vectors.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Vec3.AnyType} vec0 The values for row 0.
* @param {goog.vec.Vec3.AnyType} vec1 The values for row 1.
* @param {goog.vec.Vec3.AnyType} vec2 The values for row 2.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat3.setRows = function(mat, vec0, vec1, vec2) {
goog.vec.Mat3.setRow(mat, 0, vec0);
goog.vec.Mat3.setRow(mat, 1, vec1);
goog.vec.Mat3.setRow(mat, 2, vec2);
return mat;
};
/**
* Retrieves the rows of the matrix into the supplied vectors.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to supplying the values.
* @param {goog.vec.Vec3.AnyType} vec0 The vector to receive row 0.
* @param {goog.vec.Vec3.AnyType} vec1 The vector to receive row 1.
* @param {goog.vec.Vec3.AnyType} vec2 The vector to receive row 2.
*/
goog.vec.Mat3.getRows = function(mat, vec0, vec1, vec2) {
goog.vec.Mat3.getRow(mat, 0, vec0);
goog.vec.Mat3.getRow(mat, 1, vec1);
goog.vec.Mat3.getRow(mat, 2, vec2);
};
/**
* Makes the given 3x3 matrix the zero matrix.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @return {goog.vec.Mat3.AnyType} return mat so operations can be chained.
*/
goog.vec.Mat3.makeZero = function(mat) {
mat[0] = 0;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 0;
mat[5] = 0;
mat[6] = 0;
mat[7] = 0;
mat[8] = 0;
return mat;
};
/**
* Makes the given 3x3 matrix the identity matrix.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @return {goog.vec.Mat3.AnyType} return mat so operations can be chained.
*/
goog.vec.Mat3.makeIdentity = function(mat) {
mat[0] = 1;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 1;
mat[5] = 0;
mat[6] = 0;
mat[7] = 0;
mat[8] = 1;
return mat;
};
/**
* Performs a per-component addition of the matrices mat0 and mat1, storing
* the result into resultMat.
*
* @param {goog.vec.Mat3.AnyType} mat0 The first addend.
* @param {goog.vec.Mat3.AnyType} mat1 The second addend.
* @param {goog.vec.Mat3.AnyType} resultMat The matrix to
* receive the results (may be either mat0 or mat1).
* @return {goog.vec.Mat3.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat3.addMat = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] + mat1[0];
resultMat[1] = mat0[1] + mat1[1];
resultMat[2] = mat0[2] + mat1[2];
resultMat[3] = mat0[3] + mat1[3];
resultMat[4] = mat0[4] + mat1[4];
resultMat[5] = mat0[5] + mat1[5];
resultMat[6] = mat0[6] + mat1[6];
resultMat[7] = mat0[7] + mat1[7];
resultMat[8] = mat0[8] + mat1[8];
return resultMat;
};
/**
* Performs a per-component subtraction of the matrices mat0 and mat1,
* storing the result into resultMat.
*
* @param {goog.vec.Mat3.AnyType} mat0 The minuend.
* @param {goog.vec.Mat3.AnyType} mat1 The subtrahend.
* @param {goog.vec.Mat3.AnyType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.Mat3.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat3.subMat = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] - mat1[0];
resultMat[1] = mat0[1] - mat1[1];
resultMat[2] = mat0[2] - mat1[2];
resultMat[3] = mat0[3] - mat1[3];
resultMat[4] = mat0[4] - mat1[4];
resultMat[5] = mat0[5] - mat1[5];
resultMat[6] = mat0[6] - mat1[6];
resultMat[7] = mat0[7] - mat1[7];
resultMat[8] = mat0[8] - mat1[8];
return resultMat;
};
/**
* Multiplies matrix mat0 with the given scalar, storing the result
* into resultMat.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} scalar The scalar value to multiple to each element of mat.
* @param {goog.vec.Mat3.AnyType} resultMat The matrix to receive
* the results (may be mat).
* @return {goog.vec.Mat3.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat3.multScalar = function(mat, scalar, resultMat) {
resultMat[0] = mat[0] * scalar;
resultMat[1] = mat[1] * scalar;
resultMat[2] = mat[2] * scalar;
resultMat[3] = mat[3] * scalar;
resultMat[4] = mat[4] * scalar;
resultMat[5] = mat[5] * scalar;
resultMat[6] = mat[6] * scalar;
resultMat[7] = mat[7] * scalar;
resultMat[8] = mat[8] * scalar;
return resultMat;
};
/**
* Multiplies the two matrices mat0 and mat1 using matrix multiplication,
* storing the result into resultMat.
*
* @param {goog.vec.Mat3.AnyType} mat0 The first (left hand) matrix.
* @param {goog.vec.Mat3.AnyType} mat1 The second (right hand) matrix.
* @param {goog.vec.Mat3.AnyType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.Mat3.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat3.multMat = function(mat0, mat1, resultMat) {
var a00 = mat0[0], a10 = mat0[1], a20 = mat0[2];
var a01 = mat0[3], a11 = mat0[4], a21 = mat0[5];
var a02 = mat0[6], a12 = mat0[7], a22 = mat0[8];
var b00 = mat1[0], b10 = mat1[1], b20 = mat1[2];
var b01 = mat1[3], b11 = mat1[4], b21 = mat1[5];
var b02 = mat1[6], b12 = mat1[7], b22 = mat1[8];
resultMat[0] = a00 * b00 + a01 * b10 + a02 * b20;
resultMat[1] = a10 * b00 + a11 * b10 + a12 * b20;
resultMat[2] = a20 * b00 + a21 * b10 + a22 * b20;
resultMat[3] = a00 * b01 + a01 * b11 + a02 * b21;
resultMat[4] = a10 * b01 + a11 * b11 + a12 * b21;
resultMat[5] = a20 * b01 + a21 * b11 + a22 * b21;
resultMat[6] = a00 * b02 + a01 * b12 + a02 * b22;
resultMat[7] = a10 * b02 + a11 * b12 + a12 * b22;
resultMat[8] = a20 * b02 + a21 * b12 + a22 * b22;
return resultMat;
};
/**
* Transposes the given matrix mat storing the result into resultMat.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix to transpose.
* @param {goog.vec.Mat3.AnyType} resultMat The matrix to receive
* the results (may be mat).
* @return {goog.vec.Mat3.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat3.transpose = function(mat, resultMat) {
if (resultMat == mat) {
var a10 = mat[1], a20 = mat[2], a21 = mat[5];
resultMat[1] = mat[3];
resultMat[2] = mat[6];
resultMat[3] = a10;
resultMat[5] = mat[7];
resultMat[6] = a20;
resultMat[7] = a21;
} else {
resultMat[0] = mat[0];
resultMat[1] = mat[3];
resultMat[2] = mat[6];
resultMat[3] = mat[1];
resultMat[4] = mat[4];
resultMat[5] = mat[7];
resultMat[6] = mat[2];
resultMat[7] = mat[5];
resultMat[8] = mat[8];
}
return resultMat;
};
/**
* Computes the inverse of mat0 storing the result into resultMat. If the
* inverse is defined, this function returns true, false otherwise.
*
* @param {goog.vec.Mat3.AnyType} mat0 The matrix to invert.
* @param {goog.vec.Mat3.AnyType} resultMat The matrix to receive
* the result (may be mat0).
* @return {boolean} True if the inverse is defined. If false is returned,
* resultMat is not modified.
*/
goog.vec.Mat3.invert = function(mat0, resultMat) {
var a00 = mat0[0], a10 = mat0[1], a20 = mat0[2];
var a01 = mat0[3], a11 = mat0[4], a21 = mat0[5];
var a02 = mat0[6], a12 = mat0[7], a22 = mat0[8];
var t00 = a11 * a22 - a12 * a21;
var t10 = a12 * a20 - a10 * a22;
var t20 = a10 * a21 - a11 * a20;
var det = a00 * t00 + a01 * t10 + a02 * t20;
if (det == 0) {
return false;
}
var idet = 1 / det;
resultMat[0] = t00 * idet;
resultMat[3] = (a02 * a21 - a01 * a22) * idet;
resultMat[6] = (a01 * a12 - a02 * a11) * idet;
resultMat[1] = t10 * idet;
resultMat[4] = (a00 * a22 - a02 * a20) * idet;
resultMat[7] = (a02 * a10 - a00 * a12) * idet;
resultMat[2] = t20 * idet;
resultMat[5] = (a01 * a20 - a00 * a21) * idet;
resultMat[8] = (a00 * a11 - a01 * a10) * idet;
return true;
};
/**
* Returns true if the components of mat0 are equal to the components of mat1.
*
* @param {goog.vec.Mat3.AnyType} mat0 The first matrix.
* @param {goog.vec.Mat3.AnyType} mat1 The second matrix.
* @return {boolean} True if the the two matrices are equivalent.
*/
goog.vec.Mat3.equals = function(mat0, mat1) {
return mat0.length == mat1.length &&
mat0[0] == mat1[0] && mat0[1] == mat1[1] && mat0[2] == mat1[2] &&
mat0[3] == mat1[3] && mat0[4] == mat1[4] && mat0[5] == mat1[5] &&
mat0[6] == mat1[6] && mat0[7] == mat1[7] && mat0[8] == mat1[8];
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed matrix into resultVec.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix supplying the transformation.
* @param {goog.vec.Vec3.AnyType} vec The vector to transform.
* @param {goog.vec.Vec3.AnyType} resultVec The vector to
* receive the results (may be vec).
* @return {goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Mat3.multVec3 = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
resultVec[0] = x * mat[0] + y * mat[3] + z * mat[6];
resultVec[1] = x * mat[1] + y * mat[4] + z * mat[7];
resultVec[2] = x * mat[2] + y * mat[5] + z * mat[8];
return resultVec;
};
/**
* Makes the given 3x3 matrix a translation matrix with x and y
* translation values.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} x The translation along the x axis.
* @param {number} y The translation along the y axis.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.makeTranslate = function(mat, x, y) {
goog.vec.Mat3.makeIdentity(mat);
return goog.vec.Mat3.setColumnValues(mat, 2, x, y, 1);
};
/**
* Makes the given 3x3 matrix a scale matrix with x, y, and z scale factors.
*
* @param {goog.vec.Mat3.AnyType} mat The 3x3 (9-element) matrix
* array to receive the new scale matrix.
* @param {number} x The scale along the x axis.
* @param {number} y The scale along the y axis.
* @param {number} z The scale along the z axis.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.makeScale = function(mat, x, y, z) {
goog.vec.Mat3.makeIdentity(mat);
return goog.vec.Mat3.setDiagonalValues(mat, x, y, z);
};
/**
* Makes the given 3x3 matrix a rotation matrix with the given rotation
* angle about the axis defined by the vector (ax, ay, az).
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @param {number} ax The x component of the rotation axis.
* @param {number} ay The y component of the rotation axis.
* @param {number} az The z component of the rotation axis.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.makeRotate = function(mat, angle, ax, ay, az) {
var c = Math.cos(angle);
var d = 1 - c;
var s = Math.sin(angle);
return goog.vec.Mat3.setFromValues(mat,
ax * ax * d + c,
ax * ay * d + az * s,
ax * az * d - ay * s,
ax * ay * d - az * s,
ay * ay * d + c,
ay * az * d + ax * s,
ax * az * d + ay * s,
ay * az * d - ax * s,
az * az * d + c);
};
/**
* Makes the given 3x3 matrix a rotation matrix with the given rotation
* angle about the X axis.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.makeRotateX = function(mat, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
return goog.vec.Mat3.setFromValues(mat,
1, 0, 0,
0, c, s,
0, -s, c);
};
/**
* Makes the given 3x3 matrix a rotation matrix with the given rotation
* angle about the Y axis.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.makeRotateY = function(mat, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
return goog.vec.Mat3.setFromValues(mat,
c, 0, -s,
0, 1, 0,
s, 0, c);
};
/**
* Makes the given 3x3 matrix a rotation matrix with the given rotation
* angle about the Z axis.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.makeRotateZ = function(mat, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
return goog.vec.Mat3.setFromValues(mat,
c, s, 0,
-s, c, 0,
0, 0, 1);
};
/**
* Rotate the given matrix by angle about the x,y,z axis. Equivalent to:
* goog.vec.Mat3.multMat(
* mat,
* goog.vec.Mat3.makeRotate(goog.vec.Mat3.create(), angle, x, y, z),
* mat);
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @param {number} x The x component of the rotation axis.
* @param {number} y The y component of the rotation axis.
* @param {number} z The z component of the rotation axis.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.rotate = function(mat, angle, x, y, z) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2];
var m01 = mat[3], m11 = mat[4], m21 = mat[5];
var m02 = mat[6], m12 = mat[7], m22 = mat[8];
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
var diffCosAngle = 1 - cosAngle;
var r00 = x * x * diffCosAngle + cosAngle;
var r10 = x * y * diffCosAngle + z * sinAngle;
var r20 = x * z * diffCosAngle - y * sinAngle;
var r01 = x * y * diffCosAngle - z * sinAngle;
var r11 = y * y * diffCosAngle + cosAngle;
var r21 = y * z * diffCosAngle + x * sinAngle;
var r02 = x * z * diffCosAngle + y * sinAngle;
var r12 = y * z * diffCosAngle - x * sinAngle;
var r22 = z * z * diffCosAngle + cosAngle;
return goog.vec.Mat3.setFromValues(
mat,
m00 * r00 + m01 * r10 + m02 * r20,
m10 * r00 + m11 * r10 + m12 * r20,
m20 * r00 + m21 * r10 + m22 * r20,
m00 * r01 + m01 * r11 + m02 * r21,
m10 * r01 + m11 * r11 + m12 * r21,
m20 * r01 + m21 * r11 + m22 * r21,
m00 * r02 + m01 * r12 + m02 * r22,
m10 * r02 + m11 * r12 + m12 * r22,
m20 * r02 + m21 * r12 + m22 * r22);
};
/**
* Rotate the given matrix by angle about the x axis. Equivalent to:
* goog.vec.Mat3.multMat(
* mat,
* goog.vec.Mat3.makeRotateX(goog.vec.Mat3.create(), angle),
* mat);
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.rotateX = function(mat, angle) {
var m01 = mat[3], m11 = mat[4], m21 = mat[5];
var m02 = mat[6], m12 = mat[7], m22 = mat[8];
var c = Math.cos(angle);
var s = Math.sin(angle);
mat[3] = m01 * c + m02 * s;
mat[4] = m11 * c + m12 * s;
mat[5] = m21 * c + m22 * s;
mat[6] = m01 * -s + m02 * c;
mat[7] = m11 * -s + m12 * c;
mat[8] = m21 * -s + m22 * c;
return mat;
};
/**
* Rotate the given matrix by angle about the y axis. Equivalent to:
* goog.vec.Mat3.multMat(
* mat,
* goog.vec.Mat3.makeRotateY(goog.vec.Mat3.create(), angle),
* mat);
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.rotateY = function(mat, angle) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2];
var m02 = mat[6], m12 = mat[7], m22 = mat[8];
var c = Math.cos(angle);
var s = Math.sin(angle);
mat[0] = m00 * c + m02 * -s;
mat[1] = m10 * c + m12 * -s;
mat[2] = m20 * c + m22 * -s;
mat[6] = m00 * s + m02 * c;
mat[7] = m10 * s + m12 * c;
mat[8] = m20 * s + m22 * c;
return mat;
};
/**
* Rotate the given matrix by angle about the z axis. Equivalent to:
* goog.vec.Mat3.multMat(
* mat,
* goog.vec.Mat3.makeRotateZ(goog.vec.Mat3.create(), angle),
* mat);
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.rotateZ = function(mat, angle) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2];
var m01 = mat[3], m11 = mat[4], m21 = mat[5];
var c = Math.cos(angle);
var s = Math.sin(angle);
mat[0] = m00 * c + m01 * s;
mat[1] = m10 * c + m11 * s;
mat[2] = m20 * c + m21 * s;
mat[3] = m00 * -s + m01 * c;
mat[4] = m10 * -s + m11 * c;
mat[5] = m20 * -s + m21 * c;
return mat;
};
/**
* Makes the given 3x3 matrix a rotation matrix given Euler angles using
* the ZXZ convention.
* Given the euler angles [theta1, theta2, theta3], the rotation is defined as
* rotation = rotation_z(theta1) * rotation_x(theta2) * rotation_z(theta3),
* with theta1 in [0, 2 * pi], theta2 in [0, pi] and theta3 in [0, 2 * pi].
* rotation_x(theta) means rotation around the X axis of theta radians.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {number} theta1 The angle of rotation around the Z axis in radians.
* @param {number} theta2 The angle of rotation around the X axis in radians.
* @param {number} theta3 The angle of rotation around the Z axis in radians.
* @return {goog.vec.Mat3.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat3.makeEulerZXZ = function(mat, theta1, theta2, theta3) {
var c1 = Math.cos(theta1);
var s1 = Math.sin(theta1);
var c2 = Math.cos(theta2);
var s2 = Math.sin(theta2);
var c3 = Math.cos(theta3);
var s3 = Math.sin(theta3);
mat[0] = c1 * c3 - c2 * s1 * s3;
mat[1] = c2 * c1 * s3 + c3 * s1;
mat[2] = s3 * s2;
mat[3] = -c1 * s3 - c3 * c2 * s1;
mat[4] = c1 * c2 * c3 - s1 * s3;
mat[5] = c3 * s2;
mat[6] = s2 * s1;
mat[7] = -c1 * s2;
mat[8] = c2;
return mat;
};
/**
* Decomposes a rotation matrix into Euler angles using the ZXZ convention so
* that rotation = rotation_z(theta1) * rotation_x(theta2) * rotation_z(theta3),
* with theta1 in [0, 2 * pi], theta2 in [0, pi] and theta3 in [0, 2 * pi].
* rotation_x(theta) means rotation around the X axis of theta radians.
*
* @param {goog.vec.Mat3.AnyType} mat The matrix.
* @param {goog.vec.Vec3.AnyType} euler The ZXZ Euler angles in
* radians as [theta1, theta2, theta3].
* @param {boolean=} opt_theta2IsNegative Whether theta2 is in [-pi, 0] instead
* of the default [0, pi].
* @return {goog.vec.Vec3.AnyType} return euler so that operations can be
* chained together.
*/
goog.vec.Mat3.toEulerZXZ = function(mat, euler, opt_theta2IsNegative) {
// There is an ambiguity in the sign of sinTheta2 because of the sqrt.
var sinTheta2 = Math.sqrt(mat[2] * mat[2] + mat[5] * mat[5]);
// By default we explicitely constrain theta2 to be in [0, pi],
// so sinTheta2 is always positive. We can change the behavior and specify
// theta2 to be negative in [-pi, 0] with opt_Theta2IsNegative.
var signTheta2 = opt_theta2IsNegative ? -1 : 1;
if (sinTheta2 > goog.vec.EPSILON) {
euler[2] = Math.atan2(mat[2] * signTheta2, mat[5] * signTheta2);
euler[1] = Math.atan2(sinTheta2 * signTheta2, mat[8]);
euler[0] = Math.atan2(mat[6] * signTheta2, -mat[7] * signTheta2);
} else {
// There is also an arbitrary choice for theta1 = 0 or theta2 = 0 here.
// We assume theta1 = 0 as some applications do not allow the camera to roll
// (i.e. have theta1 != 0).
euler[0] = 0;
euler[1] = Math.atan2(sinTheta2 * signTheta2, mat[8]);
euler[2] = Math.atan2(mat[1], mat[0]);
}
// Atan2 outputs angles in [-pi, pi] so we bring them back to [0, 2 * pi].
euler[0] = (euler[0] + Math.PI * 2) % (Math.PI * 2);
euler[2] = (euler[2] + Math.PI * 2) % (Math.PI * 2);
// For theta2 we want the angle to be in [0, pi] or [-pi, 0] depending on
// signTheta2.
euler[1] = ((euler[1] * signTheta2 + Math.PI * 2) % (Math.PI * 2)) *
signTheta2;
return euler;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Supplies global data types and constants for the vector math
* library.
*/
goog.provide('goog.vec');
goog.provide('goog.vec.AnyType');
goog.provide('goog.vec.ArrayType');
goog.provide('goog.vec.Float32');
goog.provide('goog.vec.Float64');
goog.provide('goog.vec.Number');
/**
* On platforms that don't have native Float32Array or Float64Array support we
* use a javascript implementation so that this math library can be used on all
* platforms.
*/
goog.require('goog.vec.Float32Array');
goog.require('goog.vec.Float64Array');
// All vector and matrix operations are based upon arrays of numbers using
// either Float32Array, Float64Array, or a standard Javascript Array of
// Numbers.
/** @typedef {Float32Array} */
goog.vec.Float32;
/** @typedef {Float64Array} */
goog.vec.Float64;
/** @typedef {Array.<number>} */
goog.vec.Number;
/** @typedef {goog.vec.Float32|goog.vec.Float64|goog.vec.Number} */
goog.vec.AnyType;
/**
* @deprecated Use AnyType.
* @typedef {Float32Array|Array.<number>}
*/
goog.vec.ArrayType;
/**
* For graphics work, 6 decimal places of accuracy are typically all that is
* required.
*
* @type {number}
* @const
*/
goog.vec.EPSILON = 1e-6;
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Supplies 4 element vectors that are compatible with WebGL.
* Each element is a float32 since that is typically the desired size of a
* 4-vector in the GPU. The API is structured to avoid unnecessary memory
* allocations. The last parameter will typically be the output vector and
* an object can be both an input and output parameter to all methods except
* where noted.
*
*/
goog.provide('goog.vec.Vec4');
goog.require('goog.vec');
/** @typedef {goog.vec.Float32} */ goog.vec.Vec4.Float32;
/** @typedef {goog.vec.Float64} */ goog.vec.Vec4.Float64;
/** @typedef {goog.vec.Number} */ goog.vec.Vec4.Number;
/** @typedef {goog.vec.AnyType} */ goog.vec.Vec4.AnyType;
// The following two types are deprecated - use the above types instead.
/** @typedef {Float32Array} */ goog.vec.Vec4.Type;
/** @typedef {goog.vec.ArrayType} */ goog.vec.Vec4.Vec4Like;
/**
* Creates a 4 element vector of Float32. The array is initialized to zero.
*
* @return {!goog.vec.Vec4.Float32} The new 3 element array.
*/
goog.vec.Vec4.createFloat32 = function() {
return new Float32Array(4);
};
/**
* Creates a 4 element vector of Float64. The array is initialized to zero.
*
* @return {!goog.vec.Vec4.Float64} The new 4 element array.
*/
goog.vec.Vec4.createFloat64 = function() {
return new Float64Array(4);
};
/**
* Creates a 4 element vector of Number. The array is initialized to zero.
*
* @return {!goog.vec.Vec4.Number} The new 4 element array.
*/
goog.vec.Vec4.createNumber = function() {
var v = new Array(4);
goog.vec.Vec4.setFromValues(v, 0, 0, 0, 0);
return v;
};
/**
* Creates a 4 element vector of Float32Array. The array is initialized to zero.
*
* @deprecated Use createFloat32.
* @return {!goog.vec.Vec4.Type} The new 4 element array.
*/
goog.vec.Vec4.create = function() {
return new Float32Array(4);
};
/**
* Creates a new 4 element vector initialized with the value from the given
* array.
*
* @deprecated Use createFloat32FromArray.
* @param {goog.vec.Vec4.Vec4Like} vec The source 4 element array.
* @return {!goog.vec.Vec4.Type} The new 4 element array.
*/
goog.vec.Vec4.createFromArray = function(vec) {
var newVec = goog.vec.Vec4.create();
goog.vec.Vec4.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 4 element FLoat32 vector initialized with the value from the
* given array.
*
* @param {goog.vec.Vec4.AnyType} vec The source 3 element array.
* @return {!goog.vec.Vec4.Float32} The new 3 element array.
*/
goog.vec.Vec4.createFloat32FromArray = function(vec) {
var newVec = goog.vec.Vec4.createFloat32();
goog.vec.Vec4.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 4 element Float32 vector initialized with the supplied values.
*
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @param {number} v3 The value for element at index 3.
* @return {!goog.vec.Vec4.Float32} The new vector.
*/
goog.vec.Vec4.createFloat32FromValues = function(v0, v1, v2, v3) {
var vec = goog.vec.Vec4.createFloat32();
goog.vec.Vec4.setFromValues(vec, v0, v1, v2, v3);
return vec;
};
/**
* Creates a clone of the given 4 element Float32 vector.
*
* @param {goog.vec.Vec4.Float32} vec The source 3 element vector.
* @return {!goog.vec.Vec4.Float32} The new cloned vector.
*/
goog.vec.Vec4.cloneFloat32 = goog.vec.Vec4.createFloat32FromArray;
/**
* Creates a new 4 element Float64 vector initialized with the value from the
* given array.
*
* @param {goog.vec.Vec4.AnyType} vec The source 4 element array.
* @return {!goog.vec.Vec4.Float64} The new 4 element array.
*/
goog.vec.Vec4.createFloat64FromArray = function(vec) {
var newVec = goog.vec.Vec4.createFloat64();
goog.vec.Vec4.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 4 element Float64 vector initialized with the supplied values.
*
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @param {number} v3 The value for element at index 3.
* @return {!goog.vec.Vec4.Float64} The new vector.
*/
goog.vec.Vec4.createFloat64FromValues = function(v0, v1, v2, v3) {
var vec = goog.vec.Vec4.createFloat64();
goog.vec.Vec4.setFromValues(vec, v0, v1, v2, v3);
return vec;
};
/**
* Creates a clone of the given 4 element vector.
*
* @param {goog.vec.Vec4.Float64} vec The source 4 element vector.
* @return {!goog.vec.Vec4.Float64} The new cloned vector.
*/
goog.vec.Vec4.cloneFloat64 = goog.vec.Vec4.createFloat64FromArray;
/**
* Creates a new 4 element vector initialized with the supplied values.
*
* @deprecated Use createFloat32FromValues.
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @param {number} v3 The value for element at index 3.
* @return {!goog.vec.Vec4.Type} The new vector.
*/
goog.vec.Vec4.createFromValues = function(v0, v1, v2, v3) {
var vec = goog.vec.Vec4.create();
goog.vec.Vec4.setFromValues(vec, v0, v1, v2, v3);
return vec;
};
/**
* Creates a clone of the given 4 element vector.
*
* @deprecated Use cloneFloat32.
* @param {goog.vec.Vec4.Vec4Like} vec The source 4 element vector.
* @return {!goog.vec.Vec4.Type} The new cloned vector.
*/
goog.vec.Vec4.clone = goog.vec.Vec4.createFromArray;
/**
* Initializes the vector with the given values.
*
* @param {goog.vec.Vec4.AnyType} vec The vector to receive the values.
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @param {number} v3 The value for element at index 3.
* @return {!goog.vec.Vec4.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Vec4.setFromValues = function(vec, v0, v1, v2, v3) {
vec[0] = v0;
vec[1] = v1;
vec[2] = v2;
vec[3] = v3;
return vec;
};
/**
* Initializes the vector with the given array of values.
*
* @param {goog.vec.Vec4.AnyType} vec The vector to receive the
* values.
* @param {goog.vec.Vec4.AnyType} values The array of values.
* @return {!goog.vec.Vec4.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Vec4.setFromArray = function(vec, values) {
vec[0] = values[0];
vec[1] = values[1];
vec[2] = values[2];
vec[3] = values[3];
return vec;
};
/**
* Performs a component-wise addition of vec0 and vec1 together storing the
* result into resultVec.
*
* @param {goog.vec.Vec4.AnyType} vec0 The first addend.
* @param {goog.vec.Vec4.AnyType} vec1 The second addend.
* @param {goog.vec.Vec4.AnyType} resultVec The vector to
* receive the result. May be vec0 or vec1.
* @return {!goog.vec.Vec4.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec4.add = function(vec0, vec1, resultVec) {
resultVec[0] = vec0[0] + vec1[0];
resultVec[1] = vec0[1] + vec1[1];
resultVec[2] = vec0[2] + vec1[2];
resultVec[3] = vec0[3] + vec1[3];
return resultVec;
};
/**
* Performs a component-wise subtraction of vec1 from vec0 storing the
* result into resultVec.
*
* @param {goog.vec.Vec4.AnyType} vec0 The minuend.
* @param {goog.vec.Vec4.AnyType} vec1 The subtrahend.
* @param {goog.vec.Vec4.AnyType} resultVec The vector to
* receive the result. May be vec0 or vec1.
* @return {!goog.vec.Vec4.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec4.subtract = function(vec0, vec1, resultVec) {
resultVec[0] = vec0[0] - vec1[0];
resultVec[1] = vec0[1] - vec1[1];
resultVec[2] = vec0[2] - vec1[2];
resultVec[3] = vec0[3] - vec1[3];
return resultVec;
};
/**
* Negates vec0, storing the result into resultVec.
*
* @param {goog.vec.Vec4.AnyType} vec0 The vector to negate.
* @param {goog.vec.Vec4.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec4.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec4.negate = function(vec0, resultVec) {
resultVec[0] = -vec0[0];
resultVec[1] = -vec0[1];
resultVec[2] = -vec0[2];
resultVec[3] = -vec0[3];
return resultVec;
};
/**
* Multiplies each component of vec0 with scalar storing the product into
* resultVec.
*
* @param {goog.vec.Vec4.AnyType} vec0 The source vector.
* @param {number} scalar The value to multiply with each component of vec0.
* @param {goog.vec.Vec4.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec4.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec4.scale = function(vec0, scalar, resultVec) {
resultVec[0] = vec0[0] * scalar;
resultVec[1] = vec0[1] * scalar;
resultVec[2] = vec0[2] * scalar;
resultVec[3] = vec0[3] * scalar;
return resultVec;
};
/**
* Returns the magnitudeSquared of the given vector.
*
* @param {goog.vec.Vec4.AnyType} vec0 The vector.
* @return {number} The magnitude of the vector.
*/
goog.vec.Vec4.magnitudeSquared = function(vec0) {
var x = vec0[0], y = vec0[1], z = vec0[2], w = vec0[3];
return x * x + y * y + z * z + w * w;
};
/**
* Returns the magnitude of the given vector.
*
* @param {goog.vec.Vec4.AnyType} vec0 The vector.
* @return {number} The magnitude of the vector.
*/
goog.vec.Vec4.magnitude = function(vec0) {
var x = vec0[0], y = vec0[1], z = vec0[2], w = vec0[3];
return Math.sqrt(x * x + y * y + z * z + w * w);
};
/**
* Normalizes the given vector storing the result into resultVec.
*
* @param {goog.vec.Vec4.AnyType} vec0 The vector to normalize.
* @param {goog.vec.Vec4.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec4.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec4.normalize = function(vec0, resultVec) {
var ilen = 1 / goog.vec.Vec4.magnitude(vec0);
resultVec[0] = vec0[0] * ilen;
resultVec[1] = vec0[1] * ilen;
resultVec[2] = vec0[2] * ilen;
resultVec[3] = vec0[3] * ilen;
return resultVec;
};
/**
* Returns the scalar product of vectors v0 and v1.
*
* @param {goog.vec.Vec4.AnyType} v0 The first vector.
* @param {goog.vec.Vec4.AnyType} v1 The second vector.
* @return {number} The scalar product.
*/
goog.vec.Vec4.dot = function(v0, v1) {
return v0[0] * v1[0] + v0[1] * v1[1] + v0[2] * v1[2] + v0[3] * v1[3];
};
/**
* Linearly interpolate from v0 to v1 according to f. The value of f should be
* in the range [0..1] otherwise the results are undefined.
*
* @param {goog.vec.Vec4.AnyType} v0 The first vector.
* @param {goog.vec.Vec4.AnyType} v1 The second vector.
* @param {number} f The interpolation factor.
* @param {goog.vec.Vec4.AnyType} resultVec The vector to receive the
* results (may be v0 or v1).
* @return {!goog.vec.Vec4.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec4.lerp = function(v0, v1, f, resultVec) {
var x = v0[0], y = v0[1], z = v0[2], w = v0[3];
resultVec[0] = (v1[0] - x) * f + x;
resultVec[1] = (v1[1] - y) * f + y;
resultVec[2] = (v1[2] - z) * f + z;
resultVec[3] = (v1[3] - w) * f + w;
return resultVec;
};
/**
* Returns true if the components of v0 are equal to the components of v1.
*
* @param {goog.vec.Vec4.AnyType} v0 The first vector.
* @param {goog.vec.Vec4.AnyType} v1 The second vector.
* @return {boolean} True if the vectors are equal, false otherwise.
*/
goog.vec.Vec4.equals = function(v0, v1) {
return v0.length == v1.length &&
v0[0] == v1[0] && v0[1] == v1[1] && v0[2] == v1[2] && v0[3] == v1[3];
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Implements quaternions and their conversion functions. In this
* implementation, quaternions are represented as 4 element vectors with the
* first 3 elements holding the imaginary components and the 4th element holding
* the real component.
*
*/
goog.provide('goog.vec.Quaternion');
goog.require('goog.vec');
goog.require('goog.vec.Vec3');
goog.require('goog.vec.Vec4');
/** @typedef {goog.vec.Float32} */ goog.vec.Quaternion.Float32;
/** @typedef {goog.vec.Float64} */ goog.vec.Quaternion.Float64;
/** @typedef {goog.vec.Number} */ goog.vec.Quaternion.Number;
/** @typedef {goog.vec.AnyType} */ goog.vec.Quaternion.AnyType;
/**
* Creates a Float32 quaternion, initialized to zero.
*
* @return {!goog.vec.Quaternion.Float32} The new quaternion.
*/
goog.vec.Quaternion.createFloat32 = goog.vec.Vec4.createFloat32;
/**
* Creates a Float64 quaternion, initialized to zero.
*
* @return {goog.vec.Quaternion.Float64} The new quaternion.
*/
goog.vec.Quaternion.createFloat64 = goog.vec.Vec4.createFloat64;
/**
* Creates a Number quaternion, initialized to zero.
*
* @return {goog.vec.Quaternion.Number} The new quaternion.
*/
goog.vec.Quaternion.createNumber = goog.vec.Vec4.createNumber;
/**
* Creates a new Float32 quaternion initialized with the values from the
* supplied array.
*
* @param {goog.vec.AnyType} vec The source 4 element array.
* @return {!goog.vec.Quaternion.Float32} The new quaternion.
*/
goog.vec.Quaternion.createFloat32FromArray =
goog.vec.Vec4.createFloat32FromArray;
/**
* Creates a new Float64 quaternion initialized with the values from the
* supplied array.
*
* @param {goog.vec.AnyType} vec The source 4 element array.
* @return {!goog.vec.Quaternion.Float64} The new quaternion.
*/
goog.vec.Quaternion.createFloat64FromArray =
goog.vec.Vec4.createFloat64FromArray;
/**
* Creates a new Float32 quaternion initialized with the supplied values.
*
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @param {number} v3 The value for element at index 3.
* @return {!goog.vec.Quaternion.Float32} The new quaternion.
*/
goog.vec.Quaternion.createFloat32FromValues =
goog.vec.Vec4.createFloat32FromValues;
/**
* Creates a new Float64 quaternion initialized with the supplied values.
*
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @param {number} v3 The value for element at index 3.
* @return {!goog.vec.Quaternion.Float64} The new quaternion.
*/
goog.vec.Quaternion.createFloat64FromValues =
goog.vec.Vec4.createFloat64FromValues;
/**
* Creates a clone of the given Float32 quaternion.
*
* @param {goog.vec.Quaternion.Float32} q The source quaternion.
* @return {goog.vec.Quaternion.Float32} The new quaternion.
*/
goog.vec.Quaternion.cloneFloat32 = goog.vec.Vec4.cloneFloat32;
/**
* Creates a clone of the given Float64 quaternion.
*
* @param {goog.vec.Quaternion.Float64} q The source quaternion.
* @return {goog.vec.Quaternion.Float64} The new quaternion.
*/
goog.vec.Quaternion.cloneFloat64 = goog.vec.Vec4.cloneFloat64;
/**
* Initializes the quaternion with the given values.
*
* @param {goog.vec.Quaternion.AnyType} q The quaternion to receive
* the values.
* @param {number} v0 The value for element at index 0.
* @param {number} v1 The value for element at index 1.
* @param {number} v2 The value for element at index 2.
* @param {number} v3 The value for element at index 3.
* @return {!goog.vec.Vec4.AnyType} return q so that operations can be
* chained together.
*/
goog.vec.Quaternion.setFromValues = goog.vec.Vec4.setFromValues;
/**
* Initializes the quaternion with the given array of values.
*
* @param {goog.vec.Quaternion.AnyType} q The quaternion to receive
* the values.
* @param {goog.vec.AnyType} values The array of values.
* @return {!goog.vec.Quaternion.AnyType} return q so that operations can be
* chained together.
*/
goog.vec.Quaternion.setFromArray = goog.vec.Vec4.setFromArray;
/**
* Adds the two quaternions.
*
* @param {goog.vec.Quaternion.AnyType} quat0 The first addend.
* @param {goog.vec.Quaternion.AnyType} quat1 The second addend.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the result. May be quat0 or quat1.
*/
goog.vec.Quaternion.add = goog.vec.Vec4.add;
/**
* Negates a quaternion, storing the result into resultQuat.
*
* @param {goog.vec.Quaternion.AnyType} quat0 The quaternion to negate.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the result. May be quat0.
*/
goog.vec.Quaternion.negate = goog.vec.Vec4.negate;
/**
* Multiplies each component of quat0 with scalar storing the product into
* resultVec.
*
* @param {goog.vec.Quaternion.AnyType} quat0 The source quaternion.
* @param {number} scalar The value to multiply with each component of quat0.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the result. May be quat0.
*/
goog.vec.Quaternion.scale = goog.vec.Vec4.scale;
/**
* Returns the square magnitude of the given quaternion.
*
* @param {goog.vec.Quaternion.AnyType} quat0 The quaternion.
* @return {number} The magnitude of the quaternion.
*/
goog.vec.Quaternion.magnitudeSquared =
goog.vec.Vec4.magnitudeSquared;
/**
* Returns the magnitude of the given quaternion.
*
* @param {goog.vec.Quaternion.AnyType} quat0 The quaternion.
* @return {number} The magnitude of the quaternion.
*/
goog.vec.Quaternion.magnitude =
goog.vec.Vec4.magnitude;
/**
* Normalizes the given quaternion storing the result into resultVec.
*
* @param {goog.vec.Quaternion.AnyType} quat0 The quaternion to
* normalize.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the result. May be quat0.
*/
goog.vec.Quaternion.normalize = goog.vec.Vec4.normalize;
/**
* Computes the dot (scalar) product of two quaternions.
*
* @param {goog.vec.Quaternion.AnyType} q0 The first quaternion.
* @param {goog.vec.Quaternion.AnyType} q1 The second quaternion.
* @return {number} The scalar product.
*/
goog.vec.Quaternion.dot = goog.vec.Vec4.dot;
/**
* Computes the conjugate of the quaternion in quat storing the result into
* resultQuat.
*
* @param {goog.vec.Quaternion.AnyType} quat The source quaternion.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the result.
* @return {!goog.vec.Quaternion.AnyType} Return q so that
* operations can be chained together.
*/
goog.vec.Quaternion.conjugate = function(quat, resultQuat) {
resultQuat[0] = -quat[0];
resultQuat[1] = -quat[1];
resultQuat[2] = -quat[2];
resultQuat[3] = quat[3];
return resultQuat;
};
/**
* Concatenates the two quaternions storing the result into resultQuat.
*
* @param {goog.vec.Quaternion.AnyType} quat0 The first quaternion.
* @param {goog.vec.Quaternion.AnyType} quat1 The second quaternion.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the result.
* @return {!goog.vec.Quaternion.AnyType} Return q so that
* operations can be chained together.
*/
goog.vec.Quaternion.concat = function(quat0, quat1, resultQuat) {
var x0 = quat0[0], y0 = quat0[1], z0 = quat0[2], w0 = quat0[3];
var x1 = quat1[0], y1 = quat1[1], z1 = quat1[2], w1 = quat1[3];
resultQuat[0] = w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1;
resultQuat[1] = w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1;
resultQuat[2] = w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1;
resultQuat[3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
return resultQuat;
};
/**
* Generates a unit quaternion from the given angle-axis rotation pair.
* The rotation axis is not required to be a unit vector, but should
* have non-zero length. The angle should be specified in radians.
*
* @param {number} angle The angle (in radians) to rotate about the axis.
* @param {goog.vec.Quaternion.AnyType} axis Unit vector specifying the
* axis of rotation.
* @param {goog.vec.Quaternion.AnyType} quat Unit quaternion to store the
* result.
* @return {goog.vec.Quaternion.AnyType} Return q so that
* operations can be chained together.
*/
goog.vec.Quaternion.fromAngleAxis = function(angle, axis, quat) {
// Normalize the axis of rotation.
goog.vec.Vec3.normalize(axis, axis);
var halfAngle = 0.5 * angle;
var sin = Math.sin(halfAngle);
goog.vec.Quaternion.setFromValues(
quat, sin * axis[0], sin * axis[1], sin * axis[2], Math.cos(halfAngle));
// Normalize the resulting quaternion.
goog.vec.Quaternion.normalize(quat, quat);
return quat;
};
/**
* Generates an angle-axis rotation pair from a unit quaternion.
* The quaternion is assumed to be of unit length. The calculated
* values are returned via the passed 'axis' object and the 'angle'
* number returned by the function itself. The returned rotation axis
* is a non-zero length unit vector, and the returned angle is in
* radians in the range of [-PI, +PI].
*
* @param {goog.vec.Quaternion.AnyType} quat Unit quaternion to convert.
* @param {goog.vec.Quaternion.AnyType} axis Vector to store the returned
* rotation axis.
* @return {number} angle Angle (in radians) to rotate about 'axis'.
* The range of the returned angle is [-PI, +PI].
*/
goog.vec.Quaternion.toAngleAxis = function(quat, axis) {
var angle = 2 * Math.acos(quat[3]);
var magnitude = Math.min(Math.max(1 - quat[3] * quat[3], 0), 1);
if (magnitude < goog.vec.EPSILON) {
// This is nearly an identity rotation, so just use a fixed +X axis.
goog.vec.Vec3.setFromValues(axis, 1, 0, 0);
} else {
// Compute the proper rotation axis.
goog.vec.Vec3.setFromValues(axis, quat[0], quat[1], quat[2]);
// Make sure the rotation axis is of unit length.
goog.vec.Vec3.normalize(axis, axis);
}
// Adjust the range of the returned angle to [-PI, +PI].
if (angle > Math.PI) {
angle -= 2 * Math.PI;
}
return angle;
};
/**
* Generates the quaternion from the given rotation matrix.
*
* @param {goog.vec.Quaternion.AnyType} matrix The source matrix.
* @param {goog.vec.Quaternion.AnyType} quat The resulting quaternion.
* @return {!goog.vec.Quaternion.AnyType} Return q so that
* operations can be chained together.
*/
goog.vec.Quaternion.fromRotationMatrix4 = function(matrix, quat) {
var sx = matrix[0], sy = matrix[5], sz = matrix[10];
quat[3] = Math.sqrt(Math.max(0, 1 + sx + sy + sz)) / 2;
quat[0] = Math.sqrt(Math.max(0, 1 + sx - sy - sz)) / 2;
quat[1] = Math.sqrt(Math.max(0, 1 - sx + sy - sz)) / 2;
quat[2] = Math.sqrt(Math.max(0, 1 - sx - sy + sz)) / 2;
quat[0] = (matrix[6] - matrix[9] < 0) != (quat[0] < 0) ? -quat[0] : quat[0];
quat[1] = (matrix[8] - matrix[2] < 0) != (quat[1] < 0) ? -quat[1] : quat[1];
quat[2] = (matrix[1] - matrix[4] < 0) != (quat[2] < 0) ? -quat[2] : quat[2];
return quat;
};
/**
* Generates the rotation matrix from the given quaternion.
*
* @param {goog.vec.Quaternion.AnyType} quat The source quaternion.
* @param {goog.vec.AnyType} matrix The resulting matrix.
* @return {!goog.vec.AnyType} Return resulting matrix so that
* operations can be chained together.
*/
goog.vec.Quaternion.toRotationMatrix4 = function(quat, matrix) {
var x = quat[0], y = quat[1], z = quat[2], w = quat[3];
var x2 = 2 * x, y2 = 2 * y, z2 = 2 * z;
var wx = x2 * w;
var wy = y2 * w;
var wz = z2 * w;
var xx = x2 * x;
var xy = y2 * x;
var xz = z2 * x;
var yy = y2 * y;
var yz = z2 * y;
var zz = z2 * z;
matrix[0] = 1 - (yy + zz);
matrix[1] = xy + wz;
matrix[2] = xz - wy;
matrix[3] = 0;
matrix[4] = xy - wz;
matrix[5] = 1 - (xx + zz);
matrix[6] = yz + wx;
matrix[7] = 0;
matrix[8] = xz + wy;
matrix[9] = yz - wx;
matrix[10] = 1 - (xx + yy);
matrix[11] = 0;
matrix[12] = 0;
matrix[13] = 0;
matrix[14] = 0;
matrix[15] = 1;
return matrix;
};
/**
* Computes the spherical linear interpolated value from the given quaternions
* q0 and q1 according to the coefficient t. The resulting quaternion is stored
* in resultQuat.
*
* @param {goog.vec.Quaternion.AnyType} q0 The first quaternion.
* @param {goog.vec.Quaternion.AnyType} q1 The second quaternion.
* @param {number} t The interpolating coefficient.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the result.
* @return {goog.vec.Quaternion.AnyType} Return q so that
* operations can be chained together.
*/
goog.vec.Quaternion.slerp = function(q0, q1, t, resultQuat) {
// Compute the dot product between q0 and q1 (cos of the angle between q0 and
// q1). If it's outside the interval [-1,1], then the arccos is not defined.
// The usual reason for this is that q0 and q1 are colinear. In this case
// the angle between the two is zero, so just return q1.
var cosVal = goog.vec.Quaternion.dot(q0, q1);
if (cosVal > 1 || cosVal < -1) {
goog.vec.Vec4.setFromArray(resultQuat, q1);
return resultQuat;
}
// Quaternions are a double cover on the space of rotations. That is, q and -q
// represent the same rotation. Thus we have two possibilities when
// interpolating between q0 and q1: going the short way or the long way. We
// prefer the short way since that is the likely expectation from users.
var factor = 1;
if (cosVal < 0) {
factor = -1;
cosVal = -cosVal;
}
// Compute the angle between q0 and q1. If it's very small, then just return
// q1 to avoid a very large denominator below.
var angle = Math.acos(cosVal);
if (angle <= goog.vec.EPSILON) {
goog.vec.Vec4.setFromArray(resultQuat, q1);
return resultQuat;
}
// Compute the coefficients and interpolate.
var invSinVal = 1 / Math.sin(angle);
var c0 = Math.sin((1 - t) * angle) * invSinVal;
var c1 = factor * Math.sin(t * angle) * invSinVal;
resultQuat[0] = q0[0] * c0 + q1[0] * c1;
resultQuat[1] = q0[1] * c0 + q1[1] * c1;
resultQuat[2] = q0[2] * c0 + q1[2] * c1;
resultQuat[3] = q0[3] * c0 + q1[3] * c1;
return resultQuat;
};
/**
* Compute the simple linear interpolation of the two quaternions q0 and q1
* according to the coefficient t. The resulting quaternion is stored in
* resultVec.
*
* @param {goog.vec.Quaternion.AnyType} q0 The first quaternion.
* @param {goog.vec.Quaternion.AnyType} q1 The second quaternion.
* @param {number} t The interpolation factor.
* @param {goog.vec.Quaternion.AnyType} resultQuat The quaternion to
* receive the results (may be q0 or q1).
*/
goog.vec.Quaternion.nlerp = goog.vec.Vec4.lerp;
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Implements a 3D ray that are compatible with WebGL.
* Each element is a float64 in case high precision is required.
* The API is structured to avoid unnecessary memory allocations.
* The last parameter will typically be the output vector and an
* object can be both an input and output parameter to all methods
* except where noted.
*
*/
goog.provide('goog.vec.Ray');
goog.require('goog.vec.Vec3');
/**
* Constructs a new ray with an optional origin and direction. If not specified,
* the default is [0, 0, 0].
* @param {goog.vec.Vec3.AnyType=} opt_origin The optional origin.
* @param {goog.vec.Vec3.AnyType=} opt_dir The optional direction.
* @constructor
*/
goog.vec.Ray = function(opt_origin, opt_dir) {
/**
* @type {goog.vec.Vec3.Number}
*/
this.origin = goog.vec.Vec3.createNumber();
if (opt_origin) {
goog.vec.Vec3.setFromArray(this.origin, opt_origin);
}
/**
* @type {goog.vec.Vec3.Number}
*/
this.dir = goog.vec.Vec3.createNumber();
if (opt_dir) {
goog.vec.Vec3.setFromArray(this.dir, opt_dir);
}
};
/**
* Sets the origin and direction of the ray.
* @param {goog.vec.AnyType} origin The new origin.
* @param {goog.vec.AnyType} dir The new direction.
*/
goog.vec.Ray.prototype.set = function(origin, dir) {
goog.vec.Vec3.setFromArray(this.origin, origin);
goog.vec.Vec3.setFromArray(this.dir, dir);
};
/**
* Sets the origin of the ray.
* @param {goog.vec.AnyType} origin the new origin.
*/
goog.vec.Ray.prototype.setOrigin = function(origin) {
goog.vec.Vec3.setFromArray(this.origin, origin);
};
/**
* Sets the direction of the ray.
* @param {goog.vec.AnyType} dir The new direction.
*/
goog.vec.Ray.prototype.setDir = function(dir) {
goog.vec.Vec3.setFromArray(this.dir, dir);
};
/**
* Returns true if this ray is equal to the other ray.
* @param {goog.vec.Ray} other The other ray.
* @return {boolean} True if this ray is equal to the other ray.
*/
goog.vec.Ray.prototype.equals = function(other) {
return other != null &&
goog.vec.Vec3.equals(this.origin, other.origin) &&
goog.vec.Vec3.equals(this.dir, other.dir);
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definition of 2 element vectors. This follows the same design
* patterns as Vec3 and Vec4.
*
*/
goog.provide('goog.vec.Vec2');
goog.require('goog.vec');
/** @typedef {goog.vec.Float32} */ goog.vec.Vec2.Float32;
/** @typedef {goog.vec.Float64} */ goog.vec.Vec2.Float64;
/** @typedef {goog.vec.Number} */ goog.vec.Vec2.Number;
/** @typedef {goog.vec.AnyType} */ goog.vec.Vec2.AnyType;
/**
* Creates a 2 element vector of Float32. The array is initialized to zero.
*
* @return {!goog.vec.Vec2.Float32} The new 2 element array.
*/
goog.vec.Vec2.createFloat32 = function() {
return new Float32Array(2);
};
/**
* Creates a 2 element vector of Float64. The array is initialized to zero.
*
* @return {!goog.vec.Vec2.Float64} The new 2 element array.
*/
goog.vec.Vec2.createFloat64 = function() {
return new Float64Array(2);
};
/**
* Creates a 2 element vector of Number. The array is initialized to zero.
*
* @return {!goog.vec.Vec2.Number} The new 2 element array.
*/
goog.vec.Vec2.createNumber = function() {
var a = new Array(2);
goog.vec.Vec2.setFromValues(a, 0, 0);
return a;
};
/**
* Creates a new 2 element FLoat32 vector initialized with the value from the
* given array.
*
* @param {goog.vec.Vec2.AnyType} vec The source 2 element array.
* @return {!goog.vec.Vec2.Float32} The new 2 element array.
*/
goog.vec.Vec2.createFloat32FromArray = function(vec) {
var newVec = goog.vec.Vec2.createFloat32();
goog.vec.Vec2.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 2 element Float32 vector initialized with the supplied values.
*
* @param {number} vec0 The value for element at index 0.
* @param {number} vec1 The value for element at index 1.
* @return {!goog.vec.Vec2.Float32} The new vector.
*/
goog.vec.Vec2.createFloat32FromValues = function(vec0, vec1) {
var a = goog.vec.Vec2.createFloat32();
goog.vec.Vec2.setFromValues(a, vec0, vec1);
return a;
};
/**
* Creates a clone of the given 2 element Float32 vector.
*
* @param {goog.vec.Vec2.Float32} vec The source 2 element vector.
* @return {!goog.vec.Vec2.Float32} The new cloned vector.
*/
goog.vec.Vec2.cloneFloat32 = goog.vec.Vec2.createFloat32FromArray;
/**
* Creates a new 2 element Float64 vector initialized with the value from the
* given array.
*
* @param {goog.vec.Vec2.AnyType} vec The source 2 element array.
* @return {!goog.vec.Vec2.Float64} The new 2 element array.
*/
goog.vec.Vec2.createFloat64FromArray = function(vec) {
var newVec = goog.vec.Vec2.createFloat64();
goog.vec.Vec2.setFromArray(newVec, vec);
return newVec;
};
/**
* Creates a new 2 element Float64 vector initialized with the supplied values.
*
* @param {number} vec0 The value for element at index 0.
* @param {number} vec1 The value for element at index 1.
* @return {!goog.vec.Vec2.Float64} The new vector.
*/
goog.vec.Vec2.createFloat64FromValues = function(vec0, vec1) {
var vec = goog.vec.Vec2.createFloat64();
goog.vec.Vec2.setFromValues(vec, vec0, vec1);
return vec;
};
/**
* Creates a clone of the given 2 element vector.
*
* @param {goog.vec.Vec2.Float64} vec The source 2 element vector.
* @return {!goog.vec.Vec2.Float64} The new cloned vector.
*/
goog.vec.Vec2.cloneFloat64 = goog.vec.Vec2.createFloat64FromArray;
/**
* Initializes the vector with the given values.
*
* @param {goog.vec.Vec2.AnyType} vec The vector to receive the values.
* @param {number} vec0 The value for element at index 0.
* @param {number} vec1 The value for element at index 1.
* @return {!goog.vec.Vec2.AnyType} Return vec so that operations can be
* chained together.
*/
goog.vec.Vec2.setFromValues = function(vec, vec0, vec1) {
vec[0] = vec0;
vec[1] = vec1;
return vec;
};
/**
* Initializes the vector with the given array of values.
*
* @param {goog.vec.Vec2.AnyType} vec The vector to receive the
* values.
* @param {goog.vec.Vec2.AnyType} values The array of values.
* @return {!goog.vec.Vec2.AnyType} Return vec so that operations can be
* chained together.
*/
goog.vec.Vec2.setFromArray = function(vec, values) {
vec[0] = values[0];
vec[1] = values[1];
return vec;
};
/**
* Performs a component-wise addition of vec0 and vec1 together storing the
* result into resultVec.
*
* @param {goog.vec.Vec2.AnyType} vec0 The first addend.
* @param {goog.vec.Vec2.AnyType} vec1 The second addend.
* @param {goog.vec.Vec2.AnyType} resultVec The vector to
* receive the result. May be vec0 or vec1.
* @return {!goog.vec.Vec2.AnyType} Return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec2.add = function(vec0, vec1, resultVec) {
resultVec[0] = vec0[0] + vec1[0];
resultVec[1] = vec0[1] + vec1[1];
return resultVec;
};
/**
* Performs a component-wise subtraction of vec1 from vec0 storing the
* result into resultVec.
*
* @param {goog.vec.Vec2.AnyType} vec0 The minuend.
* @param {goog.vec.Vec2.AnyType} vec1 The subtrahend.
* @param {goog.vec.Vec2.AnyType} resultVec The vector to
* receive the result. May be vec0 or vec1.
* @return {!goog.vec.Vec2.AnyType} Return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec2.subtract = function(vec0, vec1, resultVec) {
resultVec[0] = vec0[0] - vec1[0];
resultVec[1] = vec0[1] - vec1[1];
return resultVec;
};
/**
* Negates vec0, storing the result into resultVec.
*
* @param {goog.vec.Vec2.AnyType} vec0 The vector to negate.
* @param {goog.vec.Vec2.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec2.AnyType} Return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec2.negate = function(vec0, resultVec) {
resultVec[0] = -vec0[0];
resultVec[1] = -vec0[1];
return resultVec;
};
/**
* Multiplies each component of vec0 with scalar storing the product into
* resultVec.
*
* @param {goog.vec.Vec2.AnyType} vec0 The source vector.
* @param {number} scalar The value to multiply with each component of vec0.
* @param {goog.vec.Vec2.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec2.AnyType} Return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec2.scale = function(vec0, scalar, resultVec) {
resultVec[0] = vec0[0] * scalar;
resultVec[1] = vec0[1] * scalar;
return resultVec;
};
/**
* Returns the magnitudeSquared of the given vector.
*
* @param {goog.vec.Vec2.AnyType} vec0 The vector.
* @return {number} The magnitude of the vector.
*/
goog.vec.Vec2.magnitudeSquared = function(vec0) {
var x = vec0[0], y = vec0[1];
return x * x + y * y;
};
/**
* Returns the magnitude of the given vector.
*
* @param {goog.vec.Vec2.AnyType} vec0 The vector.
* @return {number} The magnitude of the vector.
*/
goog.vec.Vec2.magnitude = function(vec0) {
var x = vec0[0], y = vec0[1];
return Math.sqrt(x * x + y * y);
};
/**
* Normalizes the given vector storing the result into resultVec.
*
* @param {goog.vec.Vec2.AnyType} vec0 The vector to normalize.
* @param {goog.vec.Vec2.AnyType} resultVec The vector to
* receive the result. May be vec0.
* @return {!goog.vec.Vec2.AnyType} Return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec2.normalize = function(vec0, resultVec) {
var ilen = 1 / goog.vec.Vec2.magnitude(vec0);
resultVec[0] = vec0[0] * ilen;
resultVec[1] = vec0[1] * ilen;
return resultVec;
};
/**
* Returns the scalar product of vectors vec0 and vec1.
*
* @param {goog.vec.Vec2.AnyType} vec0 The first vector.
* @param {goog.vec.Vec2.AnyType} vec1 The second vector.
* @return {number} The scalar product.
*/
goog.vec.Vec2.dot = function(vec0, vec1) {
return vec0[0] * vec1[0] + vec0[1] * vec1[1];
};
/**
* Returns the squared distance between two points.
*
* @param {goog.vec.Vec2.AnyType} vec0 First point.
* @param {goog.vec.Vec2.AnyType} vec1 Second point.
* @return {number} The squared distance between the points.
*/
goog.vec.Vec2.distanceSquared = function(vec0, vec1) {
var x = vec0[0] - vec1[0];
var y = vec0[1] - vec1[1];
return x * x + y * y;
};
/**
* Returns the distance between two points.
*
* @param {goog.vec.Vec2.AnyType} vec0 First point.
* @param {goog.vec.Vec2.AnyType} vec1 Second point.
* @return {number} The distance between the points.
*/
goog.vec.Vec2.distance = function(vec0, vec1) {
return Math.sqrt(goog.vec.Vec2.distanceSquared(vec0, vec1));
};
/**
* Returns a unit vector pointing from one point to another.
* If the input points are equal then the result will be all zeros.
*
* @param {goog.vec.Vec2.AnyType} vec0 Origin point.
* @param {goog.vec.Vec2.AnyType} vec1 Target point.
* @param {goog.vec.Vec2.AnyType} resultVec The vector to receive the
* results (may be vec0 or vec1).
* @return {!goog.vec.Vec2.AnyType} Return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec2.direction = function(vec0, vec1, resultVec) {
var x = vec1[0] - vec0[0];
var y = vec1[1] - vec0[1];
var d = Math.sqrt(x * x + y * y);
if (d) {
d = 1 / d;
resultVec[0] = x * d;
resultVec[1] = y * d;
} else {
resultVec[0] = resultVec[1] = 0;
}
return resultVec;
};
/**
* Linearly interpolate from vec0 to vec1 according to f. The value of f should
* be in the range [0..1] otherwise the results are undefined.
*
* @param {goog.vec.Vec2.AnyType} vec0 The first vector.
* @param {goog.vec.Vec2.AnyType} vec1 The second vector.
* @param {number} f The interpolation factor.
* @param {goog.vec.Vec2.AnyType} resultVec The vector to receive the
* results (may be vec0 or vec1).
* @return {!goog.vec.Vec2.AnyType} Return resultVec so that operations can be
* chained together.
*/
goog.vec.Vec2.lerp = function(vec0, vec1, f, resultVec) {
var x = vec0[0], y = vec0[1];
resultVec[0] = (vec1[0] - x) * f + x;
resultVec[1] = (vec1[1] - y) * f + y;
return resultVec;
};
/**
* Returns true if the components of vec0 are equal to the components of vec1.
*
* @param {goog.vec.Vec2.AnyType} vec0 The first vector.
* @param {goog.vec.Vec2.AnyType} vec1 The second vector.
* @return {boolean} True if the vectors are equal, false otherwise.
*/
goog.vec.Vec2.equals = function(vec0, vec1) {
return vec0.length == vec1.length &&
vec0[0] == vec1[0] && vec0[1] == vec1[1];
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Implements 4x4 matrices and their related functions which are
* compatible with WebGL. The API is structured to avoid unnecessary memory
* allocations. The last parameter will typically be the output vector and
* an object can be both an input and output parameter to all methods except
* where noted. Matrix operations follow the mathematical form when multiplying
* vectors as follows: resultVec = matrix * vec.
*
* The matrices are stored in column-major order.
*
*/
goog.provide('goog.vec.Mat4');
goog.require('goog.vec');
goog.require('goog.vec.Vec3');
goog.require('goog.vec.Vec4');
/** @typedef {goog.vec.Float32} */ goog.vec.Mat4.Float32;
/** @typedef {goog.vec.Float64} */ goog.vec.Mat4.Float64;
/** @typedef {goog.vec.Number} */ goog.vec.Mat4.Number;
/** @typedef {goog.vec.AnyType} */ goog.vec.Mat4.AnyType;
// The following two types are deprecated - use the above types instead.
/** @typedef {Float32Array} */ goog.vec.Mat4.Type;
/** @typedef {goog.vec.ArrayType} */ goog.vec.Mat4.Mat4Like;
/**
* Creates the array representation of a 4x4 matrix of Float32.
* The use of the array directly instead of a class reduces overhead.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat4.Float32} The new matrix.
*/
goog.vec.Mat4.createFloat32 = function() {
return new Float32Array(16);
};
/**
* Creates the array representation of a 4x4 matrix of Float64.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat4.Float64} The new matrix.
*/
goog.vec.Mat4.createFloat64 = function() {
return new Float64Array(16);
};
/**
* Creates the array representation of a 4x4 matrix of Number.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat4.Number} The new matrix.
*/
goog.vec.Mat4.createNumber = function() {
var a = new Array(16);
goog.vec.Mat4.setFromValues(a,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0);
return a;
};
/**
* Creates the array representation of a 4x4 matrix of Float32.
* The returned matrix is cleared to all zeros.
*
* @deprecated Use createFloat32.
* @return {!goog.vec.Mat4.Type} The new matrix.
*/
goog.vec.Mat4.create = function() {
return goog.vec.Mat4.createFloat32();
};
/**
* Creates a 4x4 identity matrix of Float32.
*
* @return {!goog.vec.Mat4.Float32} The new 16 element array.
*/
goog.vec.Mat4.createFloat32Identity = function() {
var mat = goog.vec.Mat4.createFloat32();
mat[0] = mat[5] = mat[10] = mat[15] = 1;
return mat;
};
/**
* Creates a 4x4 identity matrix of Float64.
*
* @return {!goog.vec.Mat4.Float64} The new 16 element array.
*/
goog.vec.Mat4.createFloat64Identity = function() {
var mat = goog.vec.Mat4.createFloat64();
mat[0] = mat[5] = mat[10] = mat[15] = 1;
return mat;
};
/**
* Creates a 4x4 identity matrix of Number.
* The returned matrix is cleared to all zeros.
*
* @return {!goog.vec.Mat4.Number} The new 16 element array.
*/
goog.vec.Mat4.createNumberIdentity = function() {
var a = new Array(16);
goog.vec.Mat4.setFromValues(a,
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
return a;
};
/**
* Creates the array representation of a 4x4 matrix of Float32.
* The returned matrix is cleared to all zeros.
*
* @deprecated Use createFloat32Identity.
* @return {!goog.vec.Mat4.Type} The new 16 element array.
*/
goog.vec.Mat4.createIdentity = function() {
return goog.vec.Mat4.createFloat32Identity();
};
/**
* Creates a 4x4 matrix of Float32 initialized from the given array.
*
* @param {goog.vec.Mat4.AnyType} matrix The array containing the
* matrix values in column major order.
* @return {!goog.vec.Mat4.Float32} The new, 16 element array.
*/
goog.vec.Mat4.createFloat32FromArray = function(matrix) {
var newMatrix = goog.vec.Mat4.createFloat32();
goog.vec.Mat4.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 4x4 matrix of Float32 initialized from the given values.
*
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v30 The values at (3, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v31 The values at (3, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @param {number} v32 The values at (3, 2).
* @param {number} v03 The values at (0, 3).
* @param {number} v13 The values at (1, 3).
* @param {number} v23 The values at (2, 3).
* @param {number} v33 The values at (3, 3).
* @return {!goog.vec.Mat4.Float32} The new, 16 element array.
*/
goog.vec.Mat4.createFloat32FromValues = function(
v00, v10, v20, v30,
v01, v11, v21, v31,
v02, v12, v22, v32,
v03, v13, v23, v33) {
var newMatrix = goog.vec.Mat4.createFloat32();
goog.vec.Mat4.setFromValues(
newMatrix, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
v03, v13, v23, v33);
return newMatrix;
};
/**
* Creates a clone of a 4x4 matrix of Float32.
*
* @param {goog.vec.Mat4.Float32} matrix The source 4x4 matrix.
* @return {!goog.vec.Mat4.Float32} The new 4x4 element matrix.
*/
goog.vec.Mat4.cloneFloat32 = goog.vec.Mat4.createFloat32FromArray;
/**
* Creates a 4x4 matrix of Float64 initialized from the given array.
*
* @param {goog.vec.Mat4.AnyType} matrix The array containing the
* matrix values in column major order.
* @return {!goog.vec.Mat4.Float64} The new, nine element array.
*/
goog.vec.Mat4.createFloat64FromArray = function(matrix) {
var newMatrix = goog.vec.Mat4.createFloat64();
goog.vec.Mat4.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 4x4 matrix of Float64 initialized from the given values.
*
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v30 The values at (3, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v31 The values at (3, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @param {number} v32 The values at (3, 2).
* @param {number} v03 The values at (0, 3).
* @param {number} v13 The values at (1, 3).
* @param {number} v23 The values at (2, 3).
* @param {number} v33 The values at (3, 3).
* @return {!goog.vec.Mat4.Float64} The new, 16 element array.
*/
goog.vec.Mat4.createFloat64FromValues = function(
v00, v10, v20, v30,
v01, v11, v21, v31,
v02, v12, v22, v32,
v03, v13, v23, v33) {
var newMatrix = goog.vec.Mat4.createFloat64();
goog.vec.Mat4.setFromValues(
newMatrix, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
v03, v13, v23, v33);
return newMatrix;
};
/**
* Creates a clone of a 4x4 matrix of Float64.
*
* @param {goog.vec.Mat4.Float64} matrix The source 4x4 matrix.
* @return {!goog.vec.Mat4.Float64} The new 4x4 element matrix.
*/
goog.vec.Mat4.cloneFloat64 = goog.vec.Mat4.createFloat64FromArray;
/**
* Creates a 4x4 matrix of Float32 initialized from the given array.
*
* @deprecated Use createFloat32FromArray.
* @param {goog.vec.Mat4.Mat4Like} matrix The array containing the
* matrix values in column major order.
* @return {!goog.vec.Mat4.Type} The new, nine element array.
*/
goog.vec.Mat4.createFromArray = function(matrix) {
var newMatrix = goog.vec.Mat4.createFloat32();
goog.vec.Mat4.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 4x4 matrix of Float32 initialized from the given values.
*
* @deprecated Use createFloat32FromValues.
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v30 The values at (3, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v31 The values at (3, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @param {number} v32 The values at (3, 2).
* @param {number} v03 The values at (0, 3).
* @param {number} v13 The values at (1, 3).
* @param {number} v23 The values at (2, 3).
* @param {number} v33 The values at (3, 3).
* @return {!goog.vec.Mat4.Type} The new, 16 element array.
*/
goog.vec.Mat4.createFromValues = function(
v00, v10, v20, v30,
v01, v11, v21, v31,
v02, v12, v22, v32,
v03, v13, v23, v33) {
return goog.vec.Mat4.createFloat32FromValues(
v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
v03, v13, v23, v33);
};
/**
* Creates a clone of a 4x4 matrix of Float32.
*
* @deprecated Use cloneFloat32.
* @param {goog.vec.Mat4.Mat4Like} matrix The source 4x4 matrix.
* @return {!goog.vec.Mat4.Type} The new 4x4 element matrix.
*/
goog.vec.Mat4.clone = goog.vec.Mat4.createFromArray;
/**
* Retrieves the element at the requested row and column.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix containing the
* value to retrieve.
* @param {number} row The row index.
* @param {number} column The column index.
* @return {number} The element value at the requested row, column indices.
*/
goog.vec.Mat4.getElement = function(mat, row, column) {
return mat[row + column * 4];
};
/**
* Sets the element at the requested row and column.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to set the value on.
* @param {number} row The row index.
* @param {number} column The column index.
* @param {number} value The value to set at the requested row, column.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setElement = function(mat, row, column, value) {
mat[row + column * 4] = value;
return mat;
};
/**
* Initializes the matrix from the set of values. Note the values supplied are
* in column major order.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the
* values.
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v30 The values at (3, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v31 The values at (3, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @param {number} v32 The values at (3, 2).
* @param {number} v03 The values at (0, 3).
* @param {number} v13 The values at (1, 3).
* @param {number} v23 The values at (2, 3).
* @param {number} v33 The values at (3, 3).
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setFromValues = function(
mat, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
v03, v13, v23, v33) {
mat[0] = v00;
mat[1] = v10;
mat[2] = v20;
mat[3] = v30;
mat[4] = v01;
mat[5] = v11;
mat[6] = v21;
mat[7] = v31;
mat[8] = v02;
mat[9] = v12;
mat[10] = v22;
mat[11] = v32;
mat[12] = v03;
mat[13] = v13;
mat[14] = v23;
mat[15] = v33;
return mat;
};
/**
* Sets the matrix from the array of values stored in column major order.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Mat4.AnyType} values The column major ordered
* array of values to store in the matrix.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setFromArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[1];
mat[2] = values[2];
mat[3] = values[3];
mat[4] = values[4];
mat[5] = values[5];
mat[6] = values[6];
mat[7] = values[7];
mat[8] = values[8];
mat[9] = values[9];
mat[10] = values[10];
mat[11] = values[11];
mat[12] = values[12];
mat[13] = values[13];
mat[14] = values[14];
mat[15] = values[15];
return mat;
};
/**
* Sets the matrix from the array of values stored in row major order.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Mat4.AnyType} values The row major ordered array of
* values to store in the matrix.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setFromRowMajorArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[4];
mat[2] = values[8];
mat[3] = values[12];
mat[4] = values[1];
mat[5] = values[5];
mat[6] = values[9];
mat[7] = values[13];
mat[8] = values[2];
mat[9] = values[6];
mat[10] = values[10];
mat[11] = values[14];
mat[12] = values[3];
mat[13] = values[7];
mat[14] = values[11];
mat[15] = values[15];
return mat;
};
/**
* Sets the diagonal values of the matrix from the given values.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {number} v00 The values for (0, 0).
* @param {number} v11 The values for (1, 1).
* @param {number} v22 The values for (2, 2).
* @param {number} v33 The values for (3, 3).
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setDiagonalValues = function(mat, v00, v11, v22, v33) {
mat[0] = v00;
mat[5] = v11;
mat[10] = v22;
mat[15] = v33;
return mat;
};
/**
* Sets the diagonal values of the matrix from the given vector.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Vec4.AnyType} vec The vector containing the values.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setDiagonal = function(mat, vec) {
mat[0] = vec[0];
mat[5] = vec[1];
mat[10] = vec[2];
mat[15] = vec[3];
return mat;
};
/**
* Gets the diagonal values of the matrix into the given vector.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix containing the values.
* @param {goog.vec.Vec4.AnyType} vec The vector to receive the values.
* @param {number=} opt_diagonal Which diagonal to get. A value of 0 selects the
* main diagonal, a positive number selects a super diagonal and a negative
* number selects a sub diagonal.
* @return {goog.vec.Vec4.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Mat4.getDiagonal = function(mat, vec, opt_diagonal) {
if (!opt_diagonal) {
// This is the most common case, so we avoid the for loop.
vec[0] = mat[0];
vec[1] = mat[5];
vec[2] = mat[10];
vec[3] = mat[15];
} else {
var offset = opt_diagonal > 0 ? 4 * opt_diagonal : -opt_diagonal;
for (var i = 0; i < 4 - Math.abs(opt_diagonal); i++) {
vec[i] = mat[offset + 5 * i];
}
}
return vec;
};
/**
* Sets the specified column with the supplied values.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to recieve the values.
* @param {number} column The column index to set the values on.
* @param {number} v0 The value for row 0.
* @param {number} v1 The value for row 1.
* @param {number} v2 The value for row 2.
* @param {number} v3 The value for row 3.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setColumnValues = function(mat, column, v0, v1, v2, v3) {
var i = column * 4;
mat[i] = v0;
mat[i + 1] = v1;
mat[i + 2] = v2;
mat[i + 3] = v3;
return mat;
};
/**
* Sets the specified column with the value from the supplied vector.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {number} column The column index to set the values on.
* @param {goog.vec.Vec4.AnyType} vec The vector of elements for the column.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setColumn = function(mat, column, vec) {
var i = column * 4;
mat[i] = vec[0];
mat[i + 1] = vec[1];
mat[i + 2] = vec[2];
mat[i + 3] = vec[3];
return mat;
};
/**
* Retrieves the specified column from the matrix into the given vector.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix supplying the values.
* @param {number} column The column to get the values from.
* @param {goog.vec.Vec4.AnyType} vec The vector of elements to
* receive the column.
* @return {goog.vec.Vec4.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Mat4.getColumn = function(mat, column, vec) {
var i = column * 4;
vec[0] = mat[i];
vec[1] = mat[i + 1];
vec[2] = mat[i + 2];
vec[3] = mat[i + 3];
return vec;
};
/**
* Sets the columns of the matrix from the given vectors.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Vec4.AnyType} vec0 The values for column 0.
* @param {goog.vec.Vec4.AnyType} vec1 The values for column 1.
* @param {goog.vec.Vec4.AnyType} vec2 The values for column 2.
* @param {goog.vec.Vec4.AnyType} vec3 The values for column 3.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setColumns = function(mat, vec0, vec1, vec2, vec3) {
goog.vec.Mat4.setColumn(mat, 0, vec0);
goog.vec.Mat4.setColumn(mat, 1, vec1);
goog.vec.Mat4.setColumn(mat, 2, vec2);
goog.vec.Mat4.setColumn(mat, 3, vec3);
return mat;
};
/**
* Retrieves the column values from the given matrix into the given vectors.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix supplying the columns.
* @param {goog.vec.Vec4.AnyType} vec0 The vector to receive column 0.
* @param {goog.vec.Vec4.AnyType} vec1 The vector to receive column 1.
* @param {goog.vec.Vec4.AnyType} vec2 The vector to receive column 2.
* @param {goog.vec.Vec4.AnyType} vec3 The vector to receive column 3.
*/
goog.vec.Mat4.getColumns = function(mat, vec0, vec1, vec2, vec3) {
goog.vec.Mat4.getColumn(mat, 0, vec0);
goog.vec.Mat4.getColumn(mat, 1, vec1);
goog.vec.Mat4.getColumn(mat, 2, vec2);
goog.vec.Mat4.getColumn(mat, 3, vec3);
};
/**
* Sets the row values from the supplied values.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {number} row The index of the row to receive the values.
* @param {number} v0 The value for column 0.
* @param {number} v1 The value for column 1.
* @param {number} v2 The value for column 2.
* @param {number} v3 The value for column 3.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setRowValues = function(mat, row, v0, v1, v2, v3) {
mat[row] = v0;
mat[row + 4] = v1;
mat[row + 8] = v2;
mat[row + 12] = v3;
return mat;
};
/**
* Sets the row values from the supplied vector.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the row values.
* @param {number} row The index of the row.
* @param {goog.vec.Vec4.AnyType} vec The vector containing the values.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setRow = function(mat, row, vec) {
mat[row] = vec[0];
mat[row + 4] = vec[1];
mat[row + 8] = vec[2];
mat[row + 12] = vec[3];
return mat;
};
/**
* Retrieves the row values into the given vector.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix supplying the values.
* @param {number} row The index of the row supplying the values.
* @param {goog.vec.Vec4.AnyType} vec The vector to receive the row.
* @return {goog.vec.Vec4.AnyType} return vec so that operations can be
* chained together.
*/
goog.vec.Mat4.getRow = function(mat, row, vec) {
vec[0] = mat[row];
vec[1] = mat[row + 4];
vec[2] = mat[row + 8];
vec[3] = mat[row + 12];
return vec;
};
/**
* Sets the rows of the matrix from the supplied vectors.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
* @param {goog.vec.Vec4.AnyType} vec0 The values for row 0.
* @param {goog.vec.Vec4.AnyType} vec1 The values for row 1.
* @param {goog.vec.Vec4.AnyType} vec2 The values for row 2.
* @param {goog.vec.Vec4.AnyType} vec3 The values for row 3.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained together.
*/
goog.vec.Mat4.setRows = function(mat, vec0, vec1, vec2, vec3) {
goog.vec.Mat4.setRow(mat, 0, vec0);
goog.vec.Mat4.setRow(mat, 1, vec1);
goog.vec.Mat4.setRow(mat, 2, vec2);
goog.vec.Mat4.setRow(mat, 3, vec3);
return mat;
};
/**
* Retrieves the rows of the matrix into the supplied vectors.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to supply the values.
* @param {goog.vec.Vec4.AnyType} vec0 The vector to receive row 0.
* @param {goog.vec.Vec4.AnyType} vec1 The vector to receive row 1.
* @param {goog.vec.Vec4.AnyType} vec2 The vector to receive row 2.
* @param {goog.vec.Vec4.AnyType} vec3 The vector to receive row 3.
*/
goog.vec.Mat4.getRows = function(mat, vec0, vec1, vec2, vec3) {
goog.vec.Mat4.getRow(mat, 0, vec0);
goog.vec.Mat4.getRow(mat, 1, vec1);
goog.vec.Mat4.getRow(mat, 2, vec2);
goog.vec.Mat4.getRow(mat, 3, vec3);
};
/**
* Makes the given 4x4 matrix the zero matrix.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @return {!goog.vec.Mat4.AnyType} return mat so operations can be chained.
*/
goog.vec.Mat4.makeZero = function(mat) {
mat[0] = 0;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 0;
mat[5] = 0;
mat[6] = 0;
mat[7] = 0;
mat[8] = 0;
mat[9] = 0;
mat[10] = 0;
mat[11] = 0;
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 0;
return mat;
};
/**
* Makes the given 4x4 matrix the identity matrix.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @return {goog.vec.Mat4.AnyType} return mat so operations can be chained.
*/
goog.vec.Mat4.makeIdentity = function(mat) {
mat[0] = 1;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 0;
mat[5] = 1;
mat[6] = 0;
mat[7] = 0;
mat[8] = 0;
mat[9] = 0;
mat[10] = 1;
mat[11] = 0;
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 1;
return mat;
};
/**
* Performs a per-component addition of the matrix mat0 and mat1, storing
* the result into resultMat.
*
* @param {goog.vec.Mat4.AnyType} mat0 The first addend.
* @param {goog.vec.Mat4.AnyType} mat1 The second addend.
* @param {goog.vec.Mat4.AnyType} resultMat The matrix to
* receive the results (may be either mat0 or mat1).
* @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat4.addMat = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] + mat1[0];
resultMat[1] = mat0[1] + mat1[1];
resultMat[2] = mat0[2] + mat1[2];
resultMat[3] = mat0[3] + mat1[3];
resultMat[4] = mat0[4] + mat1[4];
resultMat[5] = mat0[5] + mat1[5];
resultMat[6] = mat0[6] + mat1[6];
resultMat[7] = mat0[7] + mat1[7];
resultMat[8] = mat0[8] + mat1[8];
resultMat[9] = mat0[9] + mat1[9];
resultMat[10] = mat0[10] + mat1[10];
resultMat[11] = mat0[11] + mat1[11];
resultMat[12] = mat0[12] + mat1[12];
resultMat[13] = mat0[13] + mat1[13];
resultMat[14] = mat0[14] + mat1[14];
resultMat[15] = mat0[15] + mat1[15];
return resultMat;
};
/**
* Performs a per-component subtraction of the matrix mat0 and mat1,
* storing the result into resultMat.
*
* @param {goog.vec.Mat4.AnyType} mat0 The minuend.
* @param {goog.vec.Mat4.AnyType} mat1 The subtrahend.
* @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat4.subMat = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] - mat1[0];
resultMat[1] = mat0[1] - mat1[1];
resultMat[2] = mat0[2] - mat1[2];
resultMat[3] = mat0[3] - mat1[3];
resultMat[4] = mat0[4] - mat1[4];
resultMat[5] = mat0[5] - mat1[5];
resultMat[6] = mat0[6] - mat1[6];
resultMat[7] = mat0[7] - mat1[7];
resultMat[8] = mat0[8] - mat1[8];
resultMat[9] = mat0[9] - mat1[9];
resultMat[10] = mat0[10] - mat1[10];
resultMat[11] = mat0[11] - mat1[11];
resultMat[12] = mat0[12] - mat1[12];
resultMat[13] = mat0[13] - mat1[13];
resultMat[14] = mat0[14] - mat1[14];
resultMat[15] = mat0[15] - mat1[15];
return resultMat;
};
/**
* Multiplies matrix mat with the given scalar, storing the result
* into resultMat.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} scalar The scalar value to multiply to each element of mat.
* @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
* the results (may be mat).
* @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat4.multScalar = function(mat, scalar, resultMat) {
resultMat[0] = mat[0] * scalar;
resultMat[1] = mat[1] * scalar;
resultMat[2] = mat[2] * scalar;
resultMat[3] = mat[3] * scalar;
resultMat[4] = mat[4] * scalar;
resultMat[5] = mat[5] * scalar;
resultMat[6] = mat[6] * scalar;
resultMat[7] = mat[7] * scalar;
resultMat[8] = mat[8] * scalar;
resultMat[9] = mat[9] * scalar;
resultMat[10] = mat[10] * scalar;
resultMat[11] = mat[11] * scalar;
resultMat[12] = mat[12] * scalar;
resultMat[13] = mat[13] * scalar;
resultMat[14] = mat[14] * scalar;
resultMat[15] = mat[15] * scalar;
return resultMat;
};
/**
* Multiplies the two matrices mat0 and mat1 using matrix multiplication,
* storing the result into resultMat.
*
* @param {goog.vec.Mat4.AnyType} mat0 The first (left hand) matrix.
* @param {goog.vec.Mat4.AnyType} mat1 The second (right hand) matrix.
* @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat4.multMat = function(mat0, mat1, resultMat) {
var a00 = mat0[0], a10 = mat0[1], a20 = mat0[2], a30 = mat0[3];
var a01 = mat0[4], a11 = mat0[5], a21 = mat0[6], a31 = mat0[7];
var a02 = mat0[8], a12 = mat0[9], a22 = mat0[10], a32 = mat0[11];
var a03 = mat0[12], a13 = mat0[13], a23 = mat0[14], a33 = mat0[15];
var b00 = mat1[0], b10 = mat1[1], b20 = mat1[2], b30 = mat1[3];
var b01 = mat1[4], b11 = mat1[5], b21 = mat1[6], b31 = mat1[7];
var b02 = mat1[8], b12 = mat1[9], b22 = mat1[10], b32 = mat1[11];
var b03 = mat1[12], b13 = mat1[13], b23 = mat1[14], b33 = mat1[15];
resultMat[0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;
resultMat[1] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;
resultMat[2] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;
resultMat[3] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;
resultMat[4] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;
resultMat[5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;
resultMat[6] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;
resultMat[7] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;
resultMat[8] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;
resultMat[9] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;
resultMat[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;
resultMat[11] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;
resultMat[12] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;
resultMat[13] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;
resultMat[14] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;
resultMat[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;
return resultMat;
};
/**
* Transposes the given matrix mat storing the result into resultMat.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to transpose.
* @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
* the results (may be mat).
* @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Mat4.transpose = function(mat, resultMat) {
if (resultMat == mat) {
var a10 = mat[1], a20 = mat[2], a30 = mat[3];
var a21 = mat[6], a31 = mat[7];
var a32 = mat[11];
resultMat[1] = mat[4];
resultMat[2] = mat[8];
resultMat[3] = mat[12];
resultMat[4] = a10;
resultMat[6] = mat[9];
resultMat[7] = mat[13];
resultMat[8] = a20;
resultMat[9] = a21;
resultMat[11] = mat[14];
resultMat[12] = a30;
resultMat[13] = a31;
resultMat[14] = a32;
} else {
resultMat[0] = mat[0];
resultMat[1] = mat[4];
resultMat[2] = mat[8];
resultMat[3] = mat[12];
resultMat[4] = mat[1];
resultMat[5] = mat[5];
resultMat[6] = mat[9];
resultMat[7] = mat[13];
resultMat[8] = mat[2];
resultMat[9] = mat[6];
resultMat[10] = mat[10];
resultMat[11] = mat[14];
resultMat[12] = mat[3];
resultMat[13] = mat[7];
resultMat[14] = mat[11];
resultMat[15] = mat[15];
}
return resultMat;
};
/**
* Computes the determinant of the matrix.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to compute the matrix for.
* @return {number} The determinant of the matrix.
*/
goog.vec.Mat4.determinant = function(mat) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
var a0 = m00 * m11 - m10 * m01;
var a1 = m00 * m21 - m20 * m01;
var a2 = m00 * m31 - m30 * m01;
var a3 = m10 * m21 - m20 * m11;
var a4 = m10 * m31 - m30 * m11;
var a5 = m20 * m31 - m30 * m21;
var b0 = m02 * m13 - m12 * m03;
var b1 = m02 * m23 - m22 * m03;
var b2 = m02 * m33 - m32 * m03;
var b3 = m12 * m23 - m22 * m13;
var b4 = m12 * m33 - m32 * m13;
var b5 = m22 * m33 - m32 * m23;
return a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
};
/**
* Computes the inverse of mat storing the result into resultMat. If the
* inverse is defined, this function returns true, false otherwise.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix to invert.
* @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
* the result (may be mat).
* @return {boolean} True if the inverse is defined. If false is returned,
* resultMat is not modified.
*/
goog.vec.Mat4.invert = function(mat, resultMat) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
var a0 = m00 * m11 - m10 * m01;
var a1 = m00 * m21 - m20 * m01;
var a2 = m00 * m31 - m30 * m01;
var a3 = m10 * m21 - m20 * m11;
var a4 = m10 * m31 - m30 * m11;
var a5 = m20 * m31 - m30 * m21;
var b0 = m02 * m13 - m12 * m03;
var b1 = m02 * m23 - m22 * m03;
var b2 = m02 * m33 - m32 * m03;
var b3 = m12 * m23 - m22 * m13;
var b4 = m12 * m33 - m32 * m13;
var b5 = m22 * m33 - m32 * m23;
var det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
if (det == 0) {
return false;
}
var idet = 1.0 / det;
resultMat[0] = (m11 * b5 - m21 * b4 + m31 * b3) * idet;
resultMat[1] = (-m10 * b5 + m20 * b4 - m30 * b3) * idet;
resultMat[2] = (m13 * a5 - m23 * a4 + m33 * a3) * idet;
resultMat[3] = (-m12 * a5 + m22 * a4 - m32 * a3) * idet;
resultMat[4] = (-m01 * b5 + m21 * b2 - m31 * b1) * idet;
resultMat[5] = (m00 * b5 - m20 * b2 + m30 * b1) * idet;
resultMat[6] = (-m03 * a5 + m23 * a2 - m33 * a1) * idet;
resultMat[7] = (m02 * a5 - m22 * a2 + m32 * a1) * idet;
resultMat[8] = (m01 * b4 - m11 * b2 + m31 * b0) * idet;
resultMat[9] = (-m00 * b4 + m10 * b2 - m30 * b0) * idet;
resultMat[10] = (m03 * a4 - m13 * a2 + m33 * a0) * idet;
resultMat[11] = (-m02 * a4 + m12 * a2 - m32 * a0) * idet;
resultMat[12] = (-m01 * b3 + m11 * b1 - m21 * b0) * idet;
resultMat[13] = (m00 * b3 - m10 * b1 + m20 * b0) * idet;
resultMat[14] = (-m03 * a3 + m13 * a1 - m23 * a0) * idet;
resultMat[15] = (m02 * a3 - m12 * a1 + m22 * a0) * idet;
return true;
};
/**
* Returns true if the components of mat0 are equal to the components of mat1.
*
* @param {goog.vec.Mat4.AnyType} mat0 The first matrix.
* @param {goog.vec.Mat4.AnyType} mat1 The second matrix.
* @return {boolean} True if the the two matrices are equivalent.
*/
goog.vec.Mat4.equals = function(mat0, mat1) {
return mat0.length == mat1.length &&
mat0[0] == mat1[0] &&
mat0[1] == mat1[1] &&
mat0[2] == mat1[2] &&
mat0[3] == mat1[3] &&
mat0[4] == mat1[4] &&
mat0[5] == mat1[5] &&
mat0[6] == mat1[6] &&
mat0[7] == mat1[7] &&
mat0[8] == mat1[8] &&
mat0[9] == mat1[9] &&
mat0[10] == mat1[10] &&
mat0[11] == mat1[11] &&
mat0[12] == mat1[12] &&
mat0[13] == mat1[13] &&
mat0[14] == mat1[14] &&
mat0[15] == mat1[15];
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec. The input vector is multiplied against the
* upper 3x4 matrix omitting the projective component.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
* @param {goog.vec.Vec3.AnyType} vec The 3 element vector to transform.
* @param {goog.vec.Vec3.AnyType} resultVec The 3 element vector to
* receive the results (may be vec).
* @return {goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Mat4.multVec3 = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8] + mat[12];
resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9] + mat[13];
resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10] + mat[14];
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec. The input vector is multiplied against the
* upper 3x3 matrix omitting the projective component and translation
* components.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
* @param {goog.vec.Vec3.AnyType} vec The 3 element vector to transform.
* @param {goog.vec.Vec3.AnyType} resultVec The 3 element vector to
* receive the results (may be vec).
* @return {goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Mat4.multVec3NoTranslate = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8];
resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9];
resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10];
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec. The input vector is multiplied against the
* full 4x4 matrix with the homogeneous divide applied to reduce the 4 element
* vector to a 3 element vector.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
* @param {goog.vec.Vec3.AnyType} vec The 3 element vector to transform.
* @param {goog.vec.Vec3.AnyType} resultVec The 3 element vector
* to receive the results (may be vec).
* @return {goog.vec.Vec3.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Mat4.multVec3Projective = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
var invw = 1 / (x * mat[3] + y * mat[7] + z * mat[11] + mat[15]);
resultVec[0] = (x * mat[0] + y * mat[4] + z * mat[8] + mat[12]) * invw;
resultVec[1] = (x * mat[1] + y * mat[5] + z * mat[9] + mat[13]) * invw;
resultVec[2] = (x * mat[2] + y * mat[6] + z * mat[10] + mat[14]) * invw;
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
* @param {goog.vec.Vec4.AnyType} vec The vector to transform.
* @param {goog.vec.Vec4.AnyType} resultVec The vector to
* receive the results (may be vec).
* @return {goog.vec.Vec4.AnyType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Mat4.multVec4 = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2], w = vec[3];
resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8] + w * mat[12];
resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9] + w * mat[13];
resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10] + w * mat[14];
resultVec[3] = x * mat[3] + y * mat[7] + z * mat[11] + w * mat[15];
return resultVec;
};
/**
* Makes the given 4x4 matrix a translation matrix with x, y and z
* translation factors.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} x The translation along the x axis.
* @param {number} y The translation along the y axis.
* @param {number} z The translation along the z axis.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeTranslate = function(mat, x, y, z) {
goog.vec.Mat4.makeIdentity(mat);
return goog.vec.Mat4.setColumnValues(mat, 3, x, y, z, 1);
};
/**
* Makes the given 4x4 matrix as a scale matrix with x, y and z scale factors.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} x The scale along the x axis.
* @param {number} y The scale along the y axis.
* @param {number} z The scale along the z axis.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeScale = function(mat, x, y, z) {
goog.vec.Mat4.makeIdentity(mat);
return goog.vec.Mat4.setDiagonalValues(mat, x, y, z, 1);
};
/**
* Makes the given 4x4 matrix a rotation matrix with the given rotation
* angle about the axis defined by the vector (ax, ay, az).
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @param {number} ax The x component of the rotation axis.
* @param {number} ay The y component of the rotation axis.
* @param {number} az The z component of the rotation axis.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeRotate = function(mat, angle, ax, ay, az) {
var c = Math.cos(angle);
var d = 1 - c;
var s = Math.sin(angle);
return goog.vec.Mat4.setFromValues(mat,
ax * ax * d + c,
ax * ay * d + az * s,
ax * az * d - ay * s,
0,
ax * ay * d - az * s,
ay * ay * d + c,
ay * az * d + ax * s,
0,
ax * az * d + ay * s,
ay * az * d - ax * s,
az * az * d + c,
0,
0, 0, 0, 1);
};
/**
* Makes the given 4x4 matrix a rotation matrix with the given rotation
* angle about the X axis.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeRotateX = function(mat, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
return goog.vec.Mat4.setFromValues(
mat, 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1);
};
/**
* Makes the given 4x4 matrix a rotation matrix with the given rotation
* angle about the Y axis.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeRotateY = function(mat, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
return goog.vec.Mat4.setFromValues(
mat, c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1);
};
/**
* Makes the given 4x4 matrix a rotation matrix with the given rotation
* angle about the Z axis.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The rotation angle in radians.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeRotateZ = function(mat, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
return goog.vec.Mat4.setFromValues(
mat, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
};
/**
* Makes the given 4x4 matrix a perspective projection matrix.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} left The coordinate of the left clipping plane.
* @param {number} right The coordinate of the right clipping plane.
* @param {number} bottom The coordinate of the bottom clipping plane.
* @param {number} top The coordinate of the top clipping plane.
* @param {number} near The distance to the near clipping plane.
* @param {number} far The distance to the far clipping plane.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeFrustum = function(mat, left, right, bottom, top, near, far) {
var x = (2 * near) / (right - left);
var y = (2 * near) / (top - bottom);
var a = (right + left) / (right - left);
var b = (top + bottom) / (top - bottom);
var c = -(far + near) / (far - near);
var d = -(2 * far * near) / (far - near);
return goog.vec.Mat4.setFromValues(mat,
x, 0, 0, 0,
0, y, 0, 0,
a, b, c, -1,
0, 0, d, 0
);
};
/**
* Makse the given 4x4 matrix perspective projection matrix given a
* field of view and aspect ratio.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} fovy The field of view along the y (vertical) axis in
* radians.
* @param {number} aspect The x (width) to y (height) aspect ratio.
* @param {number} near The distance to the near clipping plane.
* @param {number} far The distance to the far clipping plane.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makePerspective = function(mat, fovy, aspect, near, far) {
var angle = fovy / 2;
var dz = far - near;
var sinAngle = Math.sin(angle);
if (dz == 0 || sinAngle == 0 || aspect == 0) {
return mat;
}
var cot = Math.cos(angle) / sinAngle;
return goog.vec.Mat4.setFromValues(mat,
cot / aspect, 0, 0, 0,
0, cot, 0, 0,
0, 0, -(far + near) / dz, -1,
0, 0, -(2 * near * far) / dz, 0
);
};
/**
* Makes the given 4x4 matrix an orthographic projection matrix.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} left The coordinate of the left clipping plane.
* @param {number} right The coordinate of the right clipping plane.
* @param {number} bottom The coordinate of the bottom clipping plane.
* @param {number} top The coordinate of the top clipping plane.
* @param {number} near The distance to the near clipping plane.
* @param {number} far The distance to the far clipping plane.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeOrtho = function(mat, left, right, bottom, top, near, far) {
var x = 2 / (right - left);
var y = 2 / (top - bottom);
var z = -2 / (far - near);
var a = -(right + left) / (right - left);
var b = -(top + bottom) / (top - bottom);
var c = -(far + near) / (far - near);
return goog.vec.Mat4.setFromValues(mat,
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
a, b, c, 1
);
};
/**
* Makes the given 4x4 matrix a modelview matrix of a camera so that
* the camera is 'looking at' the given center point.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {goog.vec.Vec3.AnyType} eyePt The position of the eye point
* (camera origin).
* @param {goog.vec.Vec3.AnyType} centerPt The point to aim the camera at.
* @param {goog.vec.Vec3.AnyType} worldUpVec The vector that identifies
* the up direction for the camera.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeLookAt = function(mat, eyePt, centerPt, worldUpVec) {
// Compute the direction vector from the eye point to the center point and
// normalize.
var fwdVec = goog.vec.Mat4.tmpVec4_[0];
goog.vec.Vec3.subtract(centerPt, eyePt, fwdVec);
goog.vec.Vec3.normalize(fwdVec, fwdVec);
fwdVec[3] = 0;
// Compute the side vector from the forward vector and the input up vector.
var sideVec = goog.vec.Mat4.tmpVec4_[1];
goog.vec.Vec3.cross(fwdVec, worldUpVec, sideVec);
goog.vec.Vec3.normalize(sideVec, sideVec);
sideVec[3] = 0;
// Now the up vector to form the orthonormal basis.
var upVec = goog.vec.Mat4.tmpVec4_[2];
goog.vec.Vec3.cross(sideVec, fwdVec, upVec);
goog.vec.Vec3.normalize(upVec, upVec);
upVec[3] = 0;
// Update the view matrix with the new orthonormal basis and position the
// camera at the given eye point.
goog.vec.Vec3.negate(fwdVec, fwdVec);
goog.vec.Mat4.setRow(mat, 0, sideVec);
goog.vec.Mat4.setRow(mat, 1, upVec);
goog.vec.Mat4.setRow(mat, 2, fwdVec);
goog.vec.Mat4.setRowValues(mat, 3, 0, 0, 0, 1);
goog.vec.Mat4.translate(
mat, -eyePt[0], -eyePt[1], -eyePt[2]);
return mat;
};
/**
* Decomposes a matrix into the lookAt vectors eyePt, fwdVec and worldUpVec.
* The matrix represents the modelview matrix of a camera. It is the inverse
* of lookAt except for the output of the fwdVec instead of centerPt.
* The centerPt itself cannot be recovered from a modelview matrix.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {goog.vec.Vec3.AnyType} eyePt The position of the eye point
* (camera origin).
* @param {goog.vec.Vec3.AnyType} fwdVec The vector describing where
* the camera points to.
* @param {goog.vec.Vec3.AnyType} worldUpVec The vector that
* identifies the up direction for the camera.
* @return {boolean} True if the method succeeds, false otherwise.
* The method can only fail if the inverse of viewMatrix is not defined.
*/
goog.vec.Mat4.toLookAt = function(mat, eyePt, fwdVec, worldUpVec) {
// Get eye of the camera.
var matInverse = goog.vec.Mat4.tmpMat4_[0];
if (!goog.vec.Mat4.invert(mat, matInverse)) {
// The input matrix does not have a valid inverse.
return false;
}
if (eyePt) {
eyePt[0] = matInverse[12];
eyePt[1] = matInverse[13];
eyePt[2] = matInverse[14];
}
// Get forward vector from the definition of lookAt.
if (fwdVec || worldUpVec) {
if (!fwdVec) {
fwdVec = goog.vec.Mat4.tmpVec3_[0];
}
fwdVec[0] = -mat[2];
fwdVec[1] = -mat[6];
fwdVec[2] = -mat[10];
// Normalize forward vector.
goog.vec.Vec3.normalize(fwdVec, fwdVec);
}
if (worldUpVec) {
// Get side vector from the definition of gluLookAt.
var side = goog.vec.Mat4.tmpVec3_[1];
side[0] = mat[0];
side[1] = mat[4];
side[2] = mat[8];
// Compute up vector as a up = side x forward.
goog.vec.Vec3.cross(side, fwdVec, worldUpVec);
// Normalize up vector.
goog.vec.Vec3.normalize(worldUpVec, worldUpVec);
}
return true;
};
/**
* Makes the given 4x4 matrix a rotation matrix given Euler angles using
* the ZXZ convention.
* Given the euler angles [theta1, theta2, theta3], the rotation is defined as
* rotation = rotation_z(theta1) * rotation_x(theta2) * rotation_z(theta3),
* with theta1 in [0, 2 * pi], theta2 in [0, pi] and theta3 in [0, 2 * pi].
* rotation_x(theta) means rotation around the X axis of theta radians,
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} theta1 The angle of rotation around the Z axis in radians.
* @param {number} theta2 The angle of rotation around the X axis in radians.
* @param {number} theta3 The angle of rotation around the Z axis in radians.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.makeEulerZXZ = function(mat, theta1, theta2, theta3) {
var c1 = Math.cos(theta1);
var s1 = Math.sin(theta1);
var c2 = Math.cos(theta2);
var s2 = Math.sin(theta2);
var c3 = Math.cos(theta3);
var s3 = Math.sin(theta3);
mat[0] = c1 * c3 - c2 * s1 * s3;
mat[1] = c2 * c1 * s3 + c3 * s1;
mat[2] = s3 * s2;
mat[3] = 0;
mat[4] = -c1 * s3 - c3 * c2 * s1;
mat[5] = c1 * c2 * c3 - s1 * s3;
mat[6] = c3 * s2;
mat[7] = 0;
mat[8] = s2 * s1;
mat[9] = -c1 * s2;
mat[10] = c2;
mat[11] = 0;
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 1;
return mat;
};
/**
* Decomposes a rotation matrix into Euler angles using the ZXZ convention so
* that rotation = rotation_z(theta1) * rotation_x(theta2) * rotation_z(theta3),
* with theta1 in [0, 2 * pi], theta2 in [0, pi] and theta3 in [0, 2 * pi].
* rotation_x(theta) means rotation around the X axis of theta radians.
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {goog.vec.Vec3.AnyType} euler The ZXZ Euler angles in
* radians as [theta1, theta2, theta3].
* @param {boolean=} opt_theta2IsNegative Whether theta2 is in [-pi, 0] instead
* of the default [0, pi].
* @return {goog.vec.Vec4.AnyType} return euler so that operations can be
* chained together.
*/
goog.vec.Mat4.toEulerZXZ = function(mat, euler, opt_theta2IsNegative) {
// There is an ambiguity in the sign of sinTheta2 because of the sqrt.
var sinTheta2 = Math.sqrt(mat[2] * mat[2] + mat[6] * mat[6]);
// By default we explicitely constrain theta2 to be in [0, pi],
// so sinTheta2 is always positive. We can change the behavior and specify
// theta2 to be negative in [-pi, 0] with opt_Theta2IsNegative.
var signTheta2 = opt_theta2IsNegative ? -1 : 1;
if (sinTheta2 > goog.vec.EPSILON) {
euler[2] = Math.atan2(mat[2] * signTheta2, mat[6] * signTheta2);
euler[1] = Math.atan2(sinTheta2 * signTheta2, mat[10]);
euler[0] = Math.atan2(mat[8] * signTheta2, -mat[9] * signTheta2);
} else {
// There is also an arbitrary choice for theta1 = 0 or theta2 = 0 here.
// We assume theta1 = 0 as some applications do not allow the camera to roll
// (i.e. have theta1 != 0).
euler[0] = 0;
euler[1] = Math.atan2(sinTheta2 * signTheta2, mat[10]);
euler[2] = Math.atan2(mat[1], mat[0]);
}
// Atan2 outputs angles in [-pi, pi] so we bring them back to [0, 2 * pi].
euler[0] = (euler[0] + Math.PI * 2) % (Math.PI * 2);
euler[2] = (euler[2] + Math.PI * 2) % (Math.PI * 2);
// For theta2 we want the angle to be in [0, pi] or [-pi, 0] depending on
// signTheta2.
euler[1] = ((euler[1] * signTheta2 + Math.PI * 2) % (Math.PI * 2)) *
signTheta2;
return euler;
};
/**
* Translates the given matrix by x,y,z. Equvialent to:
* goog.vec.Mat4.multMat(
* mat,
* goog.vec.Mat4.makeTranslate(goog.vec.Mat4.create(), x, y, z),
* mat);
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} x The translation along the x axis.
* @param {number} y The translation along the y axis.
* @param {number} z The translation along the z axis.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.translate = function(mat, x, y, z) {
return goog.vec.Mat4.setColumnValues(
mat, 3,
mat[0] * x + mat[4] * y + mat[8] * z + mat[12],
mat[1] * x + mat[5] * y + mat[9] * z + mat[13],
mat[2] * x + mat[6] * y + mat[10] * z + mat[14],
mat[3] * x + mat[7] * y + mat[11] * z + mat[15]);
};
/**
* Scales the given matrix by x,y,z. Equivalent to:
* goog.vec.Mat4.multMat(
* mat,
* goog.vec.Mat4.makeScale(goog.vec.Mat4.create(), x, y, z),
* mat);
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} x The x scale factor.
* @param {number} y The y scale factor.
* @param {number} z The z scale factor.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.scale = function(mat, x, y, z) {
return goog.vec.Mat4.setFromValues(
mat,
mat[0] * x, mat[1] * x, mat[2] * x, mat[3] * x,
mat[4] * y, mat[5] * y, mat[6] * y, mat[7] * y,
mat[8] * z, mat[9] * z, mat[10] * z, mat[11] * z,
mat[12], mat[13], mat[14], mat[15]);
};
/**
* Rotate the given matrix by angle about the x,y,z axis. Equivalent to:
* goog.vec.Mat4.multMat(
* mat,
* goog.vec.Mat4.makeRotate(goog.vec.Mat4.create(), angle, x, y, z),
* mat);
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @param {number} x The x component of the rotation axis.
* @param {number} y The y component of the rotation axis.
* @param {number} z The z component of the rotation axis.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.rotate = function(mat, angle, x, y, z) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
var diffCosAngle = 1 - cosAngle;
var r00 = x * x * diffCosAngle + cosAngle;
var r10 = x * y * diffCosAngle + z * sinAngle;
var r20 = x * z * diffCosAngle - y * sinAngle;
var r01 = x * y * diffCosAngle - z * sinAngle;
var r11 = y * y * diffCosAngle + cosAngle;
var r21 = y * z * diffCosAngle + x * sinAngle;
var r02 = x * z * diffCosAngle + y * sinAngle;
var r12 = y * z * diffCosAngle - x * sinAngle;
var r22 = z * z * diffCosAngle + cosAngle;
return goog.vec.Mat4.setFromValues(
mat,
m00 * r00 + m01 * r10 + m02 * r20,
m10 * r00 + m11 * r10 + m12 * r20,
m20 * r00 + m21 * r10 + m22 * r20,
m30 * r00 + m31 * r10 + m32 * r20,
m00 * r01 + m01 * r11 + m02 * r21,
m10 * r01 + m11 * r11 + m12 * r21,
m20 * r01 + m21 * r11 + m22 * r21,
m30 * r01 + m31 * r11 + m32 * r21,
m00 * r02 + m01 * r12 + m02 * r22,
m10 * r02 + m11 * r12 + m12 * r22,
m20 * r02 + m21 * r12 + m22 * r22,
m30 * r02 + m31 * r12 + m32 * r22,
m03, m13, m23, m33);
};
/**
* Rotate the given matrix by angle about the x axis. Equivalent to:
* goog.vec.Mat4.multMat(
* mat,
* goog.vec.Mat4.makeRotateX(goog.vec.Mat4.create(), angle),
* mat);
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.rotateX = function(mat, angle) {
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var c = Math.cos(angle);
var s = Math.sin(angle);
mat[4] = m01 * c + m02 * s;
mat[5] = m11 * c + m12 * s;
mat[6] = m21 * c + m22 * s;
mat[7] = m31 * c + m32 * s;
mat[8] = m01 * -s + m02 * c;
mat[9] = m11 * -s + m12 * c;
mat[10] = m21 * -s + m22 * c;
mat[11] = m31 * -s + m32 * c;
return mat;
};
/**
* Rotate the given matrix by angle about the y axis. Equivalent to:
* goog.vec.Mat4.multMat(
* mat,
* goog.vec.Mat4.makeRotateY(goog.vec.Mat4.create(), angle),
* mat);
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.rotateY = function(mat, angle) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var c = Math.cos(angle);
var s = Math.sin(angle);
mat[0] = m00 * c + m02 * -s;
mat[1] = m10 * c + m12 * -s;
mat[2] = m20 * c + m22 * -s;
mat[3] = m30 * c + m32 * -s;
mat[8] = m00 * s + m02 * c;
mat[9] = m10 * s + m12 * c;
mat[10] = m20 * s + m22 * c;
mat[11] = m30 * s + m32 * c;
return mat;
};
/**
* Rotate the given matrix by angle about the z axis. Equivalent to:
* goog.vec.Mat4.multMat(
* mat,
* goog.vec.Mat4.makeRotateZ(goog.vec.Mat4.create(), angle),
* mat);
*
* @param {goog.vec.Mat4.AnyType} mat The matrix.
* @param {number} angle The angle in radians.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.rotateZ = function(mat, angle) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var c = Math.cos(angle);
var s = Math.sin(angle);
mat[0] = m00 * c + m01 * s;
mat[1] = m10 * c + m11 * s;
mat[2] = m20 * c + m21 * s;
mat[3] = m30 * c + m31 * s;
mat[4] = m00 * -s + m01 * c;
mat[5] = m10 * -s + m11 * c;
mat[6] = m20 * -s + m21 * c;
mat[7] = m30 * -s + m31 * c;
return mat;
};
/**
* Retrieves the translation component of the transformation matrix.
*
* @param {goog.vec.Mat4.AnyType} mat The transformation matrix.
* @param {goog.vec.Vec3.AnyType} translation The vector for storing the
* result.
* @return {goog.vec.Mat4.AnyType} return mat so that operations can be
* chained.
*/
goog.vec.Mat4.getTranslation = function(mat, translation) {
translation[0] = mat[12];
translation[1] = mat[13];
translation[2] = mat[14];
return translation;
};
/**
* @type {Array.<goog.vec.Vec3.Type>}
* @private
*/
goog.vec.Mat4.tmpVec3_ = [
goog.vec.Vec3.createFloat64(),
goog.vec.Vec3.createFloat64()
];
/**
* @type {Array.<goog.vec.Vec4.Type>}
* @private
*/
goog.vec.Mat4.tmpVec4_ = [
goog.vec.Vec4.createFloat64(),
goog.vec.Vec4.createFloat64(),
goog.vec.Vec4.createFloat64()
];
/**
* @type {Array.<goog.vec.Mat4.Type>}
* @private
*/
goog.vec.Mat4.tmpMat4_ = [
goog.vec.Mat4.createFloat64()
];
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview WARNING: DEPRECATED. Use Mat4 instead.
* Implements 4x4 matrices and their related functions which are
* compatible with WebGL. The API is structured to avoid unnecessary memory
* allocations. The last parameter will typically be the output vector and
* an object can be both an input and output parameter to all methods except
* where noted. Matrix operations follow the mathematical form when multiplying
* vectors as follows: resultVec = matrix * vec.
*
*/
goog.provide('goog.vec.Matrix4');
goog.require('goog.vec');
goog.require('goog.vec.Vec3');
goog.require('goog.vec.Vec4');
/**
* @typedef {goog.vec.ArrayType}
*/
goog.vec.Matrix4.Type;
/**
* Creates the array representation of a 4x4 matrix. The use of the array
* directly eliminates any overhead associated with the class representation
* defined above. The returned matrix is cleared to all zeros.
*
* @return {goog.vec.Matrix4.Type} The new, sixteen element array.
*/
goog.vec.Matrix4.create = function() {
return new Float32Array(16);
};
/**
* Creates the array representation of a 4x4 matrix. The use of the array
* directly eliminates any overhead associated with the class representation
* defined above. The returned matrix is initialized with the identity
*
* @return {goog.vec.Matrix4.Type} The new, sixteen element array.
*/
goog.vec.Matrix4.createIdentity = function() {
var mat = goog.vec.Matrix4.create();
mat[0] = mat[5] = mat[10] = mat[15] = 1;
return mat;
};
/**
* Creates a 4x4 matrix initialized from the given array.
*
* @param {goog.vec.ArrayType} matrix The array containing the
* matrix values in column major order.
* @return {goog.vec.Matrix4.Type} The new, 16 element array.
*/
goog.vec.Matrix4.createFromArray = function(matrix) {
var newMatrix = goog.vec.Matrix4.create();
goog.vec.Matrix4.setFromArray(newMatrix, matrix);
return newMatrix;
};
/**
* Creates a 4x4 matrix initialized from the given values.
*
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v30 The values at (3, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v31 The values at (3, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @param {number} v32 The values at (3, 2).
* @param {number} v03 The values at (0, 3).
* @param {number} v13 The values at (1, 3).
* @param {number} v23 The values at (2, 3).
* @param {number} v33 The values at (3, 3).
* @return {goog.vec.Matrix4.Type} The new, 16 element array.
*/
goog.vec.Matrix4.createFromValues = function(
v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
v03, v13, v23, v33) {
var newMatrix = goog.vec.Matrix4.create();
goog.vec.Matrix4.setFromValues(
newMatrix, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
v03, v13, v23, v33);
return newMatrix;
};
/**
* Creates a clone of a 4x4 matrix.
*
* @param {goog.vec.Matrix4.Type} matrix The source 4x4 matrix.
* @return {goog.vec.Matrix4.Type} The new, 16 element matrix.
*/
goog.vec.Matrix4.clone =
goog.vec.Matrix4.createFromArray;
/**
* Retrieves the element at the requested row and column.
*
* @param {goog.vec.ArrayType} mat The matrix containing the
* value to retrieve.
* @param {number} row The row index.
* @param {number} column The column index.
* @return {number} The element value at the requested row, column indices.
*/
goog.vec.Matrix4.getElement = function(mat, row, column) {
return mat[row + column * 4];
};
/**
* Sets the element at the requested row and column.
*
* @param {goog.vec.ArrayType} mat The matrix containing the
* value to retrieve.
* @param {number} row The row index.
* @param {number} column The column index.
* @param {number} value The value to set at the requested row, column.
*/
goog.vec.Matrix4.setElement = function(mat, row, column, value) {
mat[row + column * 4] = value;
};
/**
* Initializes the matrix from the set of values. Note the values supplied are
* in column major order.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} v00 The values at (0, 0).
* @param {number} v10 The values at (1, 0).
* @param {number} v20 The values at (2, 0).
* @param {number} v30 The values at (3, 0).
* @param {number} v01 The values at (0, 1).
* @param {number} v11 The values at (1, 1).
* @param {number} v21 The values at (2, 1).
* @param {number} v31 The values at (3, 1).
* @param {number} v02 The values at (0, 2).
* @param {number} v12 The values at (1, 2).
* @param {number} v22 The values at (2, 2).
* @param {number} v32 The values at (3, 2).
* @param {number} v03 The values at (0, 3).
* @param {number} v13 The values at (1, 3).
* @param {number} v23 The values at (2, 3).
* @param {number} v33 The values at (3, 3).
*/
goog.vec.Matrix4.setFromValues = function(
mat, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
v03, v13, v23, v33) {
mat[0] = v00;
mat[1] = v10;
mat[2] = v20;
mat[3] = v30;
mat[4] = v01;
mat[5] = v11;
mat[6] = v21;
mat[7] = v31;
mat[8] = v02;
mat[9] = v12;
mat[10] = v22;
mat[11] = v32;
mat[12] = v03;
mat[13] = v13;
mat[14] = v23;
mat[15] = v33;
};
/**
* Sets the matrix from the array of values stored in column major order.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} values The column major ordered
* array of values to store in the matrix.
*/
goog.vec.Matrix4.setFromArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[1];
mat[2] = values[2];
mat[3] = values[3];
mat[4] = values[4];
mat[5] = values[5];
mat[6] = values[6];
mat[7] = values[7];
mat[8] = values[8];
mat[9] = values[9];
mat[10] = values[10];
mat[11] = values[11];
mat[12] = values[12];
mat[13] = values[13];
mat[14] = values[14];
mat[15] = values[15];
};
/**
* Sets the matrix from the array of values stored in row major order.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} values The row major ordered array of
* values to store in the matrix.
*/
goog.vec.Matrix4.setFromRowMajorArray = function(mat, values) {
mat[0] = values[0];
mat[1] = values[4];
mat[2] = values[8];
mat[3] = values[12];
mat[4] = values[1];
mat[5] = values[5];
mat[6] = values[9];
mat[7] = values[13];
mat[8] = values[2];
mat[9] = values[6];
mat[10] = values[10];
mat[11] = values[14];
mat[12] = values[3];
mat[13] = values[7];
mat[14] = values[11];
mat[15] = values[15];
};
/**
* Sets the diagonal values of the matrix from the given values.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} v00 The values for (0, 0).
* @param {number} v11 The values for (1, 1).
* @param {number} v22 The values for (2, 2).
* @param {number} v33 The values for (3, 3).
*/
goog.vec.Matrix4.setDiagonalValues = function(
mat, v00, v11, v22, v33) {
mat[0] = v00;
mat[5] = v11;
mat[10] = v22;
mat[15] = v33;
};
/**
* Sets the diagonal values of the matrix from the given vector.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} vec The vector containing the
* values.
*/
goog.vec.Matrix4.setDiagonal = function(mat, vec) {
mat[0] = vec[0];
mat[5] = vec[1];
mat[10] = vec[2];
mat[15] = vec[3];
};
/**
* Sets the specified column with the supplied values.
*
* @param {goog.vec.ArrayType} mat The matrix to recieve the
* values.
* @param {number} column The column index to set the values on.
* @param {number} v0 The value for row 0.
* @param {number} v1 The value for row 1.
* @param {number} v2 The value for row 2.
* @param {number} v3 The value for row 3.
*/
goog.vec.Matrix4.setColumnValues = function(
mat, column, v0, v1, v2, v3) {
var i = column * 4;
mat[i] = v0;
mat[i + 1] = v1;
mat[i + 2] = v2;
mat[i + 3] = v3;
};
/**
* Sets the specified column with the value from the supplied array.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} column The column index to set the values on.
* @param {goog.vec.ArrayType} vec The vector of elements for the
* column.
*/
goog.vec.Matrix4.setColumn = function(mat, column, vec) {
var i = column * 4;
mat[i] = vec[0];
mat[i + 1] = vec[1];
mat[i + 2] = vec[2];
mat[i + 3] = vec[3];
};
/**
* Retrieves the specified column from the matrix into the given vector
* array.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* values.
* @param {number} column The column to get the values from.
* @param {goog.vec.ArrayType} vec The vector of elements to
* receive the column.
*/
goog.vec.Matrix4.getColumn = function(mat, column, vec) {
var i = column * 4;
vec[0] = mat[i];
vec[1] = mat[i + 1];
vec[2] = mat[i + 2];
vec[3] = mat[i + 3];
};
/**
* Sets the columns of the matrix from the set of vector elements.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} vec0 The values for column 0.
* @param {goog.vec.ArrayType} vec1 The values for column 1.
* @param {goog.vec.ArrayType} vec2 The values for column 2.
* @param {goog.vec.ArrayType} vec3 The values for column 3.
*/
goog.vec.Matrix4.setColumns = function(
mat, vec0, vec1, vec2, vec3) {
goog.vec.Matrix4.setColumn(mat, 0, vec0);
goog.vec.Matrix4.setColumn(mat, 1, vec1);
goog.vec.Matrix4.setColumn(mat, 2, vec2);
goog.vec.Matrix4.setColumn(mat, 3, vec3);
};
/**
* Retrieves the column values from the given matrix into the given vector
* elements.
*
* @param {goog.vec.ArrayType} mat The matrix containing the
* columns to retrieve.
* @param {goog.vec.ArrayType} vec0 The vector elements to receive
* column 0.
* @param {goog.vec.ArrayType} vec1 The vector elements to receive
* column 1.
* @param {goog.vec.ArrayType} vec2 The vector elements to receive
* column 2.
* @param {goog.vec.ArrayType} vec3 The vector elements to receive
* column 3.
*/
goog.vec.Matrix4.getColumns = function(
mat, vec0, vec1, vec2, vec3) {
goog.vec.Matrix4.getColumn(mat, 0, vec0);
goog.vec.Matrix4.getColumn(mat, 1, vec1);
goog.vec.Matrix4.getColumn(mat, 2, vec2);
goog.vec.Matrix4.getColumn(mat, 3, vec3);
};
/**
* Sets the row values from the supplied values.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {number} row The index of the row to receive the values.
* @param {number} v0 The value for column 0.
* @param {number} v1 The value for column 1.
* @param {number} v2 The value for column 2.
* @param {number} v3 The value for column 3.
*/
goog.vec.Matrix4.setRowValues = function(mat, row, v0, v1, v2, v3) {
mat[row] = v0;
mat[row + 4] = v1;
mat[row + 8] = v2;
mat[row + 12] = v3;
};
/**
* Sets the row values from the supplied vector.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* row values.
* @param {number} row The index of the row.
* @param {goog.vec.ArrayType} vec The vector containing the
* values.
*/
goog.vec.Matrix4.setRow = function(mat, row, vec) {
mat[row] = vec[0];
mat[row + 4] = vec[1];
mat[row + 8] = vec[2];
mat[row + 12] = vec[3];
};
/**
* Retrieves the row values into the given vector.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* values.
* @param {number} row The index of the row supplying the values.
* @param {goog.vec.ArrayType} vec The vector to receive the
* row.
*/
goog.vec.Matrix4.getRow = function(mat, row, vec) {
vec[0] = mat[row];
vec[1] = mat[row + 4];
vec[2] = mat[row + 8];
vec[3] = mat[row + 12];
};
/**
* Sets the rows of the matrix from the supplied vectors.
*
* @param {goog.vec.ArrayType} mat The matrix to receive the
* values.
* @param {goog.vec.ArrayType} vec0 The values for row 0.
* @param {goog.vec.ArrayType} vec1 The values for row 1.
* @param {goog.vec.ArrayType} vec2 The values for row 2.
* @param {goog.vec.ArrayType} vec3 The values for row 3.
*/
goog.vec.Matrix4.setRows = function(
mat, vec0, vec1, vec2, vec3) {
goog.vec.Matrix4.setRow(mat, 0, vec0);
goog.vec.Matrix4.setRow(mat, 1, vec1);
goog.vec.Matrix4.setRow(mat, 2, vec2);
goog.vec.Matrix4.setRow(mat, 3, vec3);
};
/**
* Retrieves the rows of the matrix into the supplied vectors.
*
* @param {goog.vec.ArrayType} mat The matrix to supply the
* values.
* @param {goog.vec.ArrayType} vec0 The vector to receive row 0.
* @param {goog.vec.ArrayType} vec1 The vector to receive row 1.
* @param {goog.vec.ArrayType} vec2 The vector to receive row 2.
* @param {goog.vec.ArrayType} vec3 The vector to receive row 3.
*/
goog.vec.Matrix4.getRows = function(
mat, vec0, vec1, vec2, vec3) {
goog.vec.Matrix4.getRow(mat, 0, vec0);
goog.vec.Matrix4.getRow(mat, 1, vec1);
goog.vec.Matrix4.getRow(mat, 2, vec2);
goog.vec.Matrix4.getRow(mat, 3, vec3);
};
/**
* Clears the given matrix to zero.
*
* @param {goog.vec.ArrayType} mat The matrix to clear.
*/
goog.vec.Matrix4.setZero = function(mat) {
mat[0] = 0;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 0;
mat[5] = 0;
mat[6] = 0;
mat[7] = 0;
mat[8] = 0;
mat[9] = 0;
mat[10] = 0;
mat[11] = 0;
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 0;
};
/**
* Sets the given matrix to the identity matrix.
*
* @param {goog.vec.ArrayType} mat The matrix to set.
*/
goog.vec.Matrix4.setIdentity = function(mat) {
mat[0] = 1;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 0;
mat[5] = 1;
mat[6] = 0;
mat[7] = 0;
mat[8] = 0;
mat[9] = 0;
mat[10] = 1;
mat[11] = 0;
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 1;
};
/**
* Performs a per-component addition of the matrix mat0 and mat1, storing
* the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The first addend.
* @param {goog.vec.ArrayType} mat1 The second addend.
* @param {goog.vec.ArrayType} resultMat The matrix to
* receive the results (may be either mat0 or mat1).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix4.add = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] + mat1[0];
resultMat[1] = mat0[1] + mat1[1];
resultMat[2] = mat0[2] + mat1[2];
resultMat[3] = mat0[3] + mat1[3];
resultMat[4] = mat0[4] + mat1[4];
resultMat[5] = mat0[5] + mat1[5];
resultMat[6] = mat0[6] + mat1[6];
resultMat[7] = mat0[7] + mat1[7];
resultMat[8] = mat0[8] + mat1[8];
resultMat[9] = mat0[9] + mat1[9];
resultMat[10] = mat0[10] + mat1[10];
resultMat[11] = mat0[11] + mat1[11];
resultMat[12] = mat0[12] + mat1[12];
resultMat[13] = mat0[13] + mat1[13];
resultMat[14] = mat0[14] + mat1[14];
resultMat[15] = mat0[15] + mat1[15];
return resultMat;
};
/**
* Performs a per-component subtraction of the matrix mat0 and mat1,
* storing the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The minuend.
* @param {goog.vec.ArrayType} mat1 The subtrahend.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix4.subtract = function(mat0, mat1, resultMat) {
resultMat[0] = mat0[0] - mat1[0];
resultMat[1] = mat0[1] - mat1[1];
resultMat[2] = mat0[2] - mat1[2];
resultMat[3] = mat0[3] - mat1[3];
resultMat[4] = mat0[4] - mat1[4];
resultMat[5] = mat0[5] - mat1[5];
resultMat[6] = mat0[6] - mat1[6];
resultMat[7] = mat0[7] - mat1[7];
resultMat[8] = mat0[8] - mat1[8];
resultMat[9] = mat0[9] - mat1[9];
resultMat[10] = mat0[10] - mat1[10];
resultMat[11] = mat0[11] - mat1[11];
resultMat[12] = mat0[12] - mat1[12];
resultMat[13] = mat0[13] - mat1[13];
resultMat[14] = mat0[14] - mat1[14];
resultMat[15] = mat0[15] - mat1[15];
return resultMat;
};
/**
* Performs a component-wise multiplication of mat0 with the given scalar
* storing the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The matrix to scale.
* @param {number} scalar The scalar value to multiple to each element of mat0.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be mat0).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix4.scale = function(mat0, scalar, resultMat) {
resultMat[0] = mat0[0] * scalar;
resultMat[1] = mat0[1] * scalar;
resultMat[2] = mat0[2] * scalar;
resultMat[3] = mat0[3] * scalar;
resultMat[4] = mat0[4] * scalar;
resultMat[5] = mat0[5] * scalar;
resultMat[6] = mat0[6] * scalar;
resultMat[7] = mat0[7] * scalar;
resultMat[8] = mat0[8] * scalar;
resultMat[9] = mat0[9] * scalar;
resultMat[10] = mat0[10] * scalar;
resultMat[11] = mat0[11] * scalar;
resultMat[12] = mat0[12] * scalar;
resultMat[13] = mat0[13] * scalar;
resultMat[14] = mat0[14] * scalar;
resultMat[15] = mat0[15] * scalar;
return resultMat;
};
/**
* Multiplies the two matrices mat0 and mat1 using matrix multiplication,
* storing the result into resultMat.
*
* @param {goog.vec.ArrayType} mat0 The first (left hand) matrix.
* @param {goog.vec.ArrayType} mat1 The second (right hand)
* matrix.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be either mat0 or mat1).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix4.multMat = function(mat0, mat1, resultMat) {
var a00 = mat0[0], a10 = mat0[1], a20 = mat0[2], a30 = mat0[3];
var a01 = mat0[4], a11 = mat0[5], a21 = mat0[6], a31 = mat0[7];
var a02 = mat0[8], a12 = mat0[9], a22 = mat0[10], a32 = mat0[11];
var a03 = mat0[12], a13 = mat0[13], a23 = mat0[14], a33 = mat0[15];
var b00 = mat1[0], b10 = mat1[1], b20 = mat1[2], b30 = mat1[3];
var b01 = mat1[4], b11 = mat1[5], b21 = mat1[6], b31 = mat1[7];
var b02 = mat1[8], b12 = mat1[9], b22 = mat1[10], b32 = mat1[11];
var b03 = mat1[12], b13 = mat1[13], b23 = mat1[14], b33 = mat1[15];
resultMat[0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;
resultMat[1] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;
resultMat[2] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;
resultMat[3] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;
resultMat[4] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;
resultMat[5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;
resultMat[6] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;
resultMat[7] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;
resultMat[8] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;
resultMat[9] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;
resultMat[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;
resultMat[11] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;
resultMat[12] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;
resultMat[13] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;
resultMat[14] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;
resultMat[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;
return resultMat;
};
/**
* Transposes the given matrix mat storing the result into resultMat.
* @param {goog.vec.ArrayType} mat The matrix to transpose.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the results (may be mat).
* @return {goog.vec.ArrayType} return resultMat so that operations can be
* chained together.
*/
goog.vec.Matrix4.transpose = function(mat, resultMat) {
if (resultMat == mat) {
var a10 = mat[1], a20 = mat[2], a30 = mat[3];
var a21 = mat[6], a31 = mat[7];
var a32 = mat[11];
resultMat[1] = mat[4];
resultMat[2] = mat[8];
resultMat[3] = mat[12];
resultMat[4] = a10;
resultMat[6] = mat[9];
resultMat[7] = mat[13];
resultMat[8] = a20;
resultMat[9] = a21;
resultMat[11] = mat[14];
resultMat[12] = a30;
resultMat[13] = a31;
resultMat[14] = a32;
} else {
resultMat[0] = mat[0];
resultMat[1] = mat[4];
resultMat[2] = mat[8];
resultMat[3] = mat[12];
resultMat[4] = mat[1];
resultMat[5] = mat[5];
resultMat[6] = mat[9];
resultMat[7] = mat[13];
resultMat[8] = mat[2];
resultMat[9] = mat[6];
resultMat[10] = mat[10];
resultMat[11] = mat[14];
resultMat[12] = mat[3];
resultMat[13] = mat[7];
resultMat[14] = mat[11];
resultMat[15] = mat[15];
}
return resultMat;
};
/**
* Computes the determinant of the matrix.
*
* @param {goog.vec.ArrayType} mat The matrix to compute the
* matrix for.
* @return {number} The determinant of the matrix.
*/
goog.vec.Matrix4.determinant = function(mat) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
var a0 = m00 * m11 - m10 * m01;
var a1 = m00 * m21 - m20 * m01;
var a2 = m00 * m31 - m30 * m01;
var a3 = m10 * m21 - m20 * m11;
var a4 = m10 * m31 - m30 * m11;
var a5 = m20 * m31 - m30 * m21;
var b0 = m02 * m13 - m12 * m03;
var b1 = m02 * m23 - m22 * m03;
var b2 = m02 * m33 - m32 * m03;
var b3 = m12 * m23 - m22 * m13;
var b4 = m12 * m33 - m32 * m13;
var b5 = m22 * m33 - m32 * m23;
return a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
};
/**
* Computes the inverse of mat storing the result into resultMat. If the
* inverse is defined, this function returns true, false otherwise.
*
* @param {goog.vec.ArrayType} mat The matrix to invert.
* @param {goog.vec.ArrayType} resultMat The matrix to receive
* the result (may be mat).
* @return {boolean} True if the inverse is defined. If false is returned,
* resultMat is not modified.
*/
goog.vec.Matrix4.invert = function(mat, resultMat) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
var a0 = m00 * m11 - m10 * m01;
var a1 = m00 * m21 - m20 * m01;
var a2 = m00 * m31 - m30 * m01;
var a3 = m10 * m21 - m20 * m11;
var a4 = m10 * m31 - m30 * m11;
var a5 = m20 * m31 - m30 * m21;
var b0 = m02 * m13 - m12 * m03;
var b1 = m02 * m23 - m22 * m03;
var b2 = m02 * m33 - m32 * m03;
var b3 = m12 * m23 - m22 * m13;
var b4 = m12 * m33 - m32 * m13;
var b5 = m22 * m33 - m32 * m23;
var det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
if (det == 0) {
return false;
}
var idet = 1.0 / det;
resultMat[0] = (m11 * b5 - m21 * b4 + m31 * b3) * idet;
resultMat[1] = (-m10 * b5 + m20 * b4 - m30 * b3) * idet;
resultMat[2] = (m13 * a5 - m23 * a4 + m33 * a3) * idet;
resultMat[3] = (-m12 * a5 + m22 * a4 - m32 * a3) * idet;
resultMat[4] = (-m01 * b5 + m21 * b2 - m31 * b1) * idet;
resultMat[5] = (m00 * b5 - m20 * b2 + m30 * b1) * idet;
resultMat[6] = (-m03 * a5 + m23 * a2 - m33 * a1) * idet;
resultMat[7] = (m02 * a5 - m22 * a2 + m32 * a1) * idet;
resultMat[8] = (m01 * b4 - m11 * b2 + m31 * b0) * idet;
resultMat[9] = (-m00 * b4 + m10 * b2 - m30 * b0) * idet;
resultMat[10] = (m03 * a4 - m13 * a2 + m33 * a0) * idet;
resultMat[11] = (-m02 * a4 + m12 * a2 - m32 * a0) * idet;
resultMat[12] = (-m01 * b3 + m11 * b1 - m21 * b0) * idet;
resultMat[13] = (m00 * b3 - m10 * b1 + m20 * b0) * idet;
resultMat[14] = (-m03 * a3 + m13 * a1 - m23 * a0) * idet;
resultMat[15] = (m02 * a3 - m12 * a1 + m22 * a0) * idet;
return true;
};
/**
* Returns true if the components of mat0 are equal to the components of mat1.
*
* @param {goog.vec.ArrayType} mat0 The first matrix.
* @param {goog.vec.ArrayType} mat1 The second matrix.
* @return {boolean} True if the the two matrices are equivalent.
*/
goog.vec.Matrix4.equals = function(mat0, mat1) {
return mat0.length == mat1.length &&
mat0[0] == mat1[0] &&
mat0[1] == mat1[1] &&
mat0[2] == mat1[2] &&
mat0[3] == mat1[3] &&
mat0[4] == mat1[4] &&
mat0[5] == mat1[5] &&
mat0[6] == mat1[6] &&
mat0[7] == mat1[7] &&
mat0[8] == mat1[8] &&
mat0[9] == mat1[9] &&
mat0[10] == mat1[10] &&
mat0[11] == mat1[11] &&
mat0[12] == mat1[12] &&
mat0[13] == mat1[13] &&
mat0[14] == mat1[14] &&
mat0[15] == mat1[15];
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec. The input vector is multiplied against the
* upper 3x4 matrix omitting the projective component.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* transformation.
* @param {goog.vec.ArrayType} vec The 3 element vector to
* transform.
* @param {goog.vec.ArrayType} resultVec The 3 element vector to
* receive the results (may be vec).
* @return {goog.vec.ArrayType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Matrix4.multVec3 = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8] + mat[12];
resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9] + mat[13];
resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10] + mat[14];
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec. The input vector is multiplied against the
* upper 3x3 matrix omitting the projective component and translation
* components.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* transformation.
* @param {goog.vec.ArrayType} vec The 3 element vector to
* transform.
* @param {goog.vec.ArrayType} resultVec The 3 element vector to
* receive the results (may be vec).
* @return {goog.vec.ArrayType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Matrix4.multVec3NoTranslate = function(
mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8];
resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9];
resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10];
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec. The input vector is multiplied against the
* full 4x4 matrix with the homogeneous divide applied to reduce the 4 element
* vector to a 3 element vector.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* transformation.
* @param {goog.vec.ArrayType} vec The 3 element vector to
* transform.
* @param {goog.vec.ArrayType} resultVec The 3 element vector
* to receive the results (may be vec).
* @return {goog.vec.ArrayType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Matrix4.multVec3Projective = function(
mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2];
var invw = 1 / (x * mat[3] + y * mat[7] + z * mat[11] + mat[15]);
resultVec[0] = (x * mat[0] + y * mat[4] + z * mat[8] + mat[12]) * invw;
resultVec[1] = (x * mat[1] + y * mat[5] + z * mat[9] + mat[13]) * invw;
resultVec[2] = (x * mat[2] + y * mat[6] + z * mat[10] + mat[14]) * invw;
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* transformation.
* @param {goog.vec.ArrayType} vec The vector to transform.
* @param {goog.vec.ArrayType} resultVec The vector to
* receive the results (may be vec).
* @return {goog.vec.ArrayType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Matrix4.multVec4 = function(mat, vec, resultVec) {
var x = vec[0], y = vec[1], z = vec[2], w = vec[3];
resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8] + w * mat[12];
resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9] + w * mat[13];
resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10] + w * mat[14];
resultVec[3] = x * mat[3] + y * mat[7] + z * mat[11] + w * mat[15];
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec. The input matrix is multiplied against the
* upper 3x4 matrix omitting the projective component.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* transformation.
* @param {goog.vec.ArrayType} vec The 3 element vector to
* transform.
* @param {goog.vec.ArrayType} resultVec The 3 element vector to
* receive the results (may be vec).
* @return {goog.vec.ArrayType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Matrix4.multVec3ToArray = function(mat, vec, resultVec) {
goog.vec.Matrix4.multVec3(
mat, vec, /** @type {goog.vec.ArrayType} */ (resultVec));
return resultVec;
};
/**
* Transforms the given vector with the given matrix storing the resulting,
* transformed vector into resultVec.
*
* @param {goog.vec.ArrayType} mat The matrix supplying the
* transformation.
* @param {goog.vec.ArrayType} vec The vector to transform.
* @param {goog.vec.ArrayType} resultVec The vector to
* receive the results (may be vec).
* @return {goog.vec.ArrayType} return resultVec so that operations can be
* chained together.
*/
goog.vec.Matrix4.multVec4ToArray = function(mat, vec, resultVec) {
goog.vec.Matrix4.multVec4(
mat, vec, /** @type {goog.vec.ArrayType} */ (resultVec));
return resultVec;
};
/**
* Initializes the given 4x4 matrix as a translation matrix with x, y and z
* translation factors.
* @param {goog.vec.ArrayType} mat The 4x4 (16-element) matrix
* array to receive the new translation matrix.
* @param {number} x The translation along the x axis.
* @param {number} y The translation along the y axis.
* @param {number} z The translation along the z axis.
*/
goog.vec.Matrix4.makeTranslate = function(mat, x, y, z) {
goog.vec.Matrix4.setIdentity(mat);
goog.vec.Matrix4.setColumnValues(mat, 3, x, y, z, 1);
};
/**
* Initializes the given 4x4 matrix as a scale matrix with x, y and z scale
* factors.
* @param {goog.vec.ArrayType} mat The 4x4 (16-element) matrix
* array to receive the new translation matrix.
* @param {number} x The scale along the x axis.
* @param {number} y The scale along the y axis.
* @param {number} z The scale along the z axis.
*/
goog.vec.Matrix4.makeScale = function(mat, x, y, z) {
goog.vec.Matrix4.setIdentity(mat);
goog.vec.Matrix4.setDiagonalValues(mat, x, y, z, 1);
};
/**
* Initializes the given 4x4 matrix as a rotation matrix with the given rotation
* angle about the axis defined by the vector (ax, ay, az).
* @param {goog.vec.ArrayType} mat The 4x4 (16-element) matrix
* array to receive the new translation matrix.
* @param {number} angle The rotation angle in radians.
* @param {number} ax The x component of the rotation axis.
* @param {number} ay The y component of the rotation axis.
* @param {number} az The z component of the rotation axis.
*/
goog.vec.Matrix4.makeAxisAngleRotate = function(
mat, angle, ax, ay, az) {
var c = Math.cos(angle);
var d = 1 - c;
var s = Math.sin(angle);
goog.vec.Matrix4.setFromValues(mat,
ax * ax * d + c,
ax * ay * d + az * s,
ax * az * d - ay * s,
0,
ax * ay * d - az * s,
ay * ay * d + c,
ay * az * d + ax * s,
0,
ax * az * d + ay * s,
ay * az * d - ax * s,
az * az * d + c,
0,
0, 0, 0, 1);
};
/**
* Initializes the given 4x4 matrix as a perspective projection matrix.
* @param {goog.vec.ArrayType} mat The 4x4 (16-element) matrix
* array to receive the new translation matrix.
* @param {number} left The coordinate of the left clipping plane.
* @param {number} right The coordinate of the right clipping plane.
* @param {number} bottom The coordinate of the bottom clipping plane.
* @param {number} top The coordinate of the top clipping plane.
* @param {number} near The distance to the near clipping plane.
* @param {number} far The distance to the far clipping plane.
*/
goog.vec.Matrix4.makeFrustum = function(
mat, left, right, bottom, top, near, far) {
var x = (2 * near) / (right - left);
var y = (2 * near) / (top - bottom);
var a = (right + left) / (right - left);
var b = (top + bottom) / (top - bottom);
var c = -(far + near) / (far - near);
var d = -(2 * far * near) / (far - near);
goog.vec.Matrix4.setFromValues(mat,
x, 0, 0, 0,
0, y, 0, 0,
a, b, c, -1,
0, 0, d, 0
);
};
/**
* Initializes the given 4x4 matrix as a perspective projection matrix given a
* field of view and aspect ratio.
* @param {goog.vec.ArrayType} mat The 4x4 (16-element) matrix
* array to receive the new translation matrix.
* @param {number} fovy The field of view along the y (vertical) axis in
* radians.
* @param {number} aspect The x (width) to y (height) aspect ratio.
* @param {number} near The distance to the near clipping plane.
* @param {number} far The distance to the far clipping plane.
*/
goog.vec.Matrix4.makePerspective = function(
mat, fovy, aspect, near, far) {
var angle = fovy / 2;
var dz = far - near;
var sinAngle = Math.sin(angle);
if (dz == 0 || sinAngle == 0 || aspect == 0) return;
var cot = Math.cos(angle) / sinAngle;
goog.vec.Matrix4.setFromValues(mat,
cot / aspect, 0, 0, 0,
0, cot, 0, 0,
0, 0, -(far + near) / dz, -1,
0, 0, -(2 * near * far) / dz, 0
);
};
/**
* Initializes the given 4x4 matrix as an orthographic projection matrix.
* @param {goog.vec.ArrayType} mat The 4x4 (16-element) matrix
* array to receive the new translation matrix.
* @param {number} left The coordinate of the left clipping plane.
* @param {number} right The coordinate of the right clipping plane.
* @param {number} bottom The coordinate of the bottom clipping plane.
* @param {number} top The coordinate of the top clipping plane.
* @param {number} near The distance to the near clipping plane.
* @param {number} far The distance to the far clipping plane.
*/
goog.vec.Matrix4.makeOrtho = function(
mat, left, right, bottom, top, near, far) {
var x = 2 / (right - left);
var y = 2 / (top - bottom);
var z = -2 / (far - near);
var a = -(right + left) / (right - left);
var b = -(top + bottom) / (top - bottom);
var c = -(far + near) / (far - near);
goog.vec.Matrix4.setFromValues(mat,
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
a, b, c, 1
);
};
/**
* Updates a matrix representing the modelview matrix of a camera so that
* the camera is 'looking at' the given center point.
* @param {goog.vec.ArrayType} viewMatrix The matrix.
* @param {goog.vec.ArrayType} eyePt The position of the eye point
* (camera origin).
* @param {goog.vec.ArrayType} centerPt The point to aim the camera
* at.
* @param {goog.vec.ArrayType} worldUpVec The vector that
* identifies the up direction for the camera.
*/
goog.vec.Matrix4.lookAt = function(
viewMatrix, eyePt, centerPt, worldUpVec) {
// Compute the direction vector from the eye point to the center point and
// normalize.
var fwdVec = goog.vec.Matrix4.tmpVec4_[0];
goog.vec.Vec3.subtract(centerPt, eyePt, fwdVec);
goog.vec.Vec3.normalize(fwdVec, fwdVec);
fwdVec[3] = 0;
// Compute the side vector from the forward vector and the input up vector.
var sideVec = goog.vec.Matrix4.tmpVec4_[1];
goog.vec.Vec3.cross(fwdVec, worldUpVec, sideVec);
goog.vec.Vec3.normalize(sideVec, sideVec);
sideVec[3] = 0;
// Now the up vector to form the orthonormal basis.
var upVec = goog.vec.Matrix4.tmpVec4_[2];
goog.vec.Vec3.cross(sideVec, fwdVec, upVec);
goog.vec.Vec3.normalize(upVec, upVec);
upVec[3] = 0;
// Update the view matrix with the new orthonormal basis and position the
// camera at the given eye point.
goog.vec.Vec3.negate(fwdVec, fwdVec);
goog.vec.Matrix4.setRow(viewMatrix, 0, sideVec);
goog.vec.Matrix4.setRow(viewMatrix, 1, upVec);
goog.vec.Matrix4.setRow(viewMatrix, 2, fwdVec);
goog.vec.Matrix4.setRowValues(viewMatrix, 3, 0, 0, 0, 1);
goog.vec.Matrix4.applyTranslate(
viewMatrix, -eyePt[0], -eyePt[1], -eyePt[2]);
};
/**
* Decomposes a matrix into the lookAt vectors eyePt, fwdVec and worldUpVec.
* The matrix represents the modelview matrix of a camera. It is the inverse
* of lookAt except for the output of the fwdVec instead of centerPt.
* The centerPt itself cannot be recovered from a modelview matrix.
* @param {goog.vec.ArrayType} viewMatrix The matrix.
* @param {goog.vec.ArrayType} eyePt The position of the eye point
* (camera origin).
* @param {goog.vec.ArrayType} fwdVec The vector describing where
* the camera points to.
* @param {goog.vec.ArrayType} worldUpVec The vector that
* identifies the up direction for the camera.
* @return {boolean} True if the method succeeds, false otherwise.
* The method can only fail if the inverse of viewMatrix is not defined.
*/
goog.vec.Matrix4.toLookAt = function(
viewMatrix, eyePt, fwdVec, worldUpVec) {
// Get eye of the camera.
var viewMatrixInverse = goog.vec.Matrix4.tmpMatrix4_[0];
if (!goog.vec.Matrix4.invert(viewMatrix, viewMatrixInverse)) {
// The input matrix does not have a valid inverse.
return false;
}
if (eyePt) {
eyePt[0] = viewMatrixInverse[12];
eyePt[1] = viewMatrixInverse[13];
eyePt[2] = viewMatrixInverse[14];
}
// Get forward vector from the definition of lookAt.
if (fwdVec || worldUpVec) {
if (!fwdVec) {
fwdVec = goog.vec.Matrix4.tmpVec3_[0];
}
fwdVec[0] = -viewMatrix[2];
fwdVec[1] = -viewMatrix[6];
fwdVec[2] = -viewMatrix[10];
// Normalize forward vector.
goog.vec.Vec3.normalize(fwdVec, fwdVec);
}
if (worldUpVec) {
// Get side vector from the definition of gluLookAt.
var side = goog.vec.Matrix4.tmpVec3_[1];
side[0] = viewMatrix[0];
side[1] = viewMatrix[4];
side[2] = viewMatrix[8];
// Compute up vector as a up = side x forward.
goog.vec.Vec3.cross(side, fwdVec, worldUpVec);
// Normalize up vector.
goog.vec.Vec3.normalize(worldUpVec, worldUpVec);
}
return true;
};
/**
* Constructs a rotation matrix from its Euler angles using the ZXZ convention.
* Given the euler angles [theta1, theta2, theta3], the rotation is defined as
* rotation = rotation_z(theta1) * rotation_x(theta2) * rotation_z(theta3),
* where rotation_x(theta) means rotation around the X axis of theta radians.
* @param {goog.vec.ArrayType} matrix The rotation matrix.
* @param {number} theta1 The angle of rotation around the Z axis in radians.
* @param {number} theta2 The angle of rotation around the X axis in radians.
* @param {number} theta3 The angle of rotation around the Z axis in radians.
*/
goog.vec.Matrix4.fromEulerZXZ = function(
matrix, theta1, theta2, theta3) {
var c1 = Math.cos(theta1);
var s1 = Math.sin(theta1);
var c2 = Math.cos(theta2);
var s2 = Math.sin(theta2);
var c3 = Math.cos(theta3);
var s3 = Math.sin(theta3);
matrix[0] = c1 * c3 - c2 * s1 * s3;
matrix[1] = c2 * c1 * s3 + c3 * s1;
matrix[2] = s3 * s2;
matrix[3] = 0;
matrix[4] = -c1 * s3 - c3 * c2 * s1;
matrix[5] = c1 * c2 * c3 - s1 * s3;
matrix[6] = c3 * s2;
matrix[7] = 0;
matrix[8] = s2 * s1;
matrix[9] = -c1 * s2;
matrix[10] = c2;
matrix[11] = 0;
matrix[12] = 0;
matrix[13] = 0;
matrix[14] = 0;
matrix[15] = 1;
};
/**
* Decomposes a rotation matrix into Euler angles using the ZXZ convention.
* @param {goog.vec.ArrayType} matrix The rotation matrix.
* @param {goog.vec.ArrayType} euler The ZXZ Euler angles in
* radians. euler = [roll, tilt, pan].
*/
goog.vec.Matrix4.toEulerZXZ = function(matrix, euler) {
var s2 = Math.sqrt(matrix[2] * matrix[2] + matrix[6] * matrix[6]);
// There is an ambiguity in the sign of s2. We assume the tilt value
// is between [-pi/2, 0], so s2 is always negative.
if (s2 > goog.vec.EPSILON) {
euler[2] = Math.atan2(-matrix[2], -matrix[6]);
euler[1] = Math.atan2(-s2, matrix[10]);
euler[0] = Math.atan2(-matrix[8], matrix[9]);
} else {
// There is also an arbitrary choice for roll = 0 or pan = 0 in this case.
// We assume roll = 0 as some applications do not allow the camera to roll.
euler[0] = 0;
euler[1] = Math.atan2(-s2, matrix[10]);
euler[2] = Math.atan2(matrix[1], matrix[0]);
}
};
/**
* Applies a translation by x,y,z to the given matrix.
*
* @param {goog.vec.ArrayType} mat The matrix.
* @param {number} x The translation along the x axis.
* @param {number} y The translation along the y axis.
* @param {number} z The translation along the z axis.
*/
goog.vec.Matrix4.applyTranslate = function(mat, x, y, z) {
goog.vec.Matrix4.setColumnValues(
mat, 3,
mat[0] * x + mat[4] * y + mat[8] * z + mat[12],
mat[1] * x + mat[5] * y + mat[9] * z + mat[13],
mat[2] * x + mat[6] * y + mat[10] * z + mat[14],
mat[3] * x + mat[7] * y + mat[11] * z + mat[15]);
};
/**
* Applies an x,y,z scale to the given matrix.
*
* @param {goog.vec.ArrayType} mat The matrix.
* @param {number} x The x scale factor.
* @param {number} y The y scale factor.
* @param {number} z The z scale factor.
*/
goog.vec.Matrix4.applyScale = function(mat, x, y, z) {
goog.vec.Matrix4.setFromValues(
mat,
mat[0] * x, mat[1] * x, mat[2] * x, mat[3] * x,
mat[4] * y, mat[5] * y, mat[6] * y, mat[7] * y,
mat[8] * z, mat[9] * z, mat[10] * z, mat[11] * z,
mat[12], mat[13], mat[14], mat[15]);
};
/**
* Applies a rotation by angle about the x,y,z axis to the given matrix.
*
* @param {goog.vec.ArrayType} mat The matrix.
* @param {number} angle The angle in radians.
* @param {number} x The x component of the rotation axis.
* @param {number} y The y component of the rotation axis.
* @param {number} z The z component of the rotation axis.
*/
goog.vec.Matrix4.applyRotate = function(mat, angle, x, y, z) {
var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
var diffCosAngle = 1 - cosAngle;
var r00 = x * x * diffCosAngle + cosAngle;
var r10 = x * y * diffCosAngle + z * sinAngle;
var r20 = x * z * diffCosAngle - y * sinAngle;
var r01 = x * y * diffCosAngle - z * sinAngle;
var r11 = y * y * diffCosAngle + cosAngle;
var r21 = y * z * diffCosAngle + x * sinAngle;
var r02 = x * z * diffCosAngle + y * sinAngle;
var r12 = y * z * diffCosAngle - x * sinAngle;
var r22 = z * z * diffCosAngle + cosAngle;
goog.vec.Matrix4.setFromValues(
mat,
m00 * r00 + m01 * r10 + m02 * r20,
m10 * r00 + m11 * r10 + m12 * r20,
m20 * r00 + m21 * r10 + m22 * r20,
m30 * r00 + m31 * r10 + m32 * r20,
m00 * r01 + m01 * r11 + m02 * r21,
m10 * r01 + m11 * r11 + m12 * r21,
m20 * r01 + m21 * r11 + m22 * r21,
m30 * r01 + m31 * r11 + m32 * r21,
m00 * r02 + m01 * r12 + m02 * r22,
m10 * r02 + m11 * r12 + m12 * r22,
m20 * r02 + m21 * r12 + m22 * r22,
m30 * r02 + m31 * r12 + m32 * r22,
m03, m13, m23, m33);
};
/**
* @type {Array.<goog.vec.Vec3.Type>}
* @private
*/
goog.vec.Matrix4.tmpVec3_ = [
goog.vec.Vec3.createNumber(),
goog.vec.Vec3.createNumber()
];
/**
* @type {Array.<goog.vec.Vec4.Type>}
* @private
*/
goog.vec.Matrix4.tmpVec4_ = [
goog.vec.Vec4.createNumber(),
goog.vec.Vec4.createNumber(),
goog.vec.Vec4.createNumber()
];
/**
* @type {Array.<goog.vec.Matrix4.Type>}
* @private
*/
goog.vec.Matrix4.tmpMatrix4_ = [
goog.vec.Matrix4.create()
];
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Supplies a Float32Array implementation that implements
* most of the Float32Array spec and that can be used when a built-in
* implementation is not available.
*
* Note that if no existing Float32Array implementation is found then
* this class and all its public properties are exported as Float32Array.
*
* Adding support for the other TypedArray classes here does not make sense
* since this vector math library only needs Float32Array.
*
*/
goog.provide('goog.vec.Float32Array');
/**
* Constructs a new Float32Array. The new array is initialized to all zeros.
*
* @param {goog.vec.Float32Array|Array|ArrayBuffer|number} p0
* The length of the array, or an array to initialize the contents of the
* new Float32Array.
* @constructor
*/
goog.vec.Float32Array = function(p0) {
this.length = p0.length || p0;
for (var i = 0; i < this.length; i++) {
this[i] = p0[i] || 0;
}
};
/**
* The number of bytes in an element (as defined by the Typed Array
* specification).
*
* @type {number}
*/
goog.vec.Float32Array.BYTES_PER_ELEMENT = 4;
/**
* The number of bytes in an element (as defined by the Typed Array
* specification).
*
* @type {number}
*/
goog.vec.Float32Array.prototype.BYTES_PER_ELEMENT = 4;
/**
* Sets elements of the array.
* @param {Array.<number>|Float32Array} values The array of values.
* @param {number=} opt_offset The offset in this array to start.
*/
goog.vec.Float32Array.prototype.set = function(values, opt_offset) {
opt_offset = opt_offset || 0;
for (var i = 0; i < values.length && opt_offset + i < this.length; i++) {
this[opt_offset + i] = values[i];
}
};
/**
* Creates a string representation of this array.
* @return {string} The string version of this array.
* @override
*/
goog.vec.Float32Array.prototype.toString = Array.prototype.join;
/**
* Note that we cannot implement the subarray() or (deprecated) slice()
* methods properly since doing so would require being able to overload
* the [] operator which is not possible in javascript. So we leave
* them unimplemented. Any attempt to call these methods will just result
* in a javascript error since we leave them undefined.
*/
/**
* If no existing Float32Array implementation is found then we export
* goog.vec.Float32Array as Float32Array.
*/
if (typeof Float32Array == 'undefined') {
goog.exportProperty(goog.vec.Float32Array, 'BYTES_PER_ELEMENT',
goog.vec.Float32Array.BYTES_PER_ELEMENT);
goog.exportProperty(goog.vec.Float32Array.prototype, 'BYTES_PER_ELEMENT',
goog.vec.Float32Array.prototype.BYTES_PER_ELEMENT);
goog.exportProperty(goog.vec.Float32Array.prototype, 'set',
goog.vec.Float32Array.prototype.set);
goog.exportProperty(goog.vec.Float32Array.prototype, 'toString',
goog.vec.Float32Array.prototype.toString);
goog.exportSymbol('Float32Array', goog.vec.Float32Array);
}
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A wrapper for the HTML5 FileSaver object.
*
*/
goog.provide('goog.fs.FileSaver');
goog.provide('goog.fs.FileSaver.EventType');
goog.provide('goog.fs.FileSaver.ProgressEvent');
goog.provide('goog.fs.FileSaver.ReadyState');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.fs.Error');
goog.require('goog.fs.ProgressEvent');
/**
* An object for monitoring the saving of files. This emits ProgressEvents of
* the types listed in {@link goog.fs.FileSaver.EventType}.
*
* This should not be instantiated directly. Instead, its subclass
* {@link goog.fs.FileWriter} should be accessed via
* {@link goog.fs.FileEntry#createWriter}.
*
* @param {!FileSaver} fileSaver The underlying FileSaver object.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.fs.FileSaver = function(fileSaver) {
goog.base(this);
/**
* The underlying FileSaver object.
*
* @type {!FileSaver}
* @private
*/
this.saver_ = fileSaver;
this.saver_.onwritestart = goog.bind(this.dispatchProgressEvent_, this);
this.saver_.onprogress = goog.bind(this.dispatchProgressEvent_, this);
this.saver_.onwrite = goog.bind(this.dispatchProgressEvent_, this);
this.saver_.onabort = goog.bind(this.dispatchProgressEvent_, this);
this.saver_.onerror = goog.bind(this.dispatchProgressEvent_, this);
this.saver_.onwriteend = goog.bind(this.dispatchProgressEvent_, this);
};
goog.inherits(goog.fs.FileSaver, goog.events.EventTarget);
/**
* Possible states for a FileSaver.
*
* @enum {number}
*/
goog.fs.FileSaver.ReadyState = {
/**
* The object has been constructed, but there is no pending write.
*/
INIT: 0,
/**
* Data is being written.
*/
WRITING: 1,
/**
* The data has been written to the file, the write was aborted, or an error
* occurred.
*/
DONE: 2
};
/**
* Events emitted by a FileSaver.
*
* @enum {string}
*/
goog.fs.FileSaver.EventType = {
/**
* Emitted when the writing begins. readyState will be WRITING.
*/
WRITE_START: 'writestart',
/**
* Emitted when progress has been made in saving the file. readyState will be
* WRITING.
*/
PROGRESS: 'progress',
/**
* Emitted when the data has been successfully written. readyState will be
* WRITING.
*/
WRITE: 'write',
/**
* Emitted when the writing has been aborted. readyState will be WRITING.
*/
ABORT: 'abort',
/**
* Emitted when an error is encountered or the writing has been aborted.
* readyState will be WRITING.
*/
ERROR: 'error',
/**
* Emitted when the writing is finished, whether successfully or not.
* readyState will be DONE.
*/
WRITE_END: 'writeend'
};
/**
* Abort the writing of the file.
*/
goog.fs.FileSaver.prototype.abort = function() {
try {
this.saver_.abort();
} catch (e) {
throw new goog.fs.Error(e.code, 'aborting save');
}
};
/**
* @return {goog.fs.FileSaver.ReadyState} The current state of the FileSaver.
*/
goog.fs.FileSaver.prototype.getReadyState = function() {
return /** @type {goog.fs.FileSaver.ReadyState} */ (this.saver_.readyState);
};
/**
* @return {goog.fs.Error} The error encountered while writing, if any.
*/
goog.fs.FileSaver.prototype.getError = function() {
return this.saver_.error &&
new goog.fs.Error(this.saver_.error.code, 'saving file');
};
/**
* Wrap a progress event emitted by the underlying file saver and re-emit it.
*
* @param {!ProgressEvent} event The underlying event.
* @private
*/
goog.fs.FileSaver.prototype.dispatchProgressEvent_ = function(event) {
this.dispatchEvent(new goog.fs.ProgressEvent(event, this));
};
/** @override */
goog.fs.FileSaver.prototype.disposeInternal = function() {
delete this.saver_;
goog.base(this, 'disposeInternal');
};
/**
* A wrapper for the progress events emitted by the FileSaver.
*
* @deprecated Use {goog.fs.ProgressEvent}.
*/
goog.fs.FileSaver.ProgressEvent = goog.fs.ProgressEvent;
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A wrapper for the HTML5 File ProgressEvent objects.
*
*/
goog.provide('goog.fs.ProgressEvent');
goog.require('goog.events.Event');
/**
* A wrapper for the progress events emitted by the File APIs.
*
* @param {!ProgressEvent} event The underlying event object.
* @param {!Object} target The file access object emitting the event.
* @extends {goog.events.Event}
* @constructor
*/
goog.fs.ProgressEvent = function(event, target) {
goog.base(this, event.type, target);
/**
* The underlying event object.
* @type {!ProgressEvent}
* @private
*/
this.event_ = event;
};
goog.inherits(goog.fs.ProgressEvent, goog.events.Event);
/**
* @return {boolean} Whether or not the total size of the of the file being
* saved is known.
*/
goog.fs.ProgressEvent.prototype.isLengthComputable = function() {
return this.event_.lengthComputable;
};
/**
* @return {number} The number of bytes saved so far.
*/
goog.fs.ProgressEvent.prototype.getLoaded = function() {
return this.event_.loaded;
};
/**
* @return {number} The total number of bytes in the file being saved.
*/
goog.fs.ProgressEvent.prototype.getTotal = function() {
return this.event_.total;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A wrapper for the HTML5 FileError object.
*
*/
goog.provide('goog.fs.Error');
goog.provide('goog.fs.Error.ErrorCode');
goog.require('goog.debug.Error');
goog.require('goog.string');
/**
* A filesystem error. Since the filesystem API is asynchronous, stack traces
* are less useful for identifying where errors come from, so this includes a
* large amount of metadata in the message.
*
* @param {number} code The error code for the error.
* @param {string} action The action being undertaken when the error was raised.
* @constructor
* @extends {goog.debug.Error}
*/
goog.fs.Error = function(code, action) {
goog.base(this, goog.string.subs('Error %s: %s', action,
goog.fs.Error.getDebugMessage(code)));
this.code = /** @type {goog.fs.Error.ErrorCode} */ (code);
};
goog.inherits(goog.fs.Error, goog.debug.Error);
/**
* Error codes for file errors.
* @see http://www.w3.org/TR/file-system-api/#idl-def-FileException
*
* @enum {number}
*/
goog.fs.Error.ErrorCode = {
NOT_FOUND: 1,
SECURITY: 2,
ABORT: 3,
NOT_READABLE: 4,
ENCODING: 5,
NO_MODIFICATION_ALLOWED: 6,
INVALID_STATE: 7,
SYNTAX: 8,
INVALID_MODIFICATION: 9,
QUOTA_EXCEEDED: 10,
TYPE_MISMATCH: 11,
PATH_EXISTS: 12
};
/**
* @param {number} errorCode The error code for the error.
* @return {string} A debug message for the given error code. These messages are
* for debugging only and are not localized.
*/
goog.fs.Error.getDebugMessage = function(errorCode) {
switch (errorCode) {
case goog.fs.Error.ErrorCode.NOT_FOUND:
return 'File or directory not found';
case goog.fs.Error.ErrorCode.SECURITY:
return 'Insecure or disallowed operation';
case goog.fs.Error.ErrorCode.ABORT:
return 'Operation aborted';
case goog.fs.Error.ErrorCode.NOT_READABLE:
return 'File or directory not readable';
case goog.fs.Error.ErrorCode.ENCODING:
return 'Invalid encoding';
case goog.fs.Error.ErrorCode.NO_MODIFICATION_ALLOWED:
return 'Cannot modify file or directory';
case goog.fs.Error.ErrorCode.INVALID_STATE:
return 'Invalid state';
case goog.fs.Error.ErrorCode.SYNTAX:
return 'Invalid line-ending specifier';
case goog.fs.Error.ErrorCode.INVALID_MODIFICATION:
return 'Invalid modification';
case goog.fs.Error.ErrorCode.QUOTA_EXCEEDED:
return 'Quota exceeded';
case goog.fs.Error.ErrorCode.TYPE_MISMATCH:
return 'Invalid filetype';
case goog.fs.Error.ErrorCode.PATH_EXISTS:
return 'File or directory already exists at specified path';
default:
return 'Unrecognized error';
}
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrappers for the HTML5 File API. These wrappers closely mirror
* the underlying APIs, but use Closure-style events and Deferred return values.
* Their existence also makes it possible to mock the FileSystem API for testing
* in browsers that don't support it natively.
*
* When adding public functions to anything under this namespace, be sure to add
* its mock counterpart to goog.testing.fs.
*
*/
goog.provide('goog.fs');
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.events');
goog.require('goog.fs.Error');
goog.require('goog.fs.FileReader');
goog.require('goog.fs.FileSystem');
goog.require('goog.userAgent');
/**
* Get a wrapped FileSystem object.
*
* @param {goog.fs.FileSystemType_} type The type of the filesystem to get.
* @param {number} size The size requested for the filesystem, in bytes.
* @return {!goog.async.Deferred} The deferred {@link goog.fs.FileSystem}. If an
* error occurs, the errback is called with a {@link goog.fs.Error}.
* @private
*/
goog.fs.get_ = function(type, size) {
var requestFileSystem = goog.global.requestFileSystem ||
goog.global.webkitRequestFileSystem;
if (!goog.isFunction(requestFileSystem)) {
return goog.async.Deferred.fail(new Error('File API unsupported'));
}
var d = new goog.async.Deferred();
requestFileSystem(type, size, function(fs) {
d.callback(new goog.fs.FileSystem(fs));
}, function(err) {
d.errback(new goog.fs.Error(err.code, 'requesting filesystem'));
});
return d;
};
/**
* The two types of filesystem.
*
* @enum {number}
* @private
*/
goog.fs.FileSystemType_ = {
/**
* A temporary filesystem may be deleted by the user agent at its discretion.
*/
TEMPORARY: 0,
/**
* A persistent filesystem will never be deleted without the user's or
* application's authorization.
*/
PERSISTENT: 1
};
/**
* Returns a temporary FileSystem object. A temporary filesystem may be deleted
* by the user agent at its discretion.
*
* @param {number} size The size requested for the filesystem, in bytes.
* @return {!goog.async.Deferred} The deferred {@link goog.fs.FileSystem}. If an
* error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.getTemporary = function(size) {
return goog.fs.get_(goog.fs.FileSystemType_.TEMPORARY, size);
};
/**
* Returns a persistent FileSystem object. A persistent filesystem will never be
* deleted without the user's or application's authorization.
*
* @param {number} size The size requested for the filesystem, in bytes.
* @return {!goog.async.Deferred} The deferred {@link goog.fs.FileSystem}. If an
* error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.getPersistent = function(size) {
return goog.fs.get_(goog.fs.FileSystemType_.PERSISTENT, size);
};
/**
* Creates a blob URL for a blob object.
*
* @param {!Blob} blob The object for which to create the URL.
* @return {string} The URL for the object.
*/
goog.fs.createObjectUrl = function(blob) {
return goog.fs.getUrlObject_().createObjectURL(blob);
};
/**
* Revokes a URL created by {@link goog.fs.createObjectUrl}.
*
* @param {string} url The URL to revoke.
*/
goog.fs.revokeObjectUrl = function(url) {
goog.fs.getUrlObject_().revokeObjectURL(url);
};
/**
* @typedef {!{createObjectURL: (function(!Blob): string),
* revokeObjectURL: function(string): void}}
*/
goog.fs.UrlObject_;
/**
* Get the object that has the createObjectURL and revokeObjectURL functions for
* this browser.
*
* @return {goog.fs.UrlObject_} The object for this browser.
* @private
*/
goog.fs.getUrlObject_ = function() {
// This is what the spec says to do
// http://dev.w3.org/2006/webapi/FileAPI/#dfn-createObjectURL
if (goog.isDef(goog.global.URL) &&
goog.isDef(goog.global.URL.createObjectURL)) {
return /** @type {goog.fs.UrlObject_} */ (goog.global.URL);
// This is what Chrome does (as of 10.0.648.6 dev)
} else if (goog.isDef(goog.global.webkitURL) &&
goog.isDef(goog.global.webkitURL.createObjectURL)) {
return /** @type {goog.fs.UrlObject_} */ (goog.global.webkitURL);
// This is what the spec used to say to do
} else if (goog.isDef(goog.global.createObjectURL)) {
return /** @type {goog.fs.UrlObject_} */ (goog.global);
} else {
throw Error('This browser doesn\'t seem to support blob URLs');
}
};
/**
* Concatenates one or more values together and converts them to a Blob.
*
* @param {...(string|!Blob|!ArrayBuffer)} var_args The values that will make up
* the resulting blob.
* @return {!Blob} The blob.
*/
goog.fs.getBlob = function(var_args) {
var BlobBuilder = goog.global.BlobBuilder || goog.global.WebKitBlobBuilder;
if (goog.isDef(BlobBuilder)) {
var bb = new BlobBuilder();
for (var i = 0; i < arguments.length; i++) {
bb.append(arguments[i]);
}
return bb.getBlob();
} else {
return new Blob(goog.array.toArray(arguments));
}
};
/**
* Converts a Blob or a File into a string. This should only be used when the
* blob is known to be small.
*
* @param {!Blob} blob The blob to convert.
* @param {string=} opt_encoding The name of the encoding to use.
* @return {!goog.async.Deferred} The deferred string. If an error occurrs, the
* errback is called with a {@link goog.fs.Error}.
* @deprecated Use {@link goog.fs.FileReader.readAsText} instead.
*/
goog.fs.blobToString = function(blob, opt_encoding) {
return goog.fs.FileReader.readAsText(blob, opt_encoding);
};
/**
* Slices the blob. The returned blob contains data from the start byte
* (inclusive) till the end byte (exclusive). Negative indices can be used
* to count bytes from the end of the blob (-1 == blob.size - 1). Indices
* are always clamped to blob range. If end is omitted, all the data till
* the end of the blob is taken.
*
* @param {!Blob} blob The blob to be sliced.
* @param {number} start Index of the starting byte.
* @param {number=} opt_end Index of the ending byte.
* @return {Blob} The blob slice or null if not supported.
*/
goog.fs.sliceBlob = function(blob, start, opt_end) {
if (!goog.isDef(opt_end)) {
opt_end = blob.size;
}
if (blob.webkitSlice) {
// Natively accepts negative indices, clamping to the blob range and
// range end is optional. See http://trac.webkit.org/changeset/83873
return blob.webkitSlice(start, opt_end);
} else if (blob.mozSlice) {
// Natively accepts negative indices, clamping to the blob range and
// range end is optional. See https://developer.mozilla.org/en/DOM/Blob
// and http://hg.mozilla.org/mozilla-central/rev/dae833f4d934
return blob.mozSlice(start, opt_end);
} else if (blob.slice) {
// Old versions of Firefox and Chrome use the original specification.
// Negative indices are not accepted, only range end is clamped and
// range end specification is obligatory.
// See http://www.w3.org/TR/2009/WD-FileAPI-20091117/
if ((goog.userAgent.GECKO && !goog.userAgent.isVersion('13.0')) ||
(goog.userAgent.WEBKIT && !goog.userAgent.isVersion('537.1'))) {
if (start < 0) {
start += blob.size;
}
if (start < 0) {
start = 0;
}
if (opt_end < 0) {
opt_end += blob.size;
}
if (opt_end < start) {
opt_end = start;
}
return blob.slice(start, opt_end - start);
}
// IE and the latest versions of Firefox and Chrome use the new
// specification. Natively accepts negative indices, clamping to the blob
// range and range end is optional.
// See http://dev.w3.org/2006/webapi/FileAPI/
return blob.slice(start, opt_end);
}
return null;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrappers for HTML5 Entry objects. These are all in the same
* file to avoid circular dependency issues.
*
* When adding or modifying functionality in this namespace, be sure to update
* the mock counterparts in goog.testing.fs.
*
*/
goog.provide('goog.fs.DirectoryEntry');
goog.provide('goog.fs.DirectoryEntry.Behavior');
goog.provide('goog.fs.Entry');
goog.provide('goog.fs.FileEntry');
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.fs.Error');
goog.require('goog.fs.FileWriter');
goog.require('goog.functions');
goog.require('goog.string');
/**
* The abstract class for entries in the filesystem.
*
* @param {!goog.fs.FileSystem} fs The wrapped filesystem.
* @param {!Entry} entry The underlying Entry object.
* @constructor
*/
goog.fs.Entry = function(fs, entry) {
/**
* The wrapped filesystem.
*
* @type {!goog.fs.FileSystem}
* @private
*/
this.fs_ = fs;
/**
* The underlying Entry object.
*
* @type {!Entry}
* @private
*/
this.entry_ = entry;
};
/**
* @return {boolean} Whether or not this entry is a file.
*/
goog.fs.Entry.prototype.isFile = function() {
return this.entry_.isFile;
};
/**
* @return {boolean} Whether or not this entry is a directory.
*/
goog.fs.Entry.prototype.isDirectory = function() {
return this.entry_.isDirectory;
};
/**
* @return {string} The name of this entry.
*/
goog.fs.Entry.prototype.getName = function() {
return this.entry_.name;
};
/**
* @return {string} The full path to this entry.
*/
goog.fs.Entry.prototype.getFullPath = function() {
return this.entry_.fullPath;
};
/**
* @return {!goog.fs.FileSystem} The filesystem backing this entry.
*/
goog.fs.Entry.prototype.getFileSystem = function() {
return this.fs_;
};
/**
* Retrieves the last modified date for this entry.
*
* @return {!goog.async.Deferred} The deferred Date for this entry. If an error
* occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.Entry.prototype.getLastModified = function() {
return this.getMetadata().addCallback(function(metadata) {
return metadata.modificationTime;
});
};
/**
* Retrieves the metadata for this entry.
*
* @return {!goog.async.Deferred} The deferred Metadata for this entry. If an
* error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.Entry.prototype.getMetadata = function() {
var d = new goog.async.Deferred();
this.entry_.getMetadata(
function(metadata) { d.callback(metadata); },
goog.bind(function(err) {
var msg = 'retrieving metadata for ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Move this entry to a new location.
*
* @param {!goog.fs.DirectoryEntry} parent The new parent directory.
* @param {string=} opt_newName The new name of the entry. If omitted, the entry
* retains its original name.
* @return {!goog.async.Deferred} The deferred {@link goog.fs.FileEntry} or
* {@link goog.fs.DirectoryEntry} for the new entry. If an error occurs, the
* errback is called with a {@link goog.fs.Error}.
*/
goog.fs.Entry.prototype.moveTo = function(parent, opt_newName) {
var d = new goog.async.Deferred();
this.entry_.moveTo(
parent.dir_, opt_newName,
goog.bind(function(entry) { d.callback(this.wrapEntry(entry)); }, this),
goog.bind(function(err) {
var msg = 'moving ' + this.getFullPath() + ' into ' +
parent.getFullPath() +
(opt_newName ? ', renaming to ' + opt_newName : '');
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Copy this entry to a new location.
*
* @param {!goog.fs.DirectoryEntry} parent The new parent directory.
* @param {string=} opt_newName The name of the new entry. If omitted, the new
* entry has the same name as the original.
* @return {!goog.async.Deferred} The deferred {@link goog.fs.FileEntry} or
* {@link goog.fs.DirectoryEntry} for the new entry. If an error occurs, the
* errback is called with a {@link goog.fs.Error}.
*/
goog.fs.Entry.prototype.copyTo = function(parent, opt_newName) {
var d = new goog.async.Deferred();
this.entry_.copyTo(
parent.dir_, opt_newName,
goog.bind(function(entry) { d.callback(this.wrapEntry(entry)); }, this),
goog.bind(function(err) {
var msg = 'copying ' + this.getFullPath() + ' into ' +
parent.getFullPath() +
(opt_newName ? ', renaming to ' + opt_newName : '');
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Wrap an HTML5 entry object in an appropriate subclass instance.
*
* @param {!Entry} entry The underlying Entry object.
* @return {!goog.fs.Entry} The appropriate subclass wrapper.
* @protected
*/
goog.fs.Entry.prototype.wrapEntry = function(entry) {
return entry.isFile ?
new goog.fs.FileEntry(this.fs_, /** @type {!FileEntry} */ (entry)) :
new goog.fs.DirectoryEntry(
this.fs_, /** @type {!DirectoryEntry} */ (entry));
};
/**
* Get the URL for this file.
*
* @param {string=} opt_mimeType The MIME type that will be served for the URL.
* @return {string} The URL.
*/
goog.fs.Entry.prototype.toUrl = function(opt_mimeType) {
return this.entry_.toURL(opt_mimeType);
};
/**
* Get the URI for this file.
*
* @deprecated Use {@link #toUrl} instead.
* @param {string=} opt_mimeType The MIME type that will be served for the URI.
* @return {string} The URI.
*/
goog.fs.Entry.prototype.toUri = goog.fs.Entry.prototype.toUrl;
/**
* Remove this entry.
*
* @return {!goog.async.Deferred} A deferred object. If the removal succeeds,
* the callback is called with true. If an error occurs, the errback is
* called a {@link goog.fs.Error}.
*/
goog.fs.Entry.prototype.remove = function() {
var d = new goog.async.Deferred();
this.entry_.remove(
goog.bind(d.callback, d, true /* result */),
goog.bind(function(err) {
var msg = 'removing ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Gets the parent directory.
*
* @return {!goog.async.Deferred} The deferred {@link goog.fs.DirectoryEntry}.
* If an error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.Entry.prototype.getParent = function() {
var d = new goog.async.Deferred();
this.entry_.getParent(
goog.bind(function(parent) {
d.callback(new goog.fs.DirectoryEntry(this.fs_, parent));
}, this),
goog.bind(function(err) {
var msg = 'getting parent of ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* A directory in a local FileSystem.
*
* This should not be instantiated directly. Instead, it should be accessed via
* {@link goog.fs.FileSystem#getRoot} or
* {@link goog.fs.DirectoryEntry#getDirectoryEntry}.
*
* @param {!goog.fs.FileSystem} fs The wrapped filesystem.
* @param {!DirectoryEntry} dir The underlying DirectoryEntry object.
* @constructor
* @extends {goog.fs.Entry}
*/
goog.fs.DirectoryEntry = function(fs, dir) {
goog.base(this, fs, dir);
/**
* The underlying DirectoryEntry object.
*
* @type {!DirectoryEntry}
* @private
*/
this.dir_ = dir;
};
goog.inherits(goog.fs.DirectoryEntry, goog.fs.Entry);
/**
* Behaviors for getting files and directories.
* @enum {number}
*/
goog.fs.DirectoryEntry.Behavior = {
/**
* Get the file if it exists, error out if it doesn't.
*/
DEFAULT: 1,
/**
* Get the file if it exists, create it if it doesn't.
*/
CREATE: 2,
/**
* Error out if the file exists, create it if it doesn't.
*/
CREATE_EXCLUSIVE: 3
};
/**
* Get a file in the directory.
*
* @param {string} path The path to the file, relative to this directory.
* @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior The behavior for
* handling an existing file, or the lack thereof.
* @return {!goog.async.Deferred} The deferred {@link goog.fs.FileEntry}. If an
* error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.DirectoryEntry.prototype.getFile = function(path, opt_behavior) {
var d = new goog.async.Deferred();
this.dir_.getFile(
path, this.getOptions_(opt_behavior),
goog.bind(function(entry) {
d.callback(new goog.fs.FileEntry(this.fs_, entry));
}, this),
goog.bind(function(err) {
var msg = 'loading file ' + path + ' from ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Get a directory within this directory.
*
* @param {string} path The path to the directory, relative to this directory.
* @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior The behavior for
* handling an existing directory, or the lack thereof.
* @return {!goog.async.Deferred} The deferred {@link goog.fs.DirectoryEntry}.
* If an error occurs, the errback is called a {@link goog.fs.Error}.
*/
goog.fs.DirectoryEntry.prototype.getDirectory = function(path, opt_behavior) {
var d = new goog.async.Deferred();
this.dir_.getDirectory(
path, this.getOptions_(opt_behavior),
goog.bind(function(entry) {
d.callback(new goog.fs.DirectoryEntry(this.fs_, entry));
}, this),
goog.bind(function(err) {
var msg = 'loading directory ' + path + ' from ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Opens the directory for the specified path, creating the directory and any
* intermediate directories as necessary.
*
* @param {string} path The directory path to create. May be absolute or
* relative to the current directory. The parent directory ".." and current
* directory "." are supported.
* @return {!goog.async.Deferred} A deferred {@link goog.fs.DirectoryEntry} for
* the requested path. If an error occurs, the errback is called with a
* {@link goog.fs.Error}.
*/
goog.fs.DirectoryEntry.prototype.createPath = function(path) {
// If the path begins at the root, reinvoke createPath on the root directory.
if (goog.string.startsWith(path, '/')) {
var root = this.getFileSystem().getRoot();
if (this.getFullPath() != root.getFullPath()) {
return root.createPath(path);
}
}
// Filter out any empty path components caused by '//' or a leading slash.
var parts = goog.array.filter(path.split('/'), goog.functions.identity);
var existed = [];
function getNextDirectory(dir) {
if (!parts.length) {
return goog.async.Deferred.succeed(dir);
}
var def;
var nextDir = parts.shift();
if (nextDir == '..') {
def = dir.getParent();
} else if (nextDir == '.') {
def = goog.async.Deferred.succeed(dir);
} else {
def = dir.getDirectory(nextDir, goog.fs.DirectoryEntry.Behavior.CREATE);
}
return def.addCallback(getNextDirectory);
}
return getNextDirectory(this);
};
/**
* Gets a list of all entries in this directory.
*
* @return {!goog.async.Deferred} The deferred list of {@link goog.fs.Entry}
* results. If an error occurs, the errback is called with a
* {@link goog.fs.Error}.
*/
goog.fs.DirectoryEntry.prototype.listDirectory = function() {
var d = new goog.async.Deferred();
var reader = this.dir_.createReader();
var results = [];
var errorCallback = goog.bind(function(err) {
var msg = 'listing directory ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this);
var successCallback = goog.bind(function(entries) {
if (entries.length) {
for (var i = 0, entry; entry = entries[i]; i++) {
results.push(this.wrapEntry(entry));
}
reader.readEntries(successCallback, errorCallback);
} else {
d.callback(results);
}
}, this);
reader.readEntries(successCallback, errorCallback);
return d;
};
/**
* Removes this directory and all its contents.
*
* @return {!goog.async.Deferred} A deferred object. If the removal succeeds,
* the callback is called with true. If an error occurs, the errback is
* called a {@link goog.fs.Error}.
*/
goog.fs.DirectoryEntry.prototype.removeRecursively = function() {
var d = new goog.async.Deferred();
this.dir_.removeRecursively(
goog.bind(d.callback, d, true /* result */),
goog.bind(function(err) {
var msg = 'removing ' + this.getFullPath() + ' recursively';
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Converts a value in the Behavior enum into an options object expected by the
* File API.
*
* @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior The behavior for
* existing files.
* @return {Object.<boolean>} The options object expected by the File API.
* @private
*/
goog.fs.DirectoryEntry.prototype.getOptions_ = function(opt_behavior) {
if (opt_behavior == goog.fs.DirectoryEntry.Behavior.CREATE) {
return {'create': true};
} else if (opt_behavior == goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE) {
return {'create': true, 'exclusive': true};
} else {
return {};
}
};
/**
* A file in a local filesystem.
*
* This should not be instantiated directly. Instead, it should be accessed via
* {@link goog.fs.DirectoryEntry#getDirectoryEntry}.
*
* @param {!goog.fs.FileSystem} fs The wrapped filesystem.
* @param {!FileEntry} file The underlying FileEntry object.
* @constructor
* @extends {goog.fs.Entry}
*/
goog.fs.FileEntry = function(fs, file) {
goog.base(this, fs, file);
/**
* The underlying FileEntry object.
*
* @type {!FileEntry}
* @private
*/
this.file_ = file;
};
goog.inherits(goog.fs.FileEntry, goog.fs.Entry);
/**
* Create a writer for writing to the file.
*
* @return {!goog.async.Deferred} The deferred {@link goog.fs.FileWriter}. If an
* error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.FileEntry.prototype.createWriter = function() {
var d = new goog.async.Deferred();
this.file_.createWriter(
function(w) { d.callback(new goog.fs.FileWriter(w)); },
goog.bind(function(err) {
var msg = 'creating writer for ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
/**
* Get the file contents as a File blob.
*
* @return {!goog.async.Deferred} The deferred File. If an error occurs, the
* errback is called with a {@link goog.fs.Error}.
*/
goog.fs.FileEntry.prototype.file = function() {
var d = new goog.async.Deferred();
this.file_.file(
function(f) { d.callback(f); },
goog.bind(function(err) {
var msg = 'getting file for ' + this.getFullPath();
d.errback(new goog.fs.Error(err.code, msg));
}, this));
return d;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A wrapper for the HTML5 FileReader object.
*
*/
goog.provide('goog.fs.FileReader');
goog.provide('goog.fs.FileReader.EventType');
goog.provide('goog.fs.FileReader.ReadyState');
goog.require('goog.async.Deferred');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.fs.Error');
goog.require('goog.fs.ProgressEvent');
/**
* An object for monitoring the reading of files. This emits ProgressEvents of
* the types listed in {@link goog.fs.FileReader.EventType}.
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.fs.FileReader = function() {
goog.base(this);
/**
* The underlying FileReader object.
*
* @type {!FileReader}
* @private
*/
this.reader_ = new FileReader();
this.reader_.onloadstart = goog.bind(this.dispatchProgressEvent_, this);
this.reader_.onprogress = goog.bind(this.dispatchProgressEvent_, this);
this.reader_.onload = goog.bind(this.dispatchProgressEvent_, this);
this.reader_.onabort = goog.bind(this.dispatchProgressEvent_, this);
this.reader_.onerror = goog.bind(this.dispatchProgressEvent_, this);
this.reader_.onloadend = goog.bind(this.dispatchProgressEvent_, this);
};
goog.inherits(goog.fs.FileReader, goog.events.EventTarget);
/**
* Possible states for a FileReader.
*
* @enum {number}
*/
goog.fs.FileReader.ReadyState = {
/**
* The object has been constructed, but there is no pending read.
*/
INIT: 0,
/**
* Data is being read.
*/
LOADING: 1,
/**
* The data has been read from the file, the read was aborted, or an error
* occurred.
*/
DONE: 2
};
/**
* Events emitted by a FileReader.
*
* @enum {string}
*/
goog.fs.FileReader.EventType = {
/**
* Emitted when the reading begins. readyState will be LOADING.
*/
LOAD_START: 'loadstart',
/**
* Emitted when progress has been made in reading the file. readyState will be
* LOADING.
*/
PROGRESS: 'progress',
/**
* Emitted when the data has been successfully read. readyState will be
* LOADING.
*/
LOAD: 'load',
/**
* Emitted when the reading has been aborted. readyState will be LOADING.
*/
ABORT: 'abort',
/**
* Emitted when an error is encountered or the reading has been aborted.
* readyState will be LOADING.
*/
ERROR: 'error',
/**
* Emitted when the reading is finished, whether successfully or not.
* readyState will be DONE.
*/
LOAD_END: 'loadend'
};
/**
* Abort the reading of the file.
*/
goog.fs.FileReader.prototype.abort = function() {
try {
this.reader_.abort();
} catch (e) {
throw new goog.fs.Error(e.code, 'aborting read');
}
};
/**
* @return {goog.fs.FileReader.ReadyState} The current state of the FileReader.
*/
goog.fs.FileReader.prototype.getReadyState = function() {
return /** @type {goog.fs.FileReader.ReadyState} */ (this.reader_.readyState);
};
/**
* @return {*} The result of the file read.
*/
goog.fs.FileReader.prototype.getResult = function() {
return this.reader_.result;
};
/**
* @return {goog.fs.Error} The error encountered while reading, if any.
*/
goog.fs.FileReader.prototype.getError = function() {
return this.reader_.error &&
new goog.fs.Error(this.reader_.error.code, 'reading file');
};
/**
* Wrap a progress event emitted by the underlying file reader and re-emit it.
*
* @param {!ProgressEvent} event The underlying event.
* @private
*/
goog.fs.FileReader.prototype.dispatchProgressEvent_ = function(event) {
this.dispatchEvent(new goog.fs.ProgressEvent(event, this));
};
/** @override */
goog.fs.FileReader.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
delete this.reader_;
};
/**
* Starts reading a blob as a binary string.
* @param {!Blob} blob The blob to read.
*/
goog.fs.FileReader.prototype.readAsBinaryString = function(blob) {
this.reader_.readAsBinaryString(blob);
};
/**
* Reads a blob as a binary string.
* @param {!Blob} blob The blob to read.
* @return {!goog.async.Deferred} The deferred Blob contents as a binary string.
* If an error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.FileReader.readAsBinaryString = function(blob) {
var reader = new goog.fs.FileReader();
var d = goog.fs.FileReader.createDeferred_(reader);
reader.readAsBinaryString(blob);
return d;
};
/**
* Starts reading a blob as an array buffer.
* @param {!Blob} blob The blob to read.
*/
goog.fs.FileReader.prototype.readAsArrayBuffer = function(blob) {
this.reader_.readAsArrayBuffer(blob);
};
/**
* Reads a blob as an array buffer.
* @param {!Blob} blob The blob to read.
* @return {!goog.async.Deferred} The deferred Blob contents as an array buffer.
* If an error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.FileReader.readAsArrayBuffer = function(blob) {
var reader = new goog.fs.FileReader();
var d = goog.fs.FileReader.createDeferred_(reader);
reader.readAsArrayBuffer(blob);
return d;
};
/**
* Starts reading a blob as text.
* @param {!Blob} blob The blob to read.
* @param {string=} opt_encoding The name of the encoding to use.
*/
goog.fs.FileReader.prototype.readAsText = function(blob, opt_encoding) {
this.reader_.readAsText(blob, opt_encoding);
};
/**
* Reads a blob as text.
* @param {!Blob} blob The blob to read.
* @param {string=} opt_encoding The name of the encoding to use.
* @return {!goog.async.Deferred} The deferred Blob contents as text.
* If an error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.FileReader.readAsText = function(blob, opt_encoding) {
var reader = new goog.fs.FileReader();
var d = goog.fs.FileReader.createDeferred_(reader);
reader.readAsText(blob, opt_encoding);
return d;
};
/**
* Starts reading a blob as a data URL.
* @param {!Blob} blob The blob to read.
*/
goog.fs.FileReader.prototype.readAsDataUrl = function(blob) {
this.reader_.readAsDataURL(blob);
};
/**
* Reads a blob as a data URL.
* @param {!Blob} blob The blob to read.
* @return {!goog.async.Deferred} The deferred Blob contents as a data URL.
* If an error occurs, the errback is called with a {@link goog.fs.Error}.
*/
goog.fs.FileReader.readAsDataUrl = function(blob) {
var reader = new goog.fs.FileReader();
var d = goog.fs.FileReader.createDeferred_(reader);
reader.readAsDataUrl(blob);
return d;
};
/**
* Creates a new deferred object for the results of a read method.
* @param {goog.fs.FileReader} reader The reader to create a deferred for.
* @return {!goog.async.Deferred} The deferred results.
* @private
*/
goog.fs.FileReader.createDeferred_ = function(reader) {
var deferred = new goog.async.Deferred();
reader.addEventListener(goog.fs.FileReader.EventType.LOAD_END,
goog.partial(function(d, r, e) {
var result = r.getResult();
var error = r.getError();
if (result != null && !error) {
d.callback(result);
} else {
d.errback(error);
}
r.dispose();
}, deferred, reader));
return deferred;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A wrapper for the HTML5 FileSystem object.
*
*/
goog.provide('goog.fs.FileSystem');
goog.require('goog.fs.DirectoryEntry');
/**
* A local filesystem.
*
* This shouldn't be instantiated directly. Instead, it should be accessed via
* {@link goog.fs.getTemporary} or {@link goog.fs.getPersistent}.
*
* @param {!FileSystem} fs The underlying FileSystem object.
* @constructor
*/
goog.fs.FileSystem = function(fs) {
/**
* The underlying FileSystem object.
*
* @type {!FileSystem}
* @private
*/
this.fs_ = fs;
};
/**
* @return {string} The name of the filesystem.
*/
goog.fs.FileSystem.prototype.getName = function() {
return this.fs_.name;
};
/**
* @return {!goog.fs.DirectoryEntry} The root directory of the filesystem.
*/
goog.fs.FileSystem.prototype.getRoot = function() {
return new goog.fs.DirectoryEntry(this, this.fs_.root);
};
/**
* @return {!FileSystem} The underlying FileSystem object.
*/
goog.fs.FileSystem.prototype.getBrowserFileSystem = function() {
return this.fs_;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A wrapper for the HTML5 FileWriter object.
*
* When adding or modifying functionality in this namespace, be sure to update
* the mock counterparts in goog.testing.fs.
*
*/
goog.provide('goog.fs.FileWriter');
goog.require('goog.fs.Error');
goog.require('goog.fs.FileSaver');
/**
* An object for monitoring the saving of files, as well as other fine-grained
* writing operations.
*
* This should not be instantiated directly. Instead, it should be accessed via
* {@link goog.fs.FileEntry#createWriter}.
*
* @param {!FileWriter} writer The underlying FileWriter object.
* @constructor
* @extends {goog.fs.FileSaver}
*/
goog.fs.FileWriter = function(writer) {
goog.base(this, writer);
/**
* The underlying FileWriter object.
*
* @type {!FileWriter}
* @private
*/
this.writer_ = writer;
};
goog.inherits(goog.fs.FileWriter, goog.fs.FileSaver);
/**
* @return {number} The byte offset at which the next write will occur.
*/
goog.fs.FileWriter.prototype.getPosition = function() {
return this.writer_.position;
};
/**
* @return {number} The length of the file.
*/
goog.fs.FileWriter.prototype.getLength = function() {
return this.writer_.length;
};
/**
* Write data to the file.
*
* @param {!Blob} blob The data to write.
*/
goog.fs.FileWriter.prototype.write = function(blob) {
try {
this.writer_.write(blob);
} catch (e) {
throw new goog.fs.Error(e.code, 'writing file');
}
};
/**
* Set the file position at which the next write will occur.
*
* @param {number} offset An absolute byte offset into the file.
*/
goog.fs.FileWriter.prototype.seek = function(offset) {
try {
this.writer_.seek(offset);
} catch (e) {
throw new goog.fs.Error(e.code, 'seeking in file');
}
};
/**
* Changes the length of the file to that specified.
*
* @param {number} size The new size of the file, in bytes.
*/
goog.fs.FileWriter.prototype.truncate = function(size) {
try {
this.writer_.truncate(size);
} catch (e) {
throw new goog.fs.Error(e.code, 'truncating file');
}
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines an Integer class for representing (potentially)
* infinite length two's-complement integer values.
*
* For the specific case of 64-bit integers, use goog.math.Long, which is more
* efficient.
*
*/
goog.provide('goog.math.Integer');
/**
* Constructs a two's-complement integer an array containing bits of the
* integer in 32-bit (signed) pieces, given in little-endian order (i.e.,
* lowest-order bits in the first piece), and the sign of -1 or 0.
*
* See the from* functions below for other convenient ways of constructing
* Integers.
*
* The internal representation of an integer is an array of 32-bit signed
* pieces, along with a sign (0 or -1) that indicates the contents of all the
* other 32-bit pieces out to infinity. We use 32-bit pieces because these are
* the size of integers on which Javascript performs bit-operations. For
* operations like addition and multiplication, we split each number into 16-bit
* pieces, which can easily be multiplied within Javascript's floating-point
* representation without overflow or change in sign.
*
* @constructor
* @param {Array.<number>} bits Array containing the bits of the number.
* @param {number} sign The sign of the number: -1 for negative and 0 positive.
*/
goog.math.Integer = function(bits, sign) {
/**
* @type {!Array.<number>}
* @private
*/
this.bits_ = [];
/**
* @type {number}
* @private
*/
this.sign_ = sign;
// Copy the 32-bit signed integer values passed in. We prune out those at the
// top that equal the sign since they are redundant.
var top = true;
for (var i = bits.length - 1; i >= 0; i--) {
var val = bits[i] | 0;
if (!top || val != sign) {
this.bits_[i] = val;
top = false;
}
}
};
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
// from* methods on which they depend.
/**
* A cache of the Integer representations of small integer values.
* @type {!Object}
* @private
*/
goog.math.Integer.IntCache_ = {};
/**
* Returns an Integer representing the given (32-bit) integer value.
* @param {number} value A 32-bit integer value.
* @return {!goog.math.Integer} The corresponding Integer value.
*/
goog.math.Integer.fromInt = function(value) {
if (-128 <= value && value < 128) {
var cachedObj = goog.math.Integer.IntCache_[value];
if (cachedObj) {
return cachedObj;
}
}
var obj = new goog.math.Integer([value | 0], value < 0 ? -1 : 0);
if (-128 <= value && value < 128) {
goog.math.Integer.IntCache_[value] = obj;
}
return obj;
};
/**
* Returns an Integer representing the given value, provided that it is a finite
* number. Otherwise, zero is returned.
* @param {number} value The value in question.
* @return {!goog.math.Integer} The corresponding Integer value.
*/
goog.math.Integer.fromNumber = function(value) {
if (isNaN(value) || !isFinite(value)) {
return goog.math.Integer.ZERO;
} else if (value < 0) {
return goog.math.Integer.fromNumber(-value).negate();
} else {
var bits = [];
var pow = 1;
for (var i = 0; value >= pow; i++) {
bits[i] = (value / pow) | 0;
pow *= goog.math.Integer.TWO_PWR_32_DBL_;
}
return new goog.math.Integer(bits, 0);
}
};
/**
* Returns a Integer representing the value that comes by concatenating the
* given entries, each is assumed to be 32 signed bits, given in little-endian
* order (lowest order bits in the lowest index), and sign-extending the highest
* order 32-bit value.
* @param {Array.<number>} bits The bits of the number, in 32-bit signed pieces,
* in little-endian order.
* @return {!goog.math.Integer} The corresponding Integer value.
*/
goog.math.Integer.fromBits = function(bits) {
var high = bits[bits.length - 1];
return new goog.math.Integer(bits, high & (1 << 31) ? -1 : 0);
};
/**
* Returns an Integer representation of the given string, written using the
* given radix.
* @param {string} str The textual representation of the Integer.
* @param {number=} opt_radix The radix in which the text is written.
* @return {!goog.math.Integer} The corresponding Integer value.
*/
goog.math.Integer.fromString = function(str, opt_radix) {
if (str.length == 0) {
throw Error('number format error: empty string');
}
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (str.charAt(0) == '-') {
return goog.math.Integer.fromString(str.substring(1), radix).negate();
} else if (str.indexOf('-') >= 0) {
throw Error('number format error: interior "-" character');
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 8));
var result = goog.math.Integer.ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i);
var value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = goog.math.Integer.fromNumber(Math.pow(radix, size));
result = result.multiply(power).add(goog.math.Integer.fromNumber(value));
} else {
result = result.multiply(radixToPower);
result = result.add(goog.math.Integer.fromNumber(value));
}
}
return result;
};
/**
* A number used repeatedly in calculations. This must appear before the first
* call to the from* functions below.
* @type {number}
* @private
*/
goog.math.Integer.TWO_PWR_32_DBL_ = (1 << 16) * (1 << 16);
/** @type {!goog.math.Integer} */
goog.math.Integer.ZERO = goog.math.Integer.fromInt(0);
/** @type {!goog.math.Integer} */
goog.math.Integer.ONE = goog.math.Integer.fromInt(1);
/**
* @type {!goog.math.Integer}
* @private
*/
goog.math.Integer.TWO_PWR_24_ = goog.math.Integer.fromInt(1 << 24);
/**
* Returns the value, assuming it is a 32-bit integer.
* @return {number} The corresponding int value.
*/
goog.math.Integer.prototype.toInt = function() {
return this.bits_.length > 0 ? this.bits_[0] : this.sign_;
};
/** @return {number} The closest floating-point representation to this value. */
goog.math.Integer.prototype.toNumber = function() {
if (this.isNegative()) {
return -this.negate().toNumber();
} else {
var val = 0;
var pow = 1;
for (var i = 0; i < this.bits_.length; i++) {
val += this.getBitsUnsigned(i) * pow;
pow *= goog.math.Integer.TWO_PWR_32_DBL_;
}
return val;
}
};
/**
* @param {number=} opt_radix The radix in which the text should be written.
* @return {string} The textual representation of this value.
* @override
*/
goog.math.Integer.prototype.toString = function(opt_radix) {
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (this.isZero()) {
return '0';
} else if (this.isNegative()) {
return '-' + this.negate().toString(radix);
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 6));
var rem = this;
var result = '';
while (true) {
var remDiv = rem.divide(radixToPower);
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
var digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) {
return digits + result;
} else {
while (digits.length < 6) {
digits = '0' + digits;
}
result = '' + digits + result;
}
}
};
/**
* Returns the index-th 32-bit (signed) piece of the Integer according to
* little-endian order (i.e., index 0 contains the smallest bits).
* @param {number} index The index in question.
* @return {number} The requested 32-bits as a signed number.
*/
goog.math.Integer.prototype.getBits = function(index) {
if (index < 0) {
return 0; // Allowing this simplifies bit shifting operations below...
} else if (index < this.bits_.length) {
return this.bits_[index];
} else {
return this.sign_;
}
};
/**
* Returns the index-th 32-bit piece as an unsigned number.
* @param {number} index The index in question.
* @return {number} The requested 32-bits as an unsigned number.
*/
goog.math.Integer.prototype.getBitsUnsigned = function(index) {
var val = this.getBits(index);
return val >= 0 ? val : goog.math.Integer.TWO_PWR_32_DBL_ + val;
};
/** @return {number} The sign bit of this number, -1 or 0. */
goog.math.Integer.prototype.getSign = function() {
return this.sign_;
};
/** @return {boolean} Whether this value is zero. */
goog.math.Integer.prototype.isZero = function() {
if (this.sign_ != 0) {
return false;
}
for (var i = 0; i < this.bits_.length; i++) {
if (this.bits_[i] != 0) {
return false;
}
}
return true;
};
/** @return {boolean} Whether this value is negative. */
goog.math.Integer.prototype.isNegative = function() {
return this.sign_ == -1;
};
/** @return {boolean} Whether this value is odd. */
goog.math.Integer.prototype.isOdd = function() {
return (this.bits_.length == 0) && (this.sign_ == -1) ||
(this.bits_.length > 0) && ((this.bits_[0] & 1) != 0);
};
/**
* @param {goog.math.Integer} other Integer to compare against.
* @return {boolean} Whether this Integer equals the other.
*/
goog.math.Integer.prototype.equals = function(other) {
if (this.sign_ != other.sign_) {
return false;
}
var len = Math.max(this.bits_.length, other.bits_.length);
for (var i = 0; i < len; i++) {
if (this.getBits(i) != other.getBits(i)) {
return false;
}
}
return true;
};
/**
* @param {goog.math.Integer} other Integer to compare against.
* @return {boolean} Whether this Integer does not equal the other.
*/
goog.math.Integer.prototype.notEquals = function(other) {
return !this.equals(other);
};
/**
* @param {goog.math.Integer} other Integer to compare against.
* @return {boolean} Whether this Integer is greater than the other.
*/
goog.math.Integer.prototype.greaterThan = function(other) {
return this.compare(other) > 0;
};
/**
* @param {goog.math.Integer} other Integer to compare against.
* @return {boolean} Whether this Integer is greater than or equal to the other.
*/
goog.math.Integer.prototype.greaterThanOrEqual = function(other) {
return this.compare(other) >= 0;
};
/**
* @param {goog.math.Integer} other Integer to compare against.
* @return {boolean} Whether this Integer is less than the other.
*/
goog.math.Integer.prototype.lessThan = function(other) {
return this.compare(other) < 0;
};
/**
* @param {goog.math.Integer} other Integer to compare against.
* @return {boolean} Whether this Integer is less than or equal to the other.
*/
goog.math.Integer.prototype.lessThanOrEqual = function(other) {
return this.compare(other) <= 0;
};
/**
* Compares this Integer with the given one.
* @param {goog.math.Integer} other Integer to compare against.
* @return {number} 0 if they are the same, 1 if the this is greater, and -1
* if the given one is greater.
*/
goog.math.Integer.prototype.compare = function(other) {
var diff = this.subtract(other);
if (diff.isNegative()) {
return -1;
} else if (diff.isZero()) {
return 0;
} else {
return +1;
}
};
/**
* Returns an integer with only the first numBits bits of this value, sign
* extended from the final bit.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Integer} The shorted integer value.
*/
goog.math.Integer.prototype.shorten = function(numBits) {
var arr_index = (numBits - 1) >> 5;
var bit_index = (numBits - 1) % 32;
var bits = [];
for (var i = 0; i < arr_index; i++) {
bits[i] = this.getBits(i);
}
var sigBits = bit_index == 31 ? 0xFFFFFFFF : (1 << (bit_index + 1)) - 1;
var val = this.getBits(arr_index) & sigBits;
if (val & (1 << bit_index)) {
val |= 0xFFFFFFFF - sigBits;
bits[arr_index] = val;
return new goog.math.Integer(bits, -1);
} else {
bits[arr_index] = val;
return new goog.math.Integer(bits, 0);
}
};
/** @return {!goog.math.Integer} The negation of this value. */
goog.math.Integer.prototype.negate = function() {
return this.not().add(goog.math.Integer.ONE);
};
/**
* Returns the sum of this and the given Integer.
* @param {goog.math.Integer} other The Integer to add to this.
* @return {!goog.math.Integer} The Integer result.
*/
goog.math.Integer.prototype.add = function(other) {
var len = Math.max(this.bits_.length, other.bits_.length);
var arr = [];
var carry = 0;
for (var i = 0; i <= len; i++) {
var a1 = this.getBits(i) >>> 16;
var a0 = this.getBits(i) & 0xFFFF;
var b1 = other.getBits(i) >>> 16;
var b0 = other.getBits(i) & 0xFFFF;
var c0 = carry + a0 + b0;
var c1 = (c0 >>> 16) + a1 + b1;
carry = c1 >>> 16;
c0 &= 0xFFFF;
c1 &= 0xFFFF;
arr[i] = (c1 << 16) | c0;
}
return goog.math.Integer.fromBits(arr);
};
/**
* Returns the difference of this and the given Integer.
* @param {goog.math.Integer} other The Integer to subtract from this.
* @return {!goog.math.Integer} The Integer result.
*/
goog.math.Integer.prototype.subtract = function(other) {
return this.add(other.negate());
};
/**
* Returns the product of this and the given Integer.
* @param {goog.math.Integer} other The Integer to multiply against this.
* @return {!goog.math.Integer} The product of this and the other.
*/
goog.math.Integer.prototype.multiply = function(other) {
if (this.isZero()) {
return goog.math.Integer.ZERO;
} else if (other.isZero()) {
return goog.math.Integer.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().multiply(other.negate());
} else {
return this.negate().multiply(other).negate();
}
} else if (other.isNegative()) {
return this.multiply(other.negate()).negate();
}
// If both numbers are small, use float multiplication
if (this.lessThan(goog.math.Integer.TWO_PWR_24_) &&
other.lessThan(goog.math.Integer.TWO_PWR_24_)) {
return goog.math.Integer.fromNumber(this.toNumber() * other.toNumber());
}
// Fill in an array of 16-bit products.
var len = this.bits_.length + other.bits_.length;
var arr = [];
for (var i = 0; i < 2 * len; i++) {
arr[i] = 0;
}
for (var i = 0; i < this.bits_.length; i++) {
for (var j = 0; j < other.bits_.length; j++) {
var a1 = this.getBits(i) >>> 16;
var a0 = this.getBits(i) & 0xFFFF;
var b1 = other.getBits(j) >>> 16;
var b0 = other.getBits(j) & 0xFFFF;
arr[2 * i + 2 * j] += a0 * b0;
goog.math.Integer.carry16_(arr, 2 * i + 2 * j);
arr[2 * i + 2 * j + 1] += a1 * b0;
goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);
arr[2 * i + 2 * j + 1] += a0 * b1;
goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);
arr[2 * i + 2 * j + 2] += a1 * b1;
goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 2);
}
}
// Combine the 16-bit values into 32-bit values.
for (var i = 0; i < len; i++) {
arr[i] = (arr[2 * i + 1] << 16) | arr[2 * i];
}
for (var i = len; i < 2 * len; i++) {
arr[i] = 0;
}
return new goog.math.Integer(arr, 0);
};
/**
* Carries any overflow from the given index into later entries.
* @param {Array.<number>} bits Array of 16-bit values in little-endian order.
* @param {number} index The index in question.
* @private
*/
goog.math.Integer.carry16_ = function(bits, index) {
while ((bits[index] & 0xFFFF) != bits[index]) {
bits[index + 1] += bits[index] >>> 16;
bits[index] &= 0xFFFF;
}
};
/**
* Returns this Integer divided by the given one.
* @param {goog.math.Integer} other Th Integer to divide this by.
* @return {!goog.math.Integer} This value divided by the given one.
*/
goog.math.Integer.prototype.divide = function(other) {
if (other.isZero()) {
throw Error('division by zero');
} else if (this.isZero()) {
return goog.math.Integer.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().divide(other.negate());
} else {
return this.negate().divide(other).negate();
}
} else if (other.isNegative()) {
return this.divide(other.negate()).negate();
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
var res = goog.math.Integer.ZERO;
var rem = this;
while (rem.greaterThanOrEqual(other)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
var approxRes = goog.math.Integer.fromNumber(approx);
var approxRem = approxRes.multiply(other);
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
approx -= delta;
approxRes = goog.math.Integer.fromNumber(approx);
approxRem = approxRes.multiply(other);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero()) {
approxRes = goog.math.Integer.ONE;
}
res = res.add(approxRes);
rem = rem.subtract(approxRem);
}
return res;
};
/**
* Returns this Integer modulo the given one.
* @param {goog.math.Integer} other The Integer by which to mod.
* @return {!goog.math.Integer} This value modulo the given one.
*/
goog.math.Integer.prototype.modulo = function(other) {
return this.subtract(this.divide(other).multiply(other));
};
/** @return {!goog.math.Integer} The bitwise-NOT of this value. */
goog.math.Integer.prototype.not = function() {
var len = this.bits_.length;
var arr = [];
for (var i = 0; i < len; i++) {
arr[i] = ~this.bits_[i];
}
return new goog.math.Integer(arr, ~this.sign_);
};
/**
* Returns the bitwise-AND of this Integer and the given one.
* @param {goog.math.Integer} other The Integer to AND with this.
* @return {!goog.math.Integer} The bitwise-AND of this and the other.
*/
goog.math.Integer.prototype.and = function(other) {
var len = Math.max(this.bits_.length, other.bits_.length);
var arr = [];
for (var i = 0; i < len; i++) {
arr[i] = this.getBits(i) & other.getBits(i);
}
return new goog.math.Integer(arr, this.sign_ & other.sign_);
};
/**
* Returns the bitwise-OR of this Integer and the given one.
* @param {goog.math.Integer} other The Integer to OR with this.
* @return {!goog.math.Integer} The bitwise-OR of this and the other.
*/
goog.math.Integer.prototype.or = function(other) {
var len = Math.max(this.bits_.length, other.bits_.length);
var arr = [];
for (var i = 0; i < len; i++) {
arr[i] = this.getBits(i) | other.getBits(i);
}
return new goog.math.Integer(arr, this.sign_ | other.sign_);
};
/**
* Returns the bitwise-XOR of this Integer and the given one.
* @param {goog.math.Integer} other The Integer to XOR with this.
* @return {!goog.math.Integer} The bitwise-XOR of this and the other.
*/
goog.math.Integer.prototype.xor = function(other) {
var len = Math.max(this.bits_.length, other.bits_.length);
var arr = [];
for (var i = 0; i < len; i++) {
arr[i] = this.getBits(i) ^ other.getBits(i);
}
return new goog.math.Integer(arr, this.sign_ ^ other.sign_);
};
/**
* Returns this value with bits shifted to the left by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Integer} This shifted to the left by the given amount.
*/
goog.math.Integer.prototype.shiftLeft = function(numBits) {
var arr_delta = numBits >> 5;
var bit_delta = numBits % 32;
var len = this.bits_.length + arr_delta + (bit_delta > 0 ? 1 : 0);
var arr = [];
for (var i = 0; i < len; i++) {
if (bit_delta > 0) {
arr[i] = (this.getBits(i - arr_delta) << bit_delta) |
(this.getBits(i - arr_delta - 1) >>> (32 - bit_delta));
} else {
arr[i] = this.getBits(i - arr_delta);
}
}
return new goog.math.Integer(arr, this.sign_);
};
/**
* Returns this value with bits shifted to the right by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Integer} This shifted to the right by the given amount.
*/
goog.math.Integer.prototype.shiftRight = function(numBits) {
var arr_delta = numBits >> 5;
var bit_delta = numBits % 32;
var len = this.bits_.length - arr_delta;
var arr = [];
for (var i = 0; i < len; i++) {
if (bit_delta > 0) {
arr[i] = (this.getBits(i + arr_delta) >>> bit_delta) |
(this.getBits(i + arr_delta + 1) << (32 - bit_delta));
} else {
arr[i] = this.getBits(i + arr_delta);
}
}
return new goog.math.Integer(arr, this.sign_);
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A utility class for representing rectangles.
*/
goog.provide('goog.math.Rect');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
/**
* Class for representing rectangular regions.
* @param {number} x Left.
* @param {number} y Top.
* @param {number} w Width.
* @param {number} h Height.
* @constructor
*/
goog.math.Rect = function(x, y, w, h) {
/** @type {number} */
this.left = x;
/** @type {number} */
this.top = y;
/** @type {number} */
this.width = w;
/** @type {number} */
this.height = h;
};
/**
* @return {!goog.math.Rect} A new copy of this Rectangle.
*/
goog.math.Rect.prototype.clone = function() {
return new goog.math.Rect(this.left, this.top, this.width, this.height);
};
/**
* Returns a new Box object with the same position and dimensions as this
* rectangle.
* @return {!goog.math.Box} A new Box representation of this Rectangle.
*/
goog.math.Rect.prototype.toBox = function() {
var right = this.left + this.width;
var bottom = this.top + this.height;
return new goog.math.Box(this.top,
right,
bottom,
this.left);
};
/**
* Creates a new Rect object with the same position and dimensions as a given
* Box. Note that this is only the inverse of toBox if left/top are defined.
* @param {goog.math.Box} box A box.
* @return {!goog.math.Rect} A new Rect initialized with the box's position
* and size.
*/
goog.math.Rect.createFromBox = function(box) {
return new goog.math.Rect(box.left, box.top,
box.right - box.left, box.bottom - box.top);
};
if (goog.DEBUG) {
/**
* Returns a nice string representing size and dimensions of rectangle.
* @return {string} In the form (50, 73 - 75w x 25h).
* @override
*/
goog.math.Rect.prototype.toString = function() {
return '(' + this.left + ', ' + this.top + ' - ' + this.width + 'w x ' +
this.height + 'h)';
};
}
/**
* Compares rectangles for equality.
* @param {goog.math.Rect} a A Rectangle.
* @param {goog.math.Rect} b A Rectangle.
* @return {boolean} True iff the rectangles have the same left, top, width,
* and height, or if both are null.
*/
goog.math.Rect.equals = function(a, b) {
if (a == b) {
return true;
}
if (!a || !b) {
return false;
}
return a.left == b.left && a.width == b.width &&
a.top == b.top && a.height == b.height;
};
/**
* Computes the intersection of this rectangle and the rectangle parameter. If
* there is no intersection, returns false and leaves this rectangle as is.
* @param {goog.math.Rect} rect A Rectangle.
* @return {boolean} True iff this rectangle intersects with the parameter.
*/
goog.math.Rect.prototype.intersection = function(rect) {
var x0 = Math.max(this.left, rect.left);
var x1 = Math.min(this.left + this.width, rect.left + rect.width);
if (x0 <= x1) {
var y0 = Math.max(this.top, rect.top);
var y1 = Math.min(this.top + this.height, rect.top + rect.height);
if (y0 <= y1) {
this.left = x0;
this.top = y0;
this.width = x1 - x0;
this.height = y1 - y0;
return true;
}
}
return false;
};
/**
* Returns the intersection of two rectangles. Two rectangles intersect if they
* touch at all, for example, two zero width and height rectangles would
* intersect if they had the same top and left.
* @param {goog.math.Rect} a A Rectangle.
* @param {goog.math.Rect} b A Rectangle.
* @return {goog.math.Rect} A new intersection rect (even if width and height
* are 0), or null if there is no intersection.
*/
goog.math.Rect.intersection = function(a, b) {
// There is no nice way to do intersection via a clone, because any such
// clone might be unnecessary if this function returns null. So, we duplicate
// code from above.
var x0 = Math.max(a.left, b.left);
var x1 = Math.min(a.left + a.width, b.left + b.width);
if (x0 <= x1) {
var y0 = Math.max(a.top, b.top);
var y1 = Math.min(a.top + a.height, b.top + b.height);
if (y0 <= y1) {
return new goog.math.Rect(x0, y0, x1 - x0, y1 - y0);
}
}
return null;
};
/**
* Returns whether two rectangles intersect. Two rectangles intersect if they
* touch at all, for example, two zero width and height rectangles would
* intersect if they had the same top and left.
* @param {goog.math.Rect} a A Rectangle.
* @param {goog.math.Rect} b A Rectangle.
* @return {boolean} Whether a and b intersect.
*/
goog.math.Rect.intersects = function(a, b) {
return (a.left <= b.left + b.width && b.left <= a.left + a.width &&
a.top <= b.top + b.height && b.top <= a.top + a.height);
};
/**
* Returns whether a rectangle intersects this rectangle.
* @param {goog.math.Rect} rect A rectangle.
* @return {boolean} Whether rect intersects this rectangle.
*/
goog.math.Rect.prototype.intersects = function(rect) {
return goog.math.Rect.intersects(this, rect);
};
/**
* Computes the difference regions between two rectangles. The return value is
* an array of 0 to 4 rectangles defining the remaining regions of the first
* rectangle after the second has been subtracted.
* @param {goog.math.Rect} a A Rectangle.
* @param {goog.math.Rect} b A Rectangle.
* @return {!Array.<!goog.math.Rect>} An array with 0 to 4 rectangles which
* together define the difference area of rectangle a minus rectangle b.
*/
goog.math.Rect.difference = function(a, b) {
var intersection = goog.math.Rect.intersection(a, b);
if (!intersection || !intersection.height || !intersection.width) {
return [a.clone()];
}
var result = [];
var top = a.top;
var height = a.height;
var ar = a.left + a.width;
var ab = a.top + a.height;
var br = b.left + b.width;
var bb = b.top + b.height;
// Subtract off any area on top where A extends past B
if (b.top > a.top) {
result.push(new goog.math.Rect(a.left, a.top, a.width, b.top - a.top));
top = b.top;
// If we're moving the top down, we also need to subtract the height diff.
height -= b.top - a.top;
}
// Subtract off any area on bottom where A extends past B
if (bb < ab) {
result.push(new goog.math.Rect(a.left, bb, a.width, ab - bb));
height = bb - top;
}
// Subtract any area on left where A extends past B
if (b.left > a.left) {
result.push(new goog.math.Rect(a.left, top, b.left - a.left, height));
}
// Subtract any area on right where A extends past B
if (br < ar) {
result.push(new goog.math.Rect(br, top, ar - br, height));
}
return result;
};
/**
* Computes the difference regions between this rectangle and {@code rect}. The
* return value is an array of 0 to 4 rectangles defining the remaining regions
* of this rectangle after the other has been subtracted.
* @param {goog.math.Rect} rect A Rectangle.
* @return {!Array.<!goog.math.Rect>} An array with 0 to 4 rectangles which
* together define the difference area of rectangle a minus rectangle b.
*/
goog.math.Rect.prototype.difference = function(rect) {
return goog.math.Rect.difference(this, rect);
};
/**
* Expand this rectangle to also include the area of the given rectangle.
* @param {goog.math.Rect} rect The other rectangle.
*/
goog.math.Rect.prototype.boundingRect = function(rect) {
// We compute right and bottom before we change left and top below.
var right = Math.max(this.left + this.width, rect.left + rect.width);
var bottom = Math.max(this.top + this.height, rect.top + rect.height);
this.left = Math.min(this.left, rect.left);
this.top = Math.min(this.top, rect.top);
this.width = right - this.left;
this.height = bottom - this.top;
};
/**
* Returns a new rectangle which completely contains both input rectangles.
* @param {goog.math.Rect} a A rectangle.
* @param {goog.math.Rect} b A rectangle.
* @return {goog.math.Rect} A new bounding rect, or null if either rect is
* null.
*/
goog.math.Rect.boundingRect = function(a, b) {
if (!a || !b) {
return null;
}
var clone = a.clone();
clone.boundingRect(b);
return clone;
};
/**
* Tests whether this rectangle entirely contains another rectangle or
* coordinate.
*
* @param {goog.math.Rect|goog.math.Coordinate} another The rectangle or
* coordinate to test for containment.
* @return {boolean} Whether this rectangle contains given rectangle or
* coordinate.
*/
goog.math.Rect.prototype.contains = function(another) {
if (another instanceof goog.math.Rect) {
return this.left <= another.left &&
this.left + this.width >= another.left + another.width &&
this.top <= another.top &&
this.top + this.height >= another.top + another.height;
} else { // (another instanceof goog.math.Coordinate)
return another.x >= this.left &&
another.x <= this.left + this.width &&
another.y >= this.top &&
another.y <= this.top + this.height;
}
};
/**
* @param {!goog.math.Coordinate} point A coordinate.
* @return {number} The squared distance between the point and the closest
* point inside the rectangle. Returns 0 if the point is inside the
* rectangle.
*/
goog.math.Rect.prototype.squaredDistance = function(point) {
var dx = point.x < this.left ?
this.left - point.x : Math.max(point.x - (this.left + this.width), 0);
var dy = point.y < this.top ?
this.top - point.y : Math.max(point.y - (this.top + this.height), 0);
return dx * dx + dy * dy;
};
/**
* @param {!goog.math.Coordinate} point A coordinate.
* @return {number} The distance between the point and the closest point
* inside the rectangle. Returns 0 if the point is inside the rectangle.
*/
goog.math.Rect.prototype.distance = function(point) {
return Math.sqrt(this.squaredDistance(point));
};
/**
* @return {!goog.math.Size} The size of this rectangle.
*/
goog.math.Rect.prototype.getSize = function() {
return new goog.math.Size(this.width, this.height);
};
/**
* @return {!goog.math.Coordinate} A new coordinate for the top-left corner of
* the rectangle.
*/
goog.math.Rect.prototype.getTopLeft = function() {
return new goog.math.Coordinate(this.left, this.top);
};
/**
* @return {!goog.math.Coordinate} A new coordinate for the center of the
* rectangle.
*/
goog.math.Rect.prototype.getCenter = function() {
return new goog.math.Coordinate(
this.left + this.width / 2, this.top + this.height / 2);
};
/**
* @return {!goog.math.Coordinate} A new coordinate for the bottom-right corner
* of the rectangle.
*/
goog.math.Rect.prototype.getBottomRight = function() {
return new goog.math.Coordinate(
this.left + this.width, this.top + this.height);
};
/**
* Rounds the fields to the next larger integer values.
* @return {!goog.math.Rect} This rectangle with ceil'd fields.
*/
goog.math.Rect.prototype.ceil = function() {
this.left = Math.ceil(this.left);
this.top = Math.ceil(this.top);
this.width = Math.ceil(this.width);
this.height = Math.ceil(this.height);
return this;
};
/**
* Rounds the fields to the next smaller integer values.
* @return {!goog.math.Rect} This rectangle with floored fields.
*/
goog.math.Rect.prototype.floor = function() {
this.left = Math.floor(this.left);
this.top = Math.floor(this.top);
this.width = Math.floor(this.width);
this.height = Math.floor(this.height);
return this;
};
/**
* Rounds the fields to nearest integer values.
* @return {!goog.math.Rect} This rectangle with rounded fields.
*/
goog.math.Rect.prototype.round = function() {
this.left = Math.round(this.left);
this.top = Math.round(this.top);
this.width = Math.round(this.width);
this.height = Math.round(this.height);
return this;
};
/**
* Translates this rectangle by the given offsets. If a
* {@code goog.math.Coordinate} is given, then the left and top values are
* translated by the coordinate's x and y values. Otherwise, top and left are
* translated by {@code tx} and {@code opt_ty} respectively.
* @param {number|goog.math.Coordinate} tx The value to translate left by or the
* the coordinate to translate this rect by.
* @param {number=} opt_ty The value to translate top by.
* @return {!goog.math.Rect} This rectangle after translating.
*/
goog.math.Rect.prototype.translate = function(tx, opt_ty) {
if (tx instanceof goog.math.Coordinate) {
this.left += tx.x;
this.top += tx.y;
} else {
this.left += tx;
if (goog.isNumber(opt_ty)) {
this.top += opt_ty;
}
}
return this;
};
/**
* Scales this rectangle by the given scale factors. The left and width values
* are scaled by {@code sx} and the top and height values are scaled by
* {@code opt_sy}. If {@code opt_sy} is not given, then all fields are scaled
* by {@code sx}.
* @param {number} sx The scale factor to use for the x dimension.
* @param {number=} opt_sy The scale factor to use for the y dimension.
* @return {!goog.math.Rect} This rectangle after scaling.
*/
goog.math.Rect.prototype.scale = function(sx, opt_sy) {
var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
this.left *= sx;
this.width *= sx;
this.top *= sy;
this.height *= sy;
return this;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A utility class for representing two-dimensional sizes.
*/
goog.provide('goog.math.Size');
/**
* Class for representing sizes consisting of a width and height. Undefined
* width and height support is deprecated and results in compiler warning.
* @param {number} width Width.
* @param {number} height Height.
* @constructor
*/
goog.math.Size = function(width, height) {
/**
* Width
* @type {number}
*/
this.width = width;
/**
* Height
* @type {number}
*/
this.height = height;
};
/**
* Compares sizes for equality.
* @param {goog.math.Size} a A Size.
* @param {goog.math.Size} b A Size.
* @return {boolean} True iff the sizes have equal widths and equal
* heights, or if both are null.
*/
goog.math.Size.equals = function(a, b) {
if (a == b) {
return true;
}
if (!a || !b) {
return false;
}
return a.width == b.width && a.height == b.height;
};
/**
* @return {!goog.math.Size} A new copy of the Size.
*/
goog.math.Size.prototype.clone = function() {
return new goog.math.Size(this.width, this.height);
};
if (goog.DEBUG) {
/**
* Returns a nice string representing size.
* @return {string} In the form (50 x 73).
* @override
*/
goog.math.Size.prototype.toString = function() {
return '(' + this.width + ' x ' + this.height + ')';
};
}
/**
* @return {number} The longer of the two dimensions in the size.
*/
goog.math.Size.prototype.getLongest = function() {
return Math.max(this.width, this.height);
};
/**
* @return {number} The shorter of the two dimensions in the size.
*/
goog.math.Size.prototype.getShortest = function() {
return Math.min(this.width, this.height);
};
/**
* @return {number} The area of the size (width * height).
*/
goog.math.Size.prototype.area = function() {
return this.width * this.height;
};
/**
* @return {number} The perimeter of the size (width + height) * 2.
*/
goog.math.Size.prototype.perimeter = function() {
return (this.width + this.height) * 2;
};
/**
* @return {number} The ratio of the size's width to its height.
*/
goog.math.Size.prototype.aspectRatio = function() {
return this.width / this.height;
};
/**
* @return {boolean} True if the size has zero area, false if both dimensions
* are non-zero numbers.
*/
goog.math.Size.prototype.isEmpty = function() {
return !this.area();
};
/**
* Clamps the width and height parameters upward to integer values.
* @return {!goog.math.Size} This size with ceil'd components.
*/
goog.math.Size.prototype.ceil = function() {
this.width = Math.ceil(this.width);
this.height = Math.ceil(this.height);
return this;
};
/**
* @param {!goog.math.Size} target The target size.
* @return {boolean} True if this Size is the same size or smaller than the
* target size in both dimensions.
*/
goog.math.Size.prototype.fitsInside = function(target) {
return this.width <= target.width && this.height <= target.height;
};
/**
* Clamps the width and height parameters downward to integer values.
* @return {!goog.math.Size} This size with floored components.
*/
goog.math.Size.prototype.floor = function() {
this.width = Math.floor(this.width);
this.height = Math.floor(this.height);
return this;
};
/**
* Rounds the width and height parameters to integer values.
* @return {!goog.math.Size} This size with rounded components.
*/
goog.math.Size.prototype.round = function() {
this.width = Math.round(this.width);
this.height = Math.round(this.height);
return this;
};
/**
* Scales this size by the given scale factors. The width and height are scaled
* by {@code sx} and {@code opt_sy} respectively. If {@code opt_sy} is not
* given, then {@code sx} is used for both the width and height.
* @param {number} sx The scale factor to use for the width.
* @param {number=} opt_sy The scale factor to use for the height.
* @return {!goog.math.Size} This Size object after scaling.
*/
goog.math.Size.prototype.scale = function(sx, opt_sy) {
var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
this.width *= sx;
this.height *= sy;
return this;
};
/**
* Uniformly scales the size to fit inside the dimensions of a given size. The
* original aspect ratio will be preserved.
*
* This function assumes that both Sizes contain strictly positive dimensions.
* @param {!goog.math.Size} target The target size.
* @return {!goog.math.Size} This Size object, after optional scaling.
*/
goog.math.Size.prototype.scaleToFit = function(target) {
var s = this.aspectRatio() > target.aspectRatio() ?
target.width / this.width :
target.height / this.height;
return this.scale(s);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines a 3-element vector class that can be used for
* coordinate math, useful for animation systems and point manipulation.
*
* Based heavily on code originally by:
*/
goog.provide('goog.math.Vec3');
goog.require('goog.math');
goog.require('goog.math.Coordinate3');
/**
* Class for a three-dimensional vector object and assorted functions useful for
* manipulation.
*
* Inherits from goog.math.Coordinate3 so that a Vec3 may be passed in to any
* function that requires a Coordinate.
*
* @param {number} x The x value for the vector.
* @param {number} y The y value for the vector.
* @param {number} z The z value for the vector.
* @constructor
* @extends {goog.math.Coordinate3}
*/
goog.math.Vec3 = function(x, y, z) {
/**
* X-value
* @type {number}
*/
this.x = x;
/**
* Y-value
* @type {number}
*/
this.y = y;
/**
* Z-value
* @type {number}
*/
this.z = z;
};
goog.inherits(goog.math.Vec3, goog.math.Coordinate3);
/**
* Generates a random unit vector.
*
* http://mathworld.wolfram.com/SpherePointPicking.html
* Using (6), (7), and (8) to generate coordinates.
* @return {!goog.math.Vec3} A random unit-length vector.
*/
goog.math.Vec3.randomUnit = function() {
var theta = Math.random() * Math.PI * 2;
var phi = Math.random() * Math.PI * 2;
var z = Math.cos(phi);
var x = Math.sqrt(1 - z * z) * Math.cos(theta);
var y = Math.sqrt(1 - z * z) * Math.sin(theta);
return new goog.math.Vec3(x, y, z);
};
/**
* Generates a random vector inside the unit sphere.
*
* @return {!goog.math.Vec3} A random vector.
*/
goog.math.Vec3.random = function() {
return goog.math.Vec3.randomUnit().scale(Math.random());
};
/**
* Returns a new Vec3 object from a given coordinate.
*
* @param {goog.math.Coordinate3} a The coordinate.
* @return {!goog.math.Vec3} A new vector object.
*/
goog.math.Vec3.fromCoordinate3 = function(a) {
return new goog.math.Vec3(a.x, a.y, a.z);
};
/**
* Creates a new copy of this Vec3.
*
* @return {!goog.math.Vec3} A new vector with the same coordinates as this one.
* @override
*/
goog.math.Vec3.prototype.clone = function() {
return new goog.math.Vec3(this.x, this.y, this.z);
};
/**
* Returns the magnitude of the vector measured from the origin.
*
* @return {number} The length of the vector.
*/
goog.math.Vec3.prototype.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
/**
* Returns the squared magnitude of the vector measured from the origin.
* NOTE(brenneman): Leaving out the square root is not a significant
* optimization in JavaScript.
*
* @return {number} The length of the vector, squared.
*/
goog.math.Vec3.prototype.squaredMagnitude = function() {
return this.x * this.x + this.y * this.y + this.z * this.z;
};
/**
* Scales the current vector by a constant.
*
* @param {number} s The scale factor.
* @return {!goog.math.Vec3} This vector, scaled.
*/
goog.math.Vec3.prototype.scale = function(s) {
this.x *= s;
this.y *= s;
this.z *= s;
return this;
};
/**
* Reverses the sign of the vector. Equivalent to scaling the vector by -1.
*
* @return {!goog.math.Vec3} This vector, inverted.
*/
goog.math.Vec3.prototype.invert = function() {
this.x = -this.x;
this.y = -this.y;
this.z = -this.z;
return this;
};
/**
* Normalizes the current vector to have a magnitude of 1.
*
* @return {!goog.math.Vec3} This vector, normalized.
*/
goog.math.Vec3.prototype.normalize = function() {
return this.scale(1 / this.magnitude());
};
/**
* Adds another vector to this vector in-place.
*
* @param {goog.math.Vec3} b The vector to add.
* @return {!goog.math.Vec3} This vector with {@code b} added.
*/
goog.math.Vec3.prototype.add = function(b) {
this.x += b.x;
this.y += b.y;
this.z += b.z;
return this;
};
/**
* Subtracts another vector from this vector in-place.
*
* @param {goog.math.Vec3} b The vector to subtract.
* @return {!goog.math.Vec3} This vector with {@code b} subtracted.
*/
goog.math.Vec3.prototype.subtract = function(b) {
this.x -= b.x;
this.y -= b.y;
this.z -= b.z;
return this;
};
/**
* Compares this vector with another for equality.
*
* @param {goog.math.Vec3} b The other vector.
* @return {boolean} True if this vector's x, y and z equal the given vector's
* x, y, and z, respectively.
*/
goog.math.Vec3.prototype.equals = function(b) {
return this == b || !!b && this.x == b.x && this.y == b.y && this.z == b.z;
};
/**
* Returns the distance between two vectors.
*
* @param {goog.math.Vec3} a The first vector.
* @param {goog.math.Vec3} b The second vector.
* @return {number} The distance.
*/
goog.math.Vec3.distance = goog.math.Coordinate3.distance;
/**
* Returns the squared distance between two vectors.
*
* @param {goog.math.Vec3} a The first vector.
* @param {goog.math.Vec3} b The second vector.
* @return {number} The squared distance.
*/
goog.math.Vec3.squaredDistance = goog.math.Coordinate3.squaredDistance;
/**
* Compares vectors for equality.
*
* @param {goog.math.Vec3} a The first vector.
* @param {goog.math.Vec3} b The second vector.
* @return {boolean} True if the vectors have equal x, y, and z coordinates.
*/
goog.math.Vec3.equals = goog.math.Coordinate3.equals;
/**
* Returns the sum of two vectors as a new Vec3.
*
* @param {goog.math.Vec3} a The first vector.
* @param {goog.math.Vec3} b The second vector.
* @return {!goog.math.Vec3} The sum vector.
*/
goog.math.Vec3.sum = function(a, b) {
return new goog.math.Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
};
/**
* Returns the difference of two vectors as a new Vec3.
*
* @param {goog.math.Vec3} a The first vector.
* @param {goog.math.Vec3} b The second vector.
* @return {!goog.math.Vec3} The difference vector.
*/
goog.math.Vec3.difference = function(a, b) {
return new goog.math.Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
};
/**
* Returns the dot-product of two vectors.
*
* @param {goog.math.Vec3} a The first vector.
* @param {goog.math.Vec3} b The second vector.
* @return {number} The dot-product of the two vectors.
*/
goog.math.Vec3.dot = function(a, b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
};
/**
* Returns the cross-product of two vectors.
*
* @param {goog.math.Vec3} a The first vector.
* @param {goog.math.Vec3} b The second vector.
* @return {!goog.math.Vec3} The cross-product of the two vectors.
*/
goog.math.Vec3.cross = function(a, b) {
return new goog.math.Vec3(a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x);
};
/**
* Returns a new Vec3 that is the linear interpolant between vectors a and b at
* scale-value x.
*
* @param {goog.math.Vec3} a Vector a.
* @param {goog.math.Vec3} b Vector b.
* @param {number} x The proportion between a and b.
* @return {!goog.math.Vec3} The interpolated vector.
*/
goog.math.Vec3.lerp = function(a, b, x) {
return new goog.math.Vec3(goog.math.lerp(a.x, b.x, x),
goog.math.lerp(a.y, b.y, x),
goog.math.lerp(a.z, b.z, x));
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A utility class for representing a numeric box.
*/
goog.provide('goog.math.Box');
goog.require('goog.math.Coordinate');
/**
* Class for representing a box. A box is specified as a top, right, bottom,
* and left. A box is useful for representing margins and padding.
*
* @param {number} top Top.
* @param {number} right Right.
* @param {number} bottom Bottom.
* @param {number} left Left.
* @constructor
*/
goog.math.Box = function(top, right, bottom, left) {
/**
* Top
* @type {number}
*/
this.top = top;
/**
* Right
* @type {number}
*/
this.right = right;
/**
* Bottom
* @type {number}
*/
this.bottom = bottom;
/**
* Left
* @type {number}
*/
this.left = left;
};
/**
* Creates a Box by bounding a collection of goog.math.Coordinate objects
* @param {...goog.math.Coordinate} var_args Coordinates to be included inside
* the box.
* @return {!goog.math.Box} A Box containing all the specified Coordinates.
*/
goog.math.Box.boundingBox = function(var_args) {
var box = new goog.math.Box(arguments[0].y, arguments[0].x,
arguments[0].y, arguments[0].x);
for (var i = 1; i < arguments.length; i++) {
var coord = arguments[i];
box.top = Math.min(box.top, coord.y);
box.right = Math.max(box.right, coord.x);
box.bottom = Math.max(box.bottom, coord.y);
box.left = Math.min(box.left, coord.x);
}
return box;
};
/**
* Creates a copy of the box with the same dimensions.
* @return {!goog.math.Box} A clone of this Box.
*/
goog.math.Box.prototype.clone = function() {
return new goog.math.Box(this.top, this.right, this.bottom, this.left);
};
if (goog.DEBUG) {
/**
* Returns a nice string representing the box.
* @return {string} In the form (50t, 73r, 24b, 13l).
* @override
*/
goog.math.Box.prototype.toString = function() {
return '(' + this.top + 't, ' + this.right + 'r, ' + this.bottom + 'b, ' +
this.left + 'l)';
};
}
/**
* Returns whether the box contains a coordinate or another box.
*
* @param {goog.math.Coordinate|goog.math.Box} other A Coordinate or a Box.
* @return {boolean} Whether the box contains the coordinate or other box.
*/
goog.math.Box.prototype.contains = function(other) {
return goog.math.Box.contains(this, other);
};
/**
* Expands box with the given margins.
*
* @param {number|goog.math.Box} top Top margin or box with all margins.
* @param {number=} opt_right Right margin.
* @param {number=} opt_bottom Bottom margin.
* @param {number=} opt_left Left margin.
* @return {!goog.math.Box} A reference to this Box.
*/
goog.math.Box.prototype.expand = function(top, opt_right, opt_bottom,
opt_left) {
if (goog.isObject(top)) {
this.top -= top.top;
this.right += top.right;
this.bottom += top.bottom;
this.left -= top.left;
} else {
this.top -= top;
this.right += opt_right;
this.bottom += opt_bottom;
this.left -= opt_left;
}
return this;
};
/**
* Expand this box to include another box.
* NOTE(user): This is used in code that needs to be very fast, please don't
* add functionality to this function at the expense of speed (variable
* arguments, accepting multiple argument types, etc).
* @param {goog.math.Box} box The box to include in this one.
*/
goog.math.Box.prototype.expandToInclude = function(box) {
this.left = Math.min(this.left, box.left);
this.top = Math.min(this.top, box.top);
this.right = Math.max(this.right, box.right);
this.bottom = Math.max(this.bottom, box.bottom);
};
/**
* Compares boxes for equality.
* @param {goog.math.Box} a A Box.
* @param {goog.math.Box} b A Box.
* @return {boolean} True iff the boxes are equal, or if both are null.
*/
goog.math.Box.equals = function(a, b) {
if (a == b) {
return true;
}
if (!a || !b) {
return false;
}
return a.top == b.top && a.right == b.right &&
a.bottom == b.bottom && a.left == b.left;
};
/**
* Returns whether a box contains a coordinate or another box.
*
* @param {goog.math.Box} box A Box.
* @param {goog.math.Coordinate|goog.math.Box} other A Coordinate or a Box.
* @return {boolean} Whether the box contains the coordinate or other box.
*/
goog.math.Box.contains = function(box, other) {
if (!box || !other) {
return false;
}
if (other instanceof goog.math.Box) {
return other.left >= box.left && other.right <= box.right &&
other.top >= box.top && other.bottom <= box.bottom;
}
// other is a Coordinate.
return other.x >= box.left && other.x <= box.right &&
other.y >= box.top && other.y <= box.bottom;
};
/**
* Returns the relative x position of a coordinate compared to a box. Returns
* zero if the coordinate is inside the box.
*
* @param {goog.math.Box} box A Box.
* @param {goog.math.Coordinate} coord A Coordinate.
* @return {number} The x position of {@code coord} relative to the nearest
* side of {@code box}, or zero if {@code coord} is inside {@code box}.
*/
goog.math.Box.relativePositionX = function(box, coord) {
if (coord.x < box.left) {
return coord.x - box.left;
} else if (coord.x > box.right) {
return coord.x - box.right;
}
return 0;
};
/**
* Returns the relative y position of a coordinate compared to a box. Returns
* zero if the coordinate is inside the box.
*
* @param {goog.math.Box} box A Box.
* @param {goog.math.Coordinate} coord A Coordinate.
* @return {number} The y position of {@code coord} relative to the nearest
* side of {@code box}, or zero if {@code coord} is inside {@code box}.
*/
goog.math.Box.relativePositionY = function(box, coord) {
if (coord.y < box.top) {
return coord.y - box.top;
} else if (coord.y > box.bottom) {
return coord.y - box.bottom;
}
return 0;
};
/**
* Returns the distance between a coordinate and the nearest corner/side of a
* box. Returns zero if the coordinate is inside the box.
*
* @param {goog.math.Box} box A Box.
* @param {goog.math.Coordinate} coord A Coordinate.
* @return {number} The distance between {@code coord} and the nearest
* corner/side of {@code box}, or zero if {@code coord} is inside
* {@code box}.
*/
goog.math.Box.distance = function(box, coord) {
var x = goog.math.Box.relativePositionX(box, coord);
var y = goog.math.Box.relativePositionY(box, coord);
return Math.sqrt(x * x + y * y);
};
/**
* Returns whether two boxes intersect.
*
* @param {goog.math.Box} a A Box.
* @param {goog.math.Box} b A second Box.
* @return {boolean} Whether the boxes intersect.
*/
goog.math.Box.intersects = function(a, b) {
return (a.left <= b.right && b.left <= a.right &&
a.top <= b.bottom && b.top <= a.bottom);
};
/**
* Returns whether two boxes would intersect with additional padding.
*
* @param {goog.math.Box} a A Box.
* @param {goog.math.Box} b A second Box.
* @param {number} padding The additional padding.
* @return {boolean} Whether the boxes intersect.
*/
goog.math.Box.intersectsWithPadding = function(a, b, padding) {
return (a.left <= b.right + padding && b.left <= a.right + padding &&
a.top <= b.bottom + padding && b.top <= a.bottom + padding);
};
/**
* Rounds the fields to the next larger integer values.
*
* @return {!goog.math.Box} This box with ceil'd fields.
*/
goog.math.Box.prototype.ceil = function() {
this.top = Math.ceil(this.top);
this.right = Math.ceil(this.right);
this.bottom = Math.ceil(this.bottom);
this.left = Math.ceil(this.left);
return this;
};
/**
* Rounds the fields to the next smaller integer values.
*
* @return {!goog.math.Box} This box with floored fields.
*/
goog.math.Box.prototype.floor = function() {
this.top = Math.floor(this.top);
this.right = Math.floor(this.right);
this.bottom = Math.floor(this.bottom);
this.left = Math.floor(this.left);
return this;
};
/**
* Rounds the fields to nearest integer values.
*
* @return {!goog.math.Box} This box with rounded fields.
*/
goog.math.Box.prototype.round = function() {
this.top = Math.round(this.top);
this.right = Math.round(this.right);
this.bottom = Math.round(this.bottom);
this.left = Math.round(this.left);
return this;
};
/**
* Translates this box by the given offsets. If a {@code goog.math.Coordinate}
* is given, then the left and right values are translated by the coordinate's
* x value and the top and bottom values are translated by the coordinate's y
* value. Otherwise, {@code tx} and {@code opt_ty} are used to translate the x
* and y dimension values.
*
* @param {number|goog.math.Coordinate} tx The value to translate the x
* dimension values by or the the coordinate to translate this box by.
* @param {number=} opt_ty The value to translate y dimension values by.
* @return {!goog.math.Box} This box after translating.
*/
goog.math.Box.prototype.translate = function(tx, opt_ty) {
if (tx instanceof goog.math.Coordinate) {
this.left += tx.x;
this.right += tx.x;
this.top += tx.y;
this.bottom += tx.y;
} else {
this.left += tx;
this.right += tx;
if (goog.isNumber(opt_ty)) {
this.top += opt_ty;
this.bottom += opt_ty;
}
}
return this;
};
/**
* Scales this coordinate by the given scale factors. The x and y dimension
* values are scaled by {@code sx} and {@code opt_sy} respectively.
* If {@code opt_sy} is not given, then {@code sx} is used for both x and y.
*
* @param {number} sx The scale factor to use for the x dimension.
* @param {number=} opt_sy The scale factor to use for the y dimension.
* @return {!goog.math.Box} This box after scaling.
*/
goog.math.Box.prototype.scale = function(sx, opt_sy) {
var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
this.left *= sx;
this.right *= sx;
this.top *= sy;
this.bottom *= sy;
return this;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A utility class for representing three-dimensional points.
*
* Based heavily on coordinate.js by:
*/
goog.provide('goog.math.Coordinate3');
/**
* Class for representing coordinates and positions in 3 dimensions.
*
* @param {number=} opt_x X coordinate, defaults to 0.
* @param {number=} opt_y Y coordinate, defaults to 0.
* @param {number=} opt_z Z coordinate, defaults to 0.
* @constructor
*/
goog.math.Coordinate3 = function(opt_x, opt_y, opt_z) {
/**
* X-value
* @type {number}
*/
this.x = goog.isDef(opt_x) ? opt_x : 0;
/**
* Y-value
* @type {number}
*/
this.y = goog.isDef(opt_y) ? opt_y : 0;
/**
* Z-value
* @type {number}
*/
this.z = goog.isDef(opt_z) ? opt_z : 0;
};
/**
* Returns a new copy of the coordinate.
*
* @return {!goog.math.Coordinate3} A clone of this coordinate.
*/
goog.math.Coordinate3.prototype.clone = function() {
return new goog.math.Coordinate3(this.x, this.y, this.z);
};
if (goog.DEBUG) {
/**
* Returns a nice string representing the coordinate.
*
* @return {string} In the form (50, 73, 31).
* @override
*/
goog.math.Coordinate3.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
};
}
/**
* Compares coordinates for equality.
*
* @param {goog.math.Coordinate3} a A Coordinate3.
* @param {goog.math.Coordinate3} b A Coordinate3.
* @return {boolean} True iff the coordinates are equal, or if both are null.
*/
goog.math.Coordinate3.equals = function(a, b) {
if (a == b) {
return true;
}
if (!a || !b) {
return false;
}
return a.x == b.x && a.y == b.y && a.z == b.z;
};
/**
* Returns the distance between two coordinates.
*
* @param {goog.math.Coordinate3} a A Coordinate3.
* @param {goog.math.Coordinate3} b A Coordinate3.
* @return {number} The distance between {@code a} and {@code b}.
*/
goog.math.Coordinate3.distance = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dz = a.z - b.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
};
/**
* Returns the squared distance between two coordinates. Squared distances can
* be used for comparisons when the actual value is not required.
*
* Performance note: eliminating the square root is an optimization often used
* in lower-level languages, but the speed difference is not nearly as
* pronounced in JavaScript (only a few percent.)
*
* @param {goog.math.Coordinate3} a A Coordinate3.
* @param {goog.math.Coordinate3} b A Coordinate3.
* @return {number} The squared distance between {@code a} and {@code b}.
*/
goog.math.Coordinate3.squaredDistance = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dz = a.z - b.z;
return dx * dx + dy * dy + dz * dz;
};
/**
* Returns the difference between two coordinates as a new
* goog.math.Coordinate3.
*
* @param {goog.math.Coordinate3} a A Coordinate3.
* @param {goog.math.Coordinate3} b A Coordinate3.
* @return {!goog.math.Coordinate3} A Coordinate3 representing the difference
* between {@code a} and {@code b}.
*/
goog.math.Coordinate3.difference = function(a, b) {
return new goog.math.Coordinate3(a.x - b.x, a.y - b.y, a.z - b.z);
};
/**
* Returns the contents of this coordinate as a 3 value Array.
*
* @return {!Array.<number>} A new array.
*/
goog.math.Coordinate3.prototype.toArray = function() {
return [this.x, this.y, this.z];
};
/**
* Converts a three element array into a Coordinate3 object. If the value
* passed in is not an array, not array-like, or not of the right length, an
* error is thrown.
*
* @param {Array.<number>} a Array of numbers to become a coordinate.
* @return {!goog.math.Coordinate3} A new coordinate from the array values.
* @throws {Error} When the oject passed in is not valid.
*/
goog.math.Coordinate3.fromArray = function(a) {
if (a.length <= 3) {
return new goog.math.Coordinate3(a[0], a[1], a[2]);
}
throw Error('Conversion from an array requires an array of length 3');
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a line in 2D space.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.math.Line');
goog.require('goog.math');
goog.require('goog.math.Coordinate');
/**
* Object representing a line.
* @param {number} x0 X coordinate of the start point.
* @param {number} y0 Y coordinate of the start point.
* @param {number} x1 X coordinate of the end point.
* @param {number} y1 Y coordinate of the end point.
* @constructor
*/
goog.math.Line = function(x0, y0, x1, y1) {
/**
* X coordinate of the first point.
* @type {number}
*/
this.x0 = x0;
/**
* Y coordinate of the first point.
* @type {number}
*/
this.y0 = y0;
/**
* X coordinate of the first control point.
* @type {number}
*/
this.x1 = x1;
/**
* Y coordinate of the first control point.
* @type {number}
*/
this.y1 = y1;
};
/**
* @return {!goog.math.Line} A copy of this line.
*/
goog.math.Line.prototype.clone = function() {
return new goog.math.Line(this.x0, this.y0, this.x1, this.y1);
};
/**
* Tests whether the given line is exactly the same as this one.
* @param {goog.math.Line} other The other line.
* @return {boolean} Whether the given line is the same as this one.
*/
goog.math.Line.prototype.equals = function(other) {
return this.x0 == other.x0 && this.y0 == other.y0 &&
this.x1 == other.x1 && this.y1 == other.y1;
};
/**
* @return {number} The squared length of the line segment used to define the
* line.
*/
goog.math.Line.prototype.getSegmentLengthSquared = function() {
var xdist = this.x1 - this.x0;
var ydist = this.y1 - this.y0;
return xdist * xdist + ydist * ydist;
};
/**
* @return {number} The length of the line segment used to define the line.
*/
goog.math.Line.prototype.getSegmentLength = function() {
return Math.sqrt(this.getSegmentLengthSquared());
};
/**
* Computes the interpolation parameter for the point on the line closest to
* a given point.
* @param {number|goog.math.Coordinate} x The x coordinate of the point, or
* a coordinate object.
* @param {number=} opt_y The y coordinate of the point - required if x is a
* number, ignored if x is a goog.math.Coordinate.
* @return {number} The interpolation parameter of the point on the line
* closest to the given point.
* @private
*/
goog.math.Line.prototype.getClosestLinearInterpolation_ = function(x, opt_y) {
var y;
if (x instanceof goog.math.Coordinate) {
y = x.y;
x = x.x;
} else {
y = opt_y;
}
var x0 = this.x0;
var y0 = this.y0;
var xChange = this.x1 - x0;
var yChange = this.y1 - y0;
return ((x - x0) * xChange + (y - y0) * yChange) /
this.getSegmentLengthSquared();
};
/**
* Returns the point on the line segment proportional to t, where for t = 0 we
* return the starting point and for t = 1 we return the end point. For t < 0
* or t > 1 we extrapolate along the line defined by the line segment.
* @param {number} t The interpolation parameter along the line segment.
* @return {!goog.math.Coordinate} The point on the line segment at t.
*/
goog.math.Line.prototype.getInterpolatedPoint = function(t) {
return new goog.math.Coordinate(
goog.math.lerp(this.x0, this.x1, t),
goog.math.lerp(this.y0, this.y1, t));
};
/**
* Computes the point on the line closest to a given point. Note that a line
* in this case is defined as the infinite line going through the start and end
* points. To find the closest point on the line segment itself see
* {@see #getClosestSegmentPoint}.
* @param {number|goog.math.Coordinate} x The x coordinate of the point, or
* a coordinate object.
* @param {number=} opt_y The y coordinate of the point - required if x is a
* number, ignored if x is a goog.math.Coordinate.
* @return {!goog.math.Coordinate} The point on the line closest to the given
* point.
*/
goog.math.Line.prototype.getClosestPoint = function(x, opt_y) {
return this.getInterpolatedPoint(
this.getClosestLinearInterpolation_(x, opt_y));
};
/**
* Computes the point on the line segment closest to a given point.
* @param {number|goog.math.Coordinate} x The x coordinate of the point, or
* a coordinate object.
* @param {number=} opt_y The y coordinate of the point - required if x is a
* number, ignored if x is a goog.math.Coordinate.
* @return {!goog.math.Coordinate} The point on the line segment closest to the
* given point.
*/
goog.math.Line.prototype.getClosestSegmentPoint = function(x, opt_y) {
return this.getInterpolatedPoint(
goog.math.clamp(this.getClosestLinearInterpolation_(x, opt_y), 0, 1));
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Class for representing matrices and static helper functions.
*/
goog.provide('goog.math.Matrix');
goog.require('goog.array');
goog.require('goog.math');
goog.require('goog.math.Size');
/**
* Class for representing and manipulating matrices.
*
* The entry that lies in the i-th row and the j-th column of a matrix is
* typically referred to as the i,j entry of the matrix.
*
* The m-by-n matrix A would have its entries referred to as:
* [ a0,0 a0,1 a0,2 ... a0,j ... a0,n ]
* [ a1,0 a1,1 a1,2 ... a1,j ... a1,n ]
* [ a2,0 a2,1 a2,2 ... a2,j ... a2,n ]
* [ . . . . . ]
* [ . . . . . ]
* [ . . . . . ]
* [ ai,0 ai,1 ai,2 ... ai,j ... ai,n ]
* [ . . . . . ]
* [ . . . . . ]
* [ . . . . . ]
* [ am,0 am,1 am,2 ... am,j ... am,n ]
*
* @param {goog.math.Matrix|Array.<Array.<number>>|goog.math.Size|number} m
* A matrix to copy, a 2D-array to take as a template, a size object for
* dimensions, or the number of rows.
* @param {number=} opt_n Number of columns of the matrix (only applicable if
* the first argument is also numeric).
* @constructor
*/
goog.math.Matrix = function(m, opt_n) {
if (m instanceof goog.math.Matrix) {
this.array_ = m.toArray();
} else if (goog.isArrayLike(m) &&
goog.math.Matrix.isValidArray(/** @type {!Array} */ (m))) {
this.array_ = goog.array.clone(/** @type {!Array.<!Array.<number>>} */ (m));
} else if (m instanceof goog.math.Size) {
this.array_ = goog.math.Matrix.createZeroPaddedArray_(m.height, m.width);
} else if (goog.isNumber(m) && goog.isNumber(opt_n) && m > 0 && opt_n > 0) {
this.array_ = goog.math.Matrix.createZeroPaddedArray_(
/** @type {number} */ (m), opt_n);
} else {
throw Error('Invalid argument(s) for Matrix contructor');
}
this.size_ = new goog.math.Size(this.array_[0].length, this.array_.length);
};
/**
* Creates a square identity matrix. i.e. for n = 3:
* <pre>
* [ 1 0 0 ]
* [ 0 1 0 ]
* [ 0 0 1 ]
* </pre>
* @param {number} n The size of the square identity matrix.
* @return {!goog.math.Matrix} Identity matrix of width and height {@code n}.
*/
goog.math.Matrix.createIdentityMatrix = function(n) {
var rv = [];
for (var i = 0; i < n; i++) {
rv[i] = [];
for (var j = 0; j < n; j++) {
rv[i][j] = i == j ? 1 : 0;
}
}
return new goog.math.Matrix(rv);
};
/**
* Calls a function for each cell in a matrix.
* @param {goog.math.Matrix} matrix The matrix to iterate over.
* @param {Function} fn The function to call for every element. This function
* takes 4 arguments (value, i, j, and the matrix)
* and the return value is irrelevant.
* @param {Object=} opt_obj The object to be used as the value of 'this'
* within {@code fn}.
*/
goog.math.Matrix.forEach = function(matrix, fn, opt_obj) {
for (var i = 0; i < matrix.getSize().height; i++) {
for (var j = 0; j < matrix.getSize().width; j++) {
fn.call(opt_obj, matrix.array_[i][j], i, j, matrix);
}
}
};
/**
* Tests whether an array is a valid matrix. A valid array is an array of
* arrays where all arrays are of the same length and all elements are numbers.
* @param {Array} arr An array to test.
* @return {boolean} Whether the array is a valid matrix.
*/
goog.math.Matrix.isValidArray = function(arr) {
var len = 0;
for (var i = 0; i < arr.length; i++) {
if (!goog.isArrayLike(arr[i]) || len > 0 && arr[i].length != len) {
return false;
}
for (var j = 0; j < arr[i].length; j++) {
if (!goog.isNumber(arr[i][j])) {
return false;
}
}
if (len == 0) {
len = arr[i].length;
}
}
return len != 0;
};
/**
* Calls a function for every cell in a matrix and inserts the result into a
* new matrix of equal dimensions.
* @param {goog.math.Matrix} matrix The matrix to iterate over.
* @param {Function} fn The function to call for every element. This function
* takes 4 arguments (value, i, j and the matrix)
* and should return something. The result will be inserted
* into a new matrix.
* @param {Object=} opt_obj The object to be used as the value of 'this'
* within {@code fn}.
* @return {!goog.math.Matrix} A new matrix with the results from {@code fn}.
*/
goog.math.Matrix.map = function(matrix, fn, opt_obj) {
var m = new goog.math.Matrix(matrix.getSize());
goog.math.Matrix.forEach(matrix, function(value, i, j) {
m.array_[i][j] = fn.call(opt_obj, value, i, j, matrix);
});
return m;
};
/**
* Creates a new zero padded matix.
* @param {number} m Height of matrix.
* @param {number} n Width of matrix.
* @return {!Array.<!Array.<number>>} The new zero padded matrix.
* @private
*/
goog.math.Matrix.createZeroPaddedArray_ = function(m, n) {
var rv = [];
for (var i = 0; i < m; i++) {
rv[i] = [];
for (var j = 0; j < n; j++) {
rv[i][j] = 0;
}
}
return rv;
};
/**
* Internal array representing the matrix.
* @type {!Array.<!Array.<number>>}
* @private
*/
goog.math.Matrix.prototype.array_;
/**
* After construction the Matrix's size is constant and stored in this object.
* @type {!goog.math.Size}
* @private
*/
goog.math.Matrix.prototype.size_;
/**
* Returns a new matrix that is the sum of this and the provided matrix.
* @param {goog.math.Matrix} m The matrix to add to this one.
* @return {!goog.math.Matrix} Resultant sum.
*/
goog.math.Matrix.prototype.add = function(m) {
if (!goog.math.Size.equals(this.size_, m.getSize())) {
throw Error('Matrix summation is only supported on arrays of equal size');
}
return goog.math.Matrix.map(this, function(val, i, j) {
return val + m.array_[i][j];
});
};
/**
* Appends the given matrix to the right side of this matrix.
* @param {goog.math.Matrix} m The matrix to augment this matrix with.
* @return {!goog.math.Matrix} A new matrix with additional columns on the
* right.
*/
goog.math.Matrix.prototype.appendColumns = function(m) {
if (this.size_.height != m.getSize().height) {
throw Error('The given matrix has height ' + m.size_.height + ', but ' +
' needs to have height ' + this.size_.height + '.');
}
var result = new goog.math.Matrix(this.size_.height,
this.size_.width + m.size_.width);
goog.math.Matrix.forEach(this, function(value, i, j) {
result.array_[i][j] = value;
});
goog.math.Matrix.forEach(m, function(value, i, j) {
result.array_[i][this.size_.width + j] = value;
}, this);
return result;
};
/**
* Appends the given matrix to the bottom of this matrix.
* @param {goog.math.Matrix} m The matrix to augment this matrix with.
* @return {!goog.math.Matrix} A new matrix with added columns on the bottom.
*/
goog.math.Matrix.prototype.appendRows = function(m) {
if (this.size_.width != m.getSize().width) {
throw Error('The given matrix has width ' + m.size_.width + ', but ' +
' needs to have width ' + this.size_.width + '.');
}
var result = new goog.math.Matrix(this.size_.height + m.size_.height,
this.size_.width);
goog.math.Matrix.forEach(this, function(value, i, j) {
result.array_[i][j] = value;
});
goog.math.Matrix.forEach(m, function(value, i, j) {
result.array_[this.size_.height + i][j] = value;
}, this);
return result;
};
/**
* Returns whether the given matrix equals this matrix.
* @param {goog.math.Matrix} m The matrix to compare to this one.
* @param {number=} opt_tolerance The tolerance when comparing array entries.
* @return {boolean} Whether the given matrix equals this matrix.
*/
goog.math.Matrix.prototype.equals = function(m, opt_tolerance) {
if (this.size_.width != m.size_.width) {
return false;
}
if (this.size_.height != m.size_.height) {
return false;
}
var tolerance = opt_tolerance || 0;
for (var i = 0; i < this.size_.height; i++) {
for (var j = 0; j < this.size_.width; j++) {
if (!goog.math.nearlyEquals(this.array_[i][j], m.array_[i][j],
tolerance)) {
return false;
}
}
}
return true;
};
/**
* Returns the determinant of this matrix. The determinant of a matrix A is
* often denoted as |A| and can only be applied to a square matrix.
* @return {number} The determinant of this matrix.
*/
goog.math.Matrix.prototype.getDeterminant = function() {
if (!this.isSquare()) {
throw Error('A determinant can only be take on a square matrix');
}
return this.getDeterminant_();
};
/**
* Returns the inverse of this matrix if it exists or null if the matrix is
* not invertible.
* @return {goog.math.Matrix} A new matrix which is the inverse of this matrix.
*/
goog.math.Matrix.prototype.getInverse = function() {
if (!this.isSquare()) {
throw Error('An inverse can only be taken on a square matrix.');
}
if (this.getSize().width == 1) {
var a = this.getValueAt(0, 0);
return a == 0 ? null : new goog.math.Matrix([[1 / a]]);
}
var identity = goog.math.Matrix.createIdentityMatrix(this.size_.height);
var mi = this.appendColumns(identity).getReducedRowEchelonForm();
var i = mi.getSubmatrixByCoordinates_(
0, 0, identity.size_.width - 1, identity.size_.height - 1);
if (!i.equals(identity)) {
return null; // This matrix was not invertible
}
return mi.getSubmatrixByCoordinates_(0, identity.size_.width);
};
/**
* Transforms this matrix into reduced row echelon form.
* @return {!goog.math.Matrix} A new matrix reduced row echelon form.
*/
goog.math.Matrix.prototype.getReducedRowEchelonForm = function() {
var result = new goog.math.Matrix(this);
var col = 0;
// Each iteration puts one row in reduced row echelon form
for (var row = 0; row < result.size_.height; row++) {
if (col >= result.size_.width) {
return result;
}
// Scan each column starting from this row on down for a non-zero value
var i = row;
while (result.array_[i][col] == 0) {
i++;
if (i == result.size_.height) {
i = row;
col++;
if (col == result.size_.width) {
return result;
}
}
}
// Make the row we found the current row with a leading 1
this.swapRows_(i, row);
var divisor = result.array_[row][col];
for (var j = col; j < result.size_.width; j++) {
result.array_[row][j] = result.array_[row][j] / divisor;
}
// Subtract a multiple of this row from each other row
// so that all the other entries in this column are 0
for (i = 0; i < result.size_.height; i++) {
if (i != row) {
var multiple = result.array_[i][col];
for (var j = col; j < result.size_.width; j++) {
result.array_[i][j] -= multiple * result.array_[row][j];
}
}
}
// Move on to the next column
col++;
}
return result;
};
/**
* @return {!goog.math.Size} The dimensions of the matrix.
*/
goog.math.Matrix.prototype.getSize = function() {
return this.size_;
};
/**
* Return the transpose of this matrix. For an m-by-n matrix, the transpose
* is the n-by-m matrix which results from turning rows into columns and columns
* into rows
* @return {!goog.math.Matrix} A new matrix A^T.
*/
goog.math.Matrix.prototype.getTranspose = function() {
var m = new goog.math.Matrix(this.size_.width, this.size_.height);
goog.math.Matrix.forEach(this, function(value, i, j) {
m.array_[j][i] = value;
});
return m;
};
/**
* Retrieves the value of a particular coordinate in the matrix or null if the
* requested coordinates are out of range.
* @param {number} i The i index of the coordinate.
* @param {number} j The j index of the coordinate.
* @return {?number} The value at the specified coordinate.
*/
goog.math.Matrix.prototype.getValueAt = function(i, j) {
if (!this.isInBounds_(i, j)) {
return null;
}
return this.array_[i][j];
};
/**
* @return {boolean} Whether the horizontal and vertical dimensions of this
* matrix are the same.
*/
goog.math.Matrix.prototype.isSquare = function() {
return this.size_.width == this.size_.height;
};
/**
* Sets the value at a particular coordinate (if the coordinate is within the
* bounds of the matrix).
* @param {number} i The i index of the coordinate.
* @param {number} j The j index of the coordinate.
* @param {number} value The new value for the coordinate.
*/
goog.math.Matrix.prototype.setValueAt = function(i, j, value) {
if (!this.isInBounds_(i, j)) {
throw Error(
'Index out of bounds when setting matrix value, (' + i + ',' + j +
') in size (' + this.size_.height + ',' + this.size_.width + ')');
}
this.array_[i][j] = value;
};
/**
* Performs matrix or scalar multiplication on a matrix and returns the
* resultant matrix.
*
* Matrix multiplication is defined between two matrices only if the number of
* columns of the first matrix is the same as the number of rows of the second
* matrix. If A is an m-by-n matrix and B is an n-by-p matrix, then their
* product AB is an m-by-p matrix
*
* Scalar multiplication returns a matrix of the same size as the original,
* each value multiplied by the given value.
*
* @param {goog.math.Matrix|number} m Matrix/number to multiply the matrix by.
* @return {!goog.math.Matrix} Resultant product.
*/
goog.math.Matrix.prototype.multiply = function(m) {
if (m instanceof goog.math.Matrix) {
if (this.size_.width != m.getSize().height) {
throw Error('Invalid matrices for multiplication. Second matrix ' +
'should have the same number of rows as the first has columns.');
}
return this.matrixMultiply_(/** @type {!goog.math.Matrix} */ (m));
} else if (goog.isNumber(m)) {
return this.scalarMultiply_(/** @type {number} */ (m));
} else {
throw Error('A matrix can only be multiplied by' +
' a number or another matrix.');
}
};
/**
* Returns a new matrix that is the difference of this and the provided matrix.
* @param {goog.math.Matrix} m The matrix to subtract from this one.
* @return {!goog.math.Matrix} Resultant difference.
*/
goog.math.Matrix.prototype.subtract = function(m) {
if (!goog.math.Size.equals(this.size_, m.getSize())) {
throw Error(
'Matrix subtraction is only supported on arrays of equal size.');
}
return goog.math.Matrix.map(this, function(val, i, j) {
return val - m.array_[i][j];
});
};
/**
* @return {!Array.<!Array.<number>>} A 2D internal array representing this
* matrix. Not a clone.
*/
goog.math.Matrix.prototype.toArray = function() {
return this.array_;
};
if (goog.DEBUG) {
/**
* Returns a string representation of the matrix. e.g.
* <pre>
* [ 12 5 9 1 ]
* [ 4 16 0 17 ]
* [ 12 5 1 23 ]
* </pre>
*
* @return {string} A string representation of this matrix.
* @override
*/
goog.math.Matrix.prototype.toString = function() {
// Calculate correct padding for optimum display of matrix
var maxLen = 0;
goog.math.Matrix.forEach(this, function(val) {
var len = String(val).length;
if (len > maxLen) {
maxLen = len;
}
});
// Build the string
var sb = [];
goog.array.forEach(this.array_, function(row, x) {
sb.push('[ ');
goog.array.forEach(row, function(val, y) {
var strval = String(val);
sb.push(goog.string.repeat(' ', maxLen - strval.length) + strval + ' ');
});
sb.push(']\n');
});
return sb.join('');
};
}
/**
* Returns the signed minor.
* @param {number} i The row index.
* @param {number} j The column index.
* @return {number} The cofactor C[i,j] of this matrix.
* @private
*/
goog.math.Matrix.prototype.getCofactor_ = function(i, j) {
return (i + j % 2 == 0 ? 1 : -1) * this.getMinor_(i, j);
};
/**
* Returns the determinant of this matrix. The determinant of a matrix A is
* often denoted as |A| and can only be applied to a square matrix. Same as
* public method but without validation. Implemented using Laplace's formula.
* @return {number} The determinant of this matrix.
* @private
*/
goog.math.Matrix.prototype.getDeterminant_ = function() {
if (this.getSize().area() == 1) {
return this.array_[0][0];
}
// We might want to use matrix decomposition to improve running time
// For now we'll do a Laplace expansion along the first row
var determinant = 0;
for (var j = 0; j < this.size_.width; j++) {
determinant += (this.array_[0][j] * this.getCofactor_(0, j));
}
return determinant;
};
/**
* Returns the determinant of the submatrix resulting from the deletion of row i
* and column j.
* @param {number} i The row to delete.
* @param {number} j The column to delete.
* @return {number} The first minor M[i,j] of this matrix.
* @private
*/
goog.math.Matrix.prototype.getMinor_ = function(i, j) {
return this.getSubmatrixByDeletion_(i, j).getDeterminant_();
};
/**
* Returns a submatrix contained within this matrix.
* @param {number} i1 The upper row index.
* @param {number} j1 The left column index.
* @param {number=} opt_i2 The lower row index.
* @param {number=} opt_j2 The right column index.
* @return {!goog.math.Matrix} The submatrix contained within the given bounds.
* @private
*/
goog.math.Matrix.prototype.getSubmatrixByCoordinates_ =
function(i1, j1, opt_i2, opt_j2) {
var i2 = opt_i2 ? opt_i2 : this.size_.height - 1;
var j2 = opt_j2 ? opt_j2 : this.size_.width - 1;
var result = new goog.math.Matrix(i2 - i1 + 1, j2 - j1 + 1);
goog.math.Matrix.forEach(result, function(value, i, j) {
result.array_[i][j] = this.array_[i1 + i][j1 + j];
}, this);
return result;
};
/**
* Returns a new matrix equal to this one, but with row i and column j deleted.
* @param {number} i The row index of the coordinate.
* @param {number} j The column index of the coordinate.
* @return {!goog.math.Matrix} The value at the specified coordinate.
* @private
*/
goog.math.Matrix.prototype.getSubmatrixByDeletion_ = function(i, j) {
var m = new goog.math.Matrix(this.size_.width - 1, this.size_.height - 1);
goog.math.Matrix.forEach(m, function(value, x, y) {
m.setValueAt(x, y, this.array_[x >= i ? x + 1 : x][y >= j ? y + 1 : y]);
}, this);
return m;
};
/**
* Returns whether the given coordinates are contained within the bounds of the
* matrix.
* @param {number} i The i index of the coordinate.
* @param {number} j The j index of the coordinate.
* @return {boolean} The value at the specified coordinate.
* @private
*/
goog.math.Matrix.prototype.isInBounds_ = function(i, j) {
return i >= 0 && i < this.size_.height &&
j >= 0 && j < this.size_.width;
};
/**
* Matrix multiplication is defined between two matrices only if the number of
* columns of the first matrix is the same as the number of rows of the second
* matrix. If A is an m-by-n matrix and B is an n-by-p matrix, then their
* product AB is an m-by-p matrix
*
* @param {goog.math.Matrix} m Matrix to multiply the matrix by.
* @return {!goog.math.Matrix} Resultant product.
* @private
*/
goog.math.Matrix.prototype.matrixMultiply_ = function(m) {
var resultMatrix = new goog.math.Matrix(this.size_.height, m.getSize().width);
goog.math.Matrix.forEach(resultMatrix, function(val, x, y) {
var newVal = 0;
for (var i = 0; i < this.size_.width; i++) {
newVal += this.getValueAt(x, i) * m.getValueAt(i, y);
}
resultMatrix.setValueAt(x, y, newVal);
}, this);
return resultMatrix;
};
/**
* Scalar multiplication returns a matrix of the same size as the original,
* each value multiplied by the given value.
*
* @param {number} m number to multiply the matrix by.
* @return {!goog.math.Matrix} Resultant product.
* @private
*/
goog.math.Matrix.prototype.scalarMultiply_ = function(m) {
return goog.math.Matrix.map(this, function(val, x, y) {
return val * m;
});
};
/**
* Swaps two rows.
* @param {number} i1 The index of the first row to swap.
* @param {number} i2 The index of the second row to swap.
* @private
*/
goog.math.Matrix.prototype.swapRows_ = function(i1, i2) {
var tmp = this.array_[i1];
this.array_[i1] = this.array_[i2];
this.array_[i2] = tmp;
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A utility class for representing two-dimensional positions.
*/
goog.provide('goog.math.Coordinate');
goog.require('goog.math');
/**
* Class for representing coordinates and positions.
* @param {number=} opt_x Left, defaults to 0.
* @param {number=} opt_y Top, defaults to 0.
* @constructor
*/
goog.math.Coordinate = function(opt_x, opt_y) {
/**
* X-value
* @type {number}
*/
this.x = goog.isDef(opt_x) ? opt_x : 0;
/**
* Y-value
* @type {number}
*/
this.y = goog.isDef(opt_y) ? opt_y : 0;
};
/**
* Returns a new copy of the coordinate.
* @return {!goog.math.Coordinate} A clone of this coordinate.
*/
goog.math.Coordinate.prototype.clone = function() {
return new goog.math.Coordinate(this.x, this.y);
};
if (goog.DEBUG) {
/**
* Returns a nice string representing the coordinate.
* @return {string} In the form (50, 73).
* @override
*/
goog.math.Coordinate.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ')';
};
}
/**
* Compares coordinates for equality.
* @param {goog.math.Coordinate} a A Coordinate.
* @param {goog.math.Coordinate} b A Coordinate.
* @return {boolean} True iff the coordinates are equal, or if both are null.
*/
goog.math.Coordinate.equals = function(a, b) {
if (a == b) {
return true;
}
if (!a || !b) {
return false;
}
return a.x == b.x && a.y == b.y;
};
/**
* Returns the distance between two coordinates.
* @param {!goog.math.Coordinate} a A Coordinate.
* @param {!goog.math.Coordinate} b A Coordinate.
* @return {number} The distance between {@code a} and {@code b}.
*/
goog.math.Coordinate.distance = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
};
/**
* Returns the magnitude of a coordinate.
* @param {!goog.math.Coordinate} a A Coordinate.
* @return {number} The distance between the origin and {@code a}.
*/
goog.math.Coordinate.magnitude = function(a) {
return Math.sqrt(a.x * a.x + a.y * a.y);
};
/**
* Returns the angle from the origin to a coordinate.
* @param {!goog.math.Coordinate} a A Coordinate.
* @return {number} The angle, in degrees, clockwise from the positive X
* axis to {@code a}.
*/
goog.math.Coordinate.azimuth = function(a) {
return goog.math.angle(0, 0, a.x, a.y);
};
/**
* Returns the squared distance between two coordinates. Squared distances can
* be used for comparisons when the actual value is not required.
*
* Performance note: eliminating the square root is an optimization often used
* in lower-level languages, but the speed difference is not nearly as
* pronounced in JavaScript (only a few percent.)
*
* @param {!goog.math.Coordinate} a A Coordinate.
* @param {!goog.math.Coordinate} b A Coordinate.
* @return {number} The squared distance between {@code a} and {@code b}.
*/
goog.math.Coordinate.squaredDistance = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
return dx * dx + dy * dy;
};
/**
* Returns the difference between two coordinates as a new
* goog.math.Coordinate.
* @param {!goog.math.Coordinate} a A Coordinate.
* @param {!goog.math.Coordinate} b A Coordinate.
* @return {!goog.math.Coordinate} A Coordinate representing the difference
* between {@code a} and {@code b}.
*/
goog.math.Coordinate.difference = function(a, b) {
return new goog.math.Coordinate(a.x - b.x, a.y - b.y);
};
/**
* Returns the sum of two coordinates as a new goog.math.Coordinate.
* @param {!goog.math.Coordinate} a A Coordinate.
* @param {!goog.math.Coordinate} b A Coordinate.
* @return {!goog.math.Coordinate} A Coordinate representing the sum of the two
* coordinates.
*/
goog.math.Coordinate.sum = function(a, b) {
return new goog.math.Coordinate(a.x + b.x, a.y + b.y);
};
/**
* Rounds the x and y fields to the next larger integer values.
* @return {!goog.math.Coordinate} This coordinate with ceil'd fields.
*/
goog.math.Coordinate.prototype.ceil = function() {
this.x = Math.ceil(this.x);
this.y = Math.ceil(this.y);
return this;
};
/**
* Rounds the x and y fields to the next smaller integer values.
* @return {!goog.math.Coordinate} This coordinate with floored fields.
*/
goog.math.Coordinate.prototype.floor = function() {
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
return this;
};
/**
* Rounds the x and y fields to the nearest integer values.
* @return {!goog.math.Coordinate} This coordinate with rounded fields.
*/
goog.math.Coordinate.prototype.round = function() {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
};
/**
* Translates this box by the given offsets. If a {@code goog.math.Coordinate}
* is given, then the x and y values are translated by the coordinate's x and y.
* Otherwise, x and y are translated by {@code tx} and {@code opt_ty}
* respectively.
* @param {number|goog.math.Coordinate} tx The value to translate x by or the
* the coordinate to translate this coordinate by.
* @param {number=} opt_ty The value to translate y by.
* @return {!goog.math.Coordinate} This coordinate after translating.
*/
goog.math.Coordinate.prototype.translate = function(tx, opt_ty) {
if (tx instanceof goog.math.Coordinate) {
this.x += tx.x;
this.y += tx.y;
} else {
this.x += tx;
if (goog.isNumber(opt_ty)) {
this.y += opt_ty;
}
}
return this;
};
/**
* Scales this coordinate by the given scale factors. The x and y values are
* scaled by {@code sx} and {@code opt_sy} respectively. If {@code opt_sy}
* is not given, then {@code sx} is used for both x and y.
* @param {number} sx The scale factor to use for the x dimension.
* @param {number=} opt_sy The scale factor to use for the y dimension.
* @return {!goog.math.Coordinate} This coordinate after scaling.
*/
goog.math.Coordinate.prototype.scale = function(sx, opt_sy) {
var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
this.x *= sx;
this.y *= sy;
return this;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A RangeSet is a structure that manages a list of ranges.
* Numeric ranges may be added and removed from the RangeSet, and the set may
* be queried for the presence or absence of individual values or ranges of
* values.
*
* This may be used, for example, to track the availability of sparse elements
* in an array without iterating over the entire array.
*
* @author brenneman@google.com (Shawn Brenneman)
*/
goog.provide('goog.math.RangeSet');
goog.require('goog.array');
goog.require('goog.iter.Iterator');
goog.require('goog.iter.StopIteration');
goog.require('goog.math.Range');
/**
* Constructs a new RangeSet, which can store numeric ranges.
*
* Ranges are treated as half-closed: that is, they are exclusive of their end
* value [start, end).
*
* New ranges added to the set which overlap the values in one or more existing
* ranges will be merged.
*
* @constructor
*/
goog.math.RangeSet = function() {
/**
* A sorted list of ranges that represent the values in the set.
* @type {!Array.<!goog.math.Range>}
* @private
*/
this.ranges_ = [];
};
if (goog.DEBUG) {
/**
* @return {string} A debug string in the form [[1, 5], [8, 9], [15, 30]].
* @override
*/
goog.math.RangeSet.prototype.toString = function() {
return '[' + this.ranges_.join(', ') + ']';
};
}
/**
* Compares two sets for equality.
*
* @param {goog.math.RangeSet} a A range set.
* @param {goog.math.RangeSet} b A range set.
* @return {boolean} Whether both sets contain the same values.
*/
goog.math.RangeSet.equals = function(a, b) {
// Fast check for object equality. Also succeeds if a and b are both null.
return a == b || !!(a && b && goog.array.equals(a.ranges_, b.ranges_,
goog.math.Range.equals));
};
/**
* @return {!goog.math.RangeSet} A new RangeSet containing the same values as
* this one.
*/
goog.math.RangeSet.prototype.clone = function() {
var set = new goog.math.RangeSet();
for (var i = this.ranges_.length; i--;) {
set.ranges_[i] = this.ranges_[i].clone();
}
return set;
};
/**
* Adds a range to the set. If the new range overlaps existing values, those
* ranges will be merged.
*
* @param {goog.math.Range} a The range to add.
*/
goog.math.RangeSet.prototype.add = function(a) {
if (a.end <= a.start) {
// Empty ranges are ignored.
return;
}
a = a.clone();
// Find the insertion point.
for (var i = 0, b; b = this.ranges_[i]; i++) {
if (a.start <= b.end) {
a.start = Math.min(a.start, b.start);
break;
}
}
var insertionPoint = i;
for (; b = this.ranges_[i]; i++) {
if (a.end < b.start) {
break;
}
a.end = Math.max(a.end, b.end);
}
this.ranges_.splice(insertionPoint, i - insertionPoint, a);
};
/**
* Removes a range of values from the set.
*
* @param {goog.math.Range} a The range to remove.
*/
goog.math.RangeSet.prototype.remove = function(a) {
if (a.end <= a.start) {
// Empty ranges are ignored.
return;
}
// Find the insertion point.
for (var i = 0, b; b = this.ranges_[i]; i++) {
if (a.start < b.end) {
break;
}
}
if (!b || a.end < b.start) {
// The range being removed doesn't overlap any existing range. Exit early.
return;
}
var insertionPoint = i;
if (a.start > b.start) {
// There is an overlap with the nearest range. Modify it accordingly.
insertionPoint++;
if (a.end < b.end) {
goog.array.insertAt(this.ranges_,
new goog.math.Range(a.end, b.end),
insertionPoint);
}
b.end = a.start;
}
for (i = insertionPoint; b = this.ranges_[i]; i++) {
b.start = Math.max(a.end, b.start);
if (a.end < b.end) {
break;
}
}
this.ranges_.splice(insertionPoint, i - insertionPoint);
};
/**
* Determines whether a given range is in the set. Only succeeds if the entire
* range is available.
*
* @param {goog.math.Range} a The query range.
* @return {boolean} Whether the entire requested range is set.
*/
goog.math.RangeSet.prototype.contains = function(a) {
if (a.end <= a.start) {
return false;
}
for (var i = 0, b; b = this.ranges_[i]; i++) {
if (a.start < b.end) {
if (a.end >= b.start) {
return goog.math.Range.contains(b, a);
}
break;
}
}
return false;
};
/**
* Determines whether a given value is set in the RangeSet.
*
* @param {number} value The value to test.
* @return {boolean} Whether the given value is in the set.
*/
goog.math.RangeSet.prototype.containsValue = function(value) {
for (var i = 0, b; b = this.ranges_[i]; i++) {
if (value < b.end) {
if (value >= b.start) {
return true;
}
break;
}
}
return false;
};
/**
* Returns the union of this RangeSet with another.
*
* @param {goog.math.RangeSet} set Another RangeSet.
* @return {!goog.math.RangeSet} A new RangeSet containing all values from
* either set.
*/
goog.math.RangeSet.prototype.union = function(set) {
// TODO(brenneman): A linear-time merge would be preferable if it is ever a
// bottleneck.
set = set.clone();
for (var i = 0, a; a = this.ranges_[i]; i++) {
set.add(a);
}
return set;
};
/**
* Subtracts the ranges of another set from this one, returning the result
* as a new RangeSet.
*
* @param {!goog.math.RangeSet} set The RangeSet to subtract.
* @return {!goog.math.RangeSet} A new RangeSet containing all values in this
* set minus the values of the input set.
*/
goog.math.RangeSet.prototype.difference = function(set) {
var ret = this.clone();
for (var i = 0, a; a = set.ranges_[i]; i++) {
ret.remove(a);
}
return ret;
};
/**
* Intersects this RangeSet with another.
*
* @param {goog.math.RangeSet} set The RangeSet to intersect with.
* @return {!goog.math.RangeSet} A new RangeSet containing all values set in
* both this and the input set.
*/
goog.math.RangeSet.prototype.intersection = function(set) {
if (this.isEmpty() || set.isEmpty()) {
return new goog.math.RangeSet();
}
return this.difference(set.inverse(this.getBounds()));
};
/**
* Creates a subset of this set over the input range.
*
* @param {goog.math.Range} range The range to copy into the slice.
* @return {!goog.math.RangeSet} A new RangeSet with a copy of the values in the
* input range.
*/
goog.math.RangeSet.prototype.slice = function(range) {
var set = new goog.math.RangeSet();
if (range.start >= range.end) {
return set;
}
for (var i = 0, b; b = this.ranges_[i]; i++) {
if (b.end <= range.start) {
continue;
}
if (b.start > range.end) {
break;
}
set.add(new goog.math.Range(Math.max(range.start, b.start),
Math.min(range.end, b.end)));
}
return set;
};
/**
* Creates an inverted slice of this set over the input range.
*
* @param {goog.math.Range} range The range to copy into the slice.
* @return {!goog.math.RangeSet} A new RangeSet containing inverted values from
* the original over the input range.
*/
goog.math.RangeSet.prototype.inverse = function(range) {
var set = new goog.math.RangeSet();
set.add(range);
for (var i = 0, b; b = this.ranges_[i]; i++) {
if (range.start >= b.end) {
continue;
}
if (range.end < b.start) {
break;
}
set.remove(b);
}
return set;
};
/**
* @return {number} The sum of the lengths of ranges covered in the set.
*/
goog.math.RangeSet.prototype.coveredLength = function() {
return /** @type {number} */ (goog.array.reduce(
this.ranges_,
function(res, range) {
return res + range.end - range.start;
}, 0));
};
/**
* @return {goog.math.Range} The total range this set covers, ignoring any
* gaps between ranges.
*/
goog.math.RangeSet.prototype.getBounds = function() {
if (this.ranges_.length) {
return new goog.math.Range(this.ranges_[0].start,
goog.array.peek(this.ranges_).end);
}
return null;
};
/**
* @return {boolean} Whether any ranges are currently in the set.
*/
goog.math.RangeSet.prototype.isEmpty = function() {
return this.ranges_.length == 0;
};
/**
* Removes all values in the set.
*/
goog.math.RangeSet.prototype.clear = function() {
this.ranges_.length = 0;
};
/**
* Returns an iterator that iterates over the ranges in the RangeSet.
*
* @param {boolean=} opt_keys Ignored for RangeSets.
* @return {!goog.iter.Iterator} An iterator over the values in the set.
*/
goog.math.RangeSet.prototype.__iterator__ = function(opt_keys) {
var i = 0;
var list = this.ranges_;
var iterator = new goog.iter.Iterator();
iterator.next = function() {
if (i >= list.length) {
throw goog.iter.StopIteration;
}
return list[i++].clone();
};
return iterator;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a cubic Bezier curve.
*
* Uses the deCasteljau algorithm to compute points on the curve.
* http://en.wikipedia.org/wiki/De_Casteljau's_algorithm
*
* Currently it uses an unrolled version of the algorithm for speed. Eventually
* it may be useful to use the loop form of the algorithm in order to support
* curves of arbitrary degree.
*
* @author robbyw@google.com (Robby Walker)
* @author wcrosby@google.com (Wayne Crosby)
*/
goog.provide('goog.math.Bezier');
goog.require('goog.math');
goog.require('goog.math.Coordinate');
/**
* Object representing a cubic bezier curve.
* @param {number} x0 X coordinate of the start point.
* @param {number} y0 Y coordinate of the start point.
* @param {number} x1 X coordinate of the first control point.
* @param {number} y1 Y coordinate of the first control point.
* @param {number} x2 X coordinate of the second control point.
* @param {number} y2 Y coordinate of the second control point.
* @param {number} x3 X coordinate of the end point.
* @param {number} y3 Y coordinate of the end point.
* @constructor
*/
goog.math.Bezier = function(x0, y0, x1, y1, x2, y2, x3, y3) {
/**
* X coordinate of the first point.
* @type {number}
*/
this.x0 = x0;
/**
* Y coordinate of the first point.
* @type {number}
*/
this.y0 = y0;
/**
* X coordinate of the first control point.
* @type {number}
*/
this.x1 = x1;
/**
* Y coordinate of the first control point.
* @type {number}
*/
this.y1 = y1;
/**
* X coordinate of the second control point.
* @type {number}
*/
this.x2 = x2;
/**
* Y coordinate of the second control point.
* @type {number}
*/
this.y2 = y2;
/**
* X coordinate of the end point.
* @type {number}
*/
this.x3 = x3;
/**
* Y coordinate of the end point.
* @type {number}
*/
this.y3 = y3;
};
/**
* Constant used to approximate ellipses.
* See: http://canvaspaint.org/blog/2006/12/ellipse/
* @type {number}
*/
goog.math.Bezier.KAPPA = 4 * (Math.sqrt(2) - 1) / 3;
/**
* @return {!goog.math.Bezier} A copy of this curve.
*/
goog.math.Bezier.prototype.clone = function() {
return new goog.math.Bezier(this.x0, this.y0, this.x1, this.y1, this.x2,
this.y2, this.x3, this.y3);
};
/**
* Test if the given curve is exactly the same as this one.
* @param {goog.math.Bezier} other The other curve.
* @return {boolean} Whether the given curve is the same as this one.
*/
goog.math.Bezier.prototype.equals = function(other) {
return this.x0 == other.x0 && this.y0 == other.y0 && this.x1 == other.x1 &&
this.y1 == other.y1 && this.x2 == other.x2 && this.y2 == other.y2 &&
this.x3 == other.x3 && this.y3 == other.y3;
};
/**
* Modifies the curve in place to progress in the opposite direction.
*/
goog.math.Bezier.prototype.flip = function() {
var temp = this.x0;
this.x0 = this.x3;
this.x3 = temp;
temp = this.y0;
this.y0 = this.y3;
this.y3 = temp;
temp = this.x1;
this.x1 = this.x2;
this.x2 = temp;
temp = this.y1;
this.y1 = this.y2;
this.y2 = temp;
};
/**
* Computes the curve at a point between 0 and 1.
* @param {number} t The point on the curve to find.
* @return {!goog.math.Coordinate} The computed coordinate.
*/
goog.math.Bezier.prototype.getPoint = function(t) {
// Special case start and end
if (t == 0) {
return new goog.math.Coordinate(this.x0, this.y0);
} else if (t == 1) {
return new goog.math.Coordinate(this.x3, this.y3);
}
// Step one - from 4 points to 3
var ix0 = goog.math.lerp(this.x0, this.x1, t);
var iy0 = goog.math.lerp(this.y0, this.y1, t);
var ix1 = goog.math.lerp(this.x1, this.x2, t);
var iy1 = goog.math.lerp(this.y1, this.y2, t);
var ix2 = goog.math.lerp(this.x2, this.x3, t);
var iy2 = goog.math.lerp(this.y2, this.y3, t);
// Step two - from 3 points to 2
ix0 = goog.math.lerp(ix0, ix1, t);
iy0 = goog.math.lerp(iy0, iy1, t);
ix1 = goog.math.lerp(ix1, ix2, t);
iy1 = goog.math.lerp(iy1, iy2, t);
// Final step - last point
return new goog.math.Coordinate(goog.math.lerp(ix0, ix1, t),
goog.math.lerp(iy0, iy1, t));
};
/**
* Changes this curve in place to be the portion of itself from [t, 1].
* @param {number} t The start of the desired portion of the curve.
*/
goog.math.Bezier.prototype.subdivideLeft = function(t) {
if (t == 1) {
return;
}
// Step one - from 4 points to 3
var ix0 = goog.math.lerp(this.x0, this.x1, t);
var iy0 = goog.math.lerp(this.y0, this.y1, t);
var ix1 = goog.math.lerp(this.x1, this.x2, t);
var iy1 = goog.math.lerp(this.y1, this.y2, t);
var ix2 = goog.math.lerp(this.x2, this.x3, t);
var iy2 = goog.math.lerp(this.y2, this.y3, t);
// Collect our new x1 and y1
this.x1 = ix0;
this.y1 = iy0;
// Step two - from 3 points to 2
ix0 = goog.math.lerp(ix0, ix1, t);
iy0 = goog.math.lerp(iy0, iy1, t);
ix1 = goog.math.lerp(ix1, ix2, t);
iy1 = goog.math.lerp(iy1, iy2, t);
// Collect our new x2 and y2
this.x2 = ix0;
this.y2 = iy0;
// Final step - last point
this.x3 = goog.math.lerp(ix0, ix1, t);
this.y3 = goog.math.lerp(iy0, iy1, t);
};
/**
* Changes this curve in place to be the portion of itself from [0, t].
* @param {number} t The end of the desired portion of the curve.
*/
goog.math.Bezier.prototype.subdivideRight = function(t) {
this.flip();
this.subdivideLeft(1 - t);
this.flip();
};
/**
* Changes this curve in place to be the portion of itself from [s, t].
* @param {number} s The start of the desired portion of the curve.
* @param {number} t The end of the desired portion of the curve.
*/
goog.math.Bezier.prototype.subdivide = function(s, t) {
this.subdivideRight(s);
this.subdivideLeft((t - s) / (1 - s));
};
/**
* Computes the position t of a point on the curve given its x coordinate.
* That is, for an input xVal, finds t s.t. getPoint(t).x = xVal.
* As such, the following should always be true up to some small epsilon:
* t ~ solvePositionFromXValue(getPoint(t).x) for t in [0, 1].
* @param {number} xVal The x coordinate of the point to find on the curve.
* @return {number} The position t.
*/
goog.math.Bezier.prototype.solvePositionFromXValue = function(xVal) {
// Desired precision on the computation.
var epsilon = 1e-6;
// Initial estimate of t using linear interpolation.
var t = (xVal - this.x0) / (this.x3 - this.x0);
if (t <= 0) {
return 0;
} else if (t >= 1) {
return 1;
}
// Try gradient descent to solve for t. If it works, it is very fast.
var tMin = 0;
var tMax = 1;
for (var i = 0; i < 8; i++) {
var value = this.getPoint(t).x;
var derivative = (this.getPoint(t + epsilon).x - value) / epsilon;
if (Math.abs(value - xVal) < epsilon) {
return t;
} else if (Math.abs(derivative) < epsilon) {
break;
} else {
if (value < xVal) {
tMin = t;
} else {
tMax = t;
}
t -= (value - xVal) / derivative;
}
}
// If the gradient descent got stuck in a local minimum, e.g. because
// the derivative was close to 0, use a Dichotomy refinement instead.
// We limit the number of interations to 8.
for (var i = 0; Math.abs(value - xVal) > epsilon && i < 8; i++) {
if (value < xVal) {
tMin = t;
t = (t + tMax) / 2;
} else {
tMax = t;
t = (t + tMin) / 2;
}
value = this.getPoint(t).x;
}
return t;
};
/**
* Computes the y coordinate of a point on the curve given its x coordinate.
* @param {number} xVal The x coordinate of the point on the curve.
* @return {number} The y coordinate of the point on the curve.
*/
goog.math.Bezier.prototype.solveYValueFromXValue = function(xVal) {
return this.getPoint(this.solvePositionFromXValue(xVal)).y;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines a Long class for representing a 64-bit two's-complement
* integer value, which faithfully simulates the behavior of a Java "long". This
* implementation is derived from LongLib in GWT.
*
*/
goog.provide('goog.math.Long');
/**
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
* values as *signed* integers. See the from* functions below for more
* convenient ways of constructing Longs.
*
* The internal representation of a long is the two given signed, 32-bit values.
* We use 32-bit pieces because these are the size of integers on which
* Javascript performs bit-operations. For operations like addition and
* multiplication, we split each number into 16-bit pieces, which can easily be
* multiplied within Javascript's floating-point representation without overflow
* or change in sign.
*
* In the algorithms below, we frequently reduce the negative case to the
* positive case by negating the input(s) and then post-processing the result.
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
* a positive number, it overflows back into a negative). Not handling this
* case would often result in infinite recursion.
*
* @param {number} low The low (signed) 32 bits of the long.
* @param {number} high The high (signed) 32 bits of the long.
* @constructor
*/
goog.math.Long = function(low, high) {
/**
* @type {number}
* @private
*/
this.low_ = low | 0; // force into 32 signed bits.
/**
* @type {number}
* @private
*/
this.high_ = high | 0; // force into 32 signed bits.
};
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
// from* methods on which they depend.
/**
* A cache of the Long representations of small integer values.
* @type {!Object}
* @private
*/
goog.math.Long.IntCache_ = {};
/**
* Returns a Long representing the given (32-bit) integer value.
* @param {number} value The 32-bit integer in question.
* @return {!goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromInt = function(value) {
if (-128 <= value && value < 128) {
var cachedObj = goog.math.Long.IntCache_[value];
if (cachedObj) {
return cachedObj;
}
}
var obj = new goog.math.Long(value | 0, value < 0 ? -1 : 0);
if (-128 <= value && value < 128) {
goog.math.Long.IntCache_[value] = obj;
}
return obj;
};
/**
* Returns a Long representing the given value, provided that it is a finite
* number. Otherwise, zero is returned.
* @param {number} value The number in question.
* @return {!goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromNumber = function(value) {
if (isNaN(value) || !isFinite(value)) {
return goog.math.Long.ZERO;
} else if (value <= -goog.math.Long.TWO_PWR_63_DBL_) {
return goog.math.Long.MIN_VALUE;
} else if (value + 1 >= goog.math.Long.TWO_PWR_63_DBL_) {
return goog.math.Long.MAX_VALUE;
} else if (value < 0) {
return goog.math.Long.fromNumber(-value).negate();
} else {
return new goog.math.Long(
(value % goog.math.Long.TWO_PWR_32_DBL_) | 0,
(value / goog.math.Long.TWO_PWR_32_DBL_) | 0);
}
};
/**
* Returns a Long representing the 64-bit integer that comes by concatenating
* the given high and low bits. Each is assumed to use 32 bits.
* @param {number} lowBits The low 32-bits.
* @param {number} highBits The high 32-bits.
* @return {!goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromBits = function(lowBits, highBits) {
return new goog.math.Long(lowBits, highBits);
};
/**
* Returns a Long representation of the given string, written using the given
* radix.
* @param {string} str The textual representation of the Long.
* @param {number=} opt_radix The radix in which the text is written.
* @return {!goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromString = function(str, opt_radix) {
if (str.length == 0) {
throw Error('number format error: empty string');
}
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (str.charAt(0) == '-') {
return goog.math.Long.fromString(str.substring(1), radix).negate();
} else if (str.indexOf('-') >= 0) {
throw Error('number format error: interior "-" character: ' + str);
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 8));
var result = goog.math.Long.ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i);
var value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = goog.math.Long.fromNumber(Math.pow(radix, size));
result = result.multiply(power).add(goog.math.Long.fromNumber(value));
} else {
result = result.multiply(radixToPower);
result = result.add(goog.math.Long.fromNumber(value));
}
}
return result;
};
// NOTE: the compiler should inline these constant values below and then remove
// these variables, so there should be no runtime penalty for these.
/**
* Number used repeated below in calculations. This must appear before the
* first call to any from* function below.
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_16_DBL_ = 1 << 16;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_24_DBL_ = 1 << 24;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_32_DBL_ =
goog.math.Long.TWO_PWR_16_DBL_ * goog.math.Long.TWO_PWR_16_DBL_;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_31_DBL_ =
goog.math.Long.TWO_PWR_32_DBL_ / 2;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_48_DBL_ =
goog.math.Long.TWO_PWR_32_DBL_ * goog.math.Long.TWO_PWR_16_DBL_;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_64_DBL_ =
goog.math.Long.TWO_PWR_32_DBL_ * goog.math.Long.TWO_PWR_32_DBL_;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_63_DBL_ =
goog.math.Long.TWO_PWR_64_DBL_ / 2;
/** @type {!goog.math.Long} */
goog.math.Long.ZERO = goog.math.Long.fromInt(0);
/** @type {!goog.math.Long} */
goog.math.Long.ONE = goog.math.Long.fromInt(1);
/** @type {!goog.math.Long} */
goog.math.Long.NEG_ONE = goog.math.Long.fromInt(-1);
/** @type {!goog.math.Long} */
goog.math.Long.MAX_VALUE =
goog.math.Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
/** @type {!goog.math.Long} */
goog.math.Long.MIN_VALUE = goog.math.Long.fromBits(0, 0x80000000 | 0);
/**
* @type {!goog.math.Long}
* @private
*/
goog.math.Long.TWO_PWR_24_ = goog.math.Long.fromInt(1 << 24);
/** @return {number} The value, assuming it is a 32-bit integer. */
goog.math.Long.prototype.toInt = function() {
return this.low_;
};
/** @return {number} The closest floating-point representation to this value. */
goog.math.Long.prototype.toNumber = function() {
return this.high_ * goog.math.Long.TWO_PWR_32_DBL_ +
this.getLowBitsUnsigned();
};
/**
* @param {number=} opt_radix The radix in which the text should be written.
* @return {string} The textual representation of this value.
* @override
*/
goog.math.Long.prototype.toString = function(opt_radix) {
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (this.isZero()) {
return '0';
}
if (this.isNegative()) {
if (this.equals(goog.math.Long.MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = goog.math.Long.fromNumber(radix);
var div = this.div(radixLong);
var rem = div.multiply(radixLong).subtract(this);
return div.toString(radix) + rem.toInt().toString(radix);
} else {
return '-' + this.negate().toString(radix);
}
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 6));
var rem = this;
var result = '';
while (true) {
var remDiv = rem.div(radixToPower);
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
var digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) {
return digits + result;
} else {
while (digits.length < 6) {
digits = '0' + digits;
}
result = '' + digits + result;
}
}
};
/** @return {number} The high 32-bits as a signed value. */
goog.math.Long.prototype.getHighBits = function() {
return this.high_;
};
/** @return {number} The low 32-bits as a signed value. */
goog.math.Long.prototype.getLowBits = function() {
return this.low_;
};
/** @return {number} The low 32-bits as an unsigned value. */
goog.math.Long.prototype.getLowBitsUnsigned = function() {
return (this.low_ >= 0) ?
this.low_ : goog.math.Long.TWO_PWR_32_DBL_ + this.low_;
};
/**
* @return {number} Returns the number of bits needed to represent the absolute
* value of this Long.
*/
goog.math.Long.prototype.getNumBitsAbs = function() {
if (this.isNegative()) {
if (this.equals(goog.math.Long.MIN_VALUE)) {
return 64;
} else {
return this.negate().getNumBitsAbs();
}
} else {
var val = this.high_ != 0 ? this.high_ : this.low_;
for (var bit = 31; bit > 0; bit--) {
if ((val & (1 << bit)) != 0) {
break;
}
}
return this.high_ != 0 ? bit + 33 : bit + 1;
}
};
/** @return {boolean} Whether this value is zero. */
goog.math.Long.prototype.isZero = function() {
return this.high_ == 0 && this.low_ == 0;
};
/** @return {boolean} Whether this value is negative. */
goog.math.Long.prototype.isNegative = function() {
return this.high_ < 0;
};
/** @return {boolean} Whether this value is odd. */
goog.math.Long.prototype.isOdd = function() {
return (this.low_ & 1) == 1;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long equals the other.
*/
goog.math.Long.prototype.equals = function(other) {
return (this.high_ == other.high_) && (this.low_ == other.low_);
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long does not equal the other.
*/
goog.math.Long.prototype.notEquals = function(other) {
return (this.high_ != other.high_) || (this.low_ != other.low_);
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than the other.
*/
goog.math.Long.prototype.lessThan = function(other) {
return this.compare(other) < 0;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than or equal to the other.
*/
goog.math.Long.prototype.lessThanOrEqual = function(other) {
return this.compare(other) <= 0;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than the other.
*/
goog.math.Long.prototype.greaterThan = function(other) {
return this.compare(other) > 0;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than or equal to the other.
*/
goog.math.Long.prototype.greaterThanOrEqual = function(other) {
return this.compare(other) >= 0;
};
/**
* Compares this Long with the given one.
* @param {goog.math.Long} other Long to compare against.
* @return {number} 0 if they are the same, 1 if the this is greater, and -1
* if the given one is greater.
*/
goog.math.Long.prototype.compare = function(other) {
if (this.equals(other)) {
return 0;
}
var thisNeg = this.isNegative();
var otherNeg = other.isNegative();
if (thisNeg && !otherNeg) {
return -1;
}
if (!thisNeg && otherNeg) {
return 1;
}
// at this point, the signs are the same, so subtraction will not overflow
if (this.subtract(other).isNegative()) {
return -1;
} else {
return 1;
}
};
/** @return {!goog.math.Long} The negation of this value. */
goog.math.Long.prototype.negate = function() {
if (this.equals(goog.math.Long.MIN_VALUE)) {
return goog.math.Long.MIN_VALUE;
} else {
return this.not().add(goog.math.Long.ONE);
}
};
/**
* Returns the sum of this and the given Long.
* @param {goog.math.Long} other Long to add to this one.
* @return {!goog.math.Long} The sum of this and the given Long.
*/
goog.math.Long.prototype.add = function(other) {
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 + b48;
c48 &= 0xFFFF;
return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns the difference of this and the given Long.
* @param {goog.math.Long} other Long to subtract from this.
* @return {!goog.math.Long} The difference of this and the given Long.
*/
goog.math.Long.prototype.subtract = function(other) {
return this.add(other.negate());
};
/**
* Returns the product of this and the given long.
* @param {goog.math.Long} other Long to multiply with this.
* @return {!goog.math.Long} The product of this and the other.
*/
goog.math.Long.prototype.multiply = function(other) {
if (this.isZero()) {
return goog.math.Long.ZERO;
} else if (other.isZero()) {
return goog.math.Long.ZERO;
}
if (this.equals(goog.math.Long.MIN_VALUE)) {
return other.isOdd() ? goog.math.Long.MIN_VALUE : goog.math.Long.ZERO;
} else if (other.equals(goog.math.Long.MIN_VALUE)) {
return this.isOdd() ? goog.math.Long.MIN_VALUE : goog.math.Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().multiply(other.negate());
} else {
return this.negate().multiply(other).negate();
}
} else if (other.isNegative()) {
return this.multiply(other.negate()).negate();
}
// If both longs are small, use float multiplication
if (this.lessThan(goog.math.Long.TWO_PWR_24_) &&
other.lessThan(goog.math.Long.TWO_PWR_24_)) {
return goog.math.Long.fromNumber(this.toNumber() * other.toNumber());
}
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xFFFF;
return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns this Long divided by the given one.
* @param {goog.math.Long} other Long by which to divide.
* @return {!goog.math.Long} This Long divided by the given one.
*/
goog.math.Long.prototype.div = function(other) {
if (other.isZero()) {
throw Error('division by zero');
} else if (this.isZero()) {
return goog.math.Long.ZERO;
}
if (this.equals(goog.math.Long.MIN_VALUE)) {
if (other.equals(goog.math.Long.ONE) ||
other.equals(goog.math.Long.NEG_ONE)) {
return goog.math.Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
} else if (other.equals(goog.math.Long.MIN_VALUE)) {
return goog.math.Long.ONE;
} else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shiftRight(1);
var approx = halfThis.div(other).shiftLeft(1);
if (approx.equals(goog.math.Long.ZERO)) {
return other.isNegative() ? goog.math.Long.ONE : goog.math.Long.NEG_ONE;
} else {
var rem = this.subtract(other.multiply(approx));
var result = approx.add(rem.div(other));
return result;
}
}
} else if (other.equals(goog.math.Long.MIN_VALUE)) {
return goog.math.Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().div(other.negate());
} else {
return this.negate().div(other).negate();
}
} else if (other.isNegative()) {
return this.div(other.negate()).negate();
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
var res = goog.math.Long.ZERO;
var rem = this;
while (rem.greaterThanOrEqual(other)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
var approxRes = goog.math.Long.fromNumber(approx);
var approxRem = approxRes.multiply(other);
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
approx -= delta;
approxRes = goog.math.Long.fromNumber(approx);
approxRem = approxRes.multiply(other);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero()) {
approxRes = goog.math.Long.ONE;
}
res = res.add(approxRes);
rem = rem.subtract(approxRem);
}
return res;
};
/**
* Returns this Long modulo the given one.
* @param {goog.math.Long} other Long by which to mod.
* @return {!goog.math.Long} This Long modulo the given one.
*/
goog.math.Long.prototype.modulo = function(other) {
return this.subtract(this.div(other).multiply(other));
};
/** @return {!goog.math.Long} The bitwise-NOT of this value. */
goog.math.Long.prototype.not = function() {
return goog.math.Long.fromBits(~this.low_, ~this.high_);
};
/**
* Returns the bitwise-AND of this Long and the given one.
* @param {goog.math.Long} other The Long with which to AND.
* @return {!goog.math.Long} The bitwise-AND of this and the other.
*/
goog.math.Long.prototype.and = function(other) {
return goog.math.Long.fromBits(this.low_ & other.low_,
this.high_ & other.high_);
};
/**
* Returns the bitwise-OR of this Long and the given one.
* @param {goog.math.Long} other The Long with which to OR.
* @return {!goog.math.Long} The bitwise-OR of this and the other.
*/
goog.math.Long.prototype.or = function(other) {
return goog.math.Long.fromBits(this.low_ | other.low_,
this.high_ | other.high_);
};
/**
* Returns the bitwise-XOR of this Long and the given one.
* @param {goog.math.Long} other The Long with which to XOR.
* @return {!goog.math.Long} The bitwise-XOR of this and the other.
*/
goog.math.Long.prototype.xor = function(other) {
return goog.math.Long.fromBits(this.low_ ^ other.low_,
this.high_ ^ other.high_);
};
/**
* Returns this Long with bits shifted to the left by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Long} This shifted to the left by the given amount.
*/
goog.math.Long.prototype.shiftLeft = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var low = this.low_;
if (numBits < 32) {
var high = this.high_;
return goog.math.Long.fromBits(
low << numBits,
(high << numBits) | (low >>> (32 - numBits)));
} else {
return goog.math.Long.fromBits(0, low << (numBits - 32));
}
}
};
/**
* Returns this Long with bits shifted to the right by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Long} This shifted to the right by the given amount.
*/
goog.math.Long.prototype.shiftRight = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return goog.math.Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >> numBits);
} else {
return goog.math.Long.fromBits(
high >> (numBits - 32),
high >= 0 ? 0 : -1);
}
}
};
/**
* Returns this Long with bits shifted to the right by the given amount, with
* the new top bits matching the current sign bit.
* @param {number} numBits The number of bits by which to shift.
* @return {!goog.math.Long} This shifted to the right by the given amount, with
* zeros placed into the new leading bits.
*/
goog.math.Long.prototype.shiftRightUnsigned = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return goog.math.Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >>> numBits);
} else if (numBits == 32) {
return goog.math.Long.fromBits(high, 0);
} else {
return goog.math.Long.fromBits(high >>> (numBits - 32), 0);
}
}
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Additional mathematical functions.
*/
goog.provide('goog.math');
goog.require('goog.array');
goog.require('goog.asserts');
/**
* Returns a random integer greater than or equal to 0 and less than {@code a}.
* @param {number} a The upper bound for the random integer (exclusive).
* @return {number} A random integer N such that 0 <= N < a.
*/
goog.math.randomInt = function(a) {
return Math.floor(Math.random() * a);
};
/**
* Returns a random number greater than or equal to {@code a} and less than
* {@code b}.
* @param {number} a The lower bound for the random number (inclusive).
* @param {number} b The upper bound for the random number (exclusive).
* @return {number} A random number N such that a <= N < b.
*/
goog.math.uniformRandom = function(a, b) {
return a + Math.random() * (b - a);
};
/**
* Takes a number and clamps it to within the provided bounds.
* @param {number} value The input number.
* @param {number} min The minimum value to return.
* @param {number} max The maximum value to return.
* @return {number} The input number if it is within bounds, or the nearest
* number within the bounds.
*/
goog.math.clamp = function(value, min, max) {
return Math.min(Math.max(value, min), max);
};
/**
* The % operator in JavaScript returns the remainder of a / b, but differs from
* some other languages in that the result will have the same sign as the
* dividend. For example, -1 % 8 == -1, whereas in some other languages
* (such as Python) the result would be 7. This function emulates the more
* correct modulo behavior, which is useful for certain applications such as
* calculating an offset index in a circular list.
*
* @param {number} a The dividend.
* @param {number} b The divisor.
* @return {number} a % b where the result is between 0 and b (either 0 <= x < b
* or b < x <= 0, depending on the sign of b).
*/
goog.math.modulo = function(a, b) {
var r = a % b;
// If r and b differ in sign, add b to wrap the result to the correct sign.
return (r * b < 0) ? r + b : r;
};
/**
* Performs linear interpolation between values a and b. Returns the value
* between a and b proportional to x (when x is between 0 and 1. When x is
* outside this range, the return value is a linear extrapolation).
* @param {number} a A number.
* @param {number} b A number.
* @param {number} x The proportion between a and b.
* @return {number} The interpolated value between a and b.
*/
goog.math.lerp = function(a, b, x) {
return a + x * (b - a);
};
/**
* Tests whether the two values are equal to each other, within a certain
* tolerance to adjust for floating pount errors.
* @param {number} a A number.
* @param {number} b A number.
* @param {number=} opt_tolerance Optional tolerance range. Defaults
* to 0.000001. If specified, should be greater than 0.
* @return {boolean} Whether {@code a} and {@code b} are nearly equal.
*/
goog.math.nearlyEquals = function(a, b, opt_tolerance) {
return Math.abs(a - b) <= (opt_tolerance || 0.000001);
};
/**
* Standardizes an angle to be in range [0-360). Negative angles become
* positive, and values greater than 360 are returned modulo 360.
* @param {number} angle Angle in degrees.
* @return {number} Standardized angle.
*/
goog.math.standardAngle = function(angle) {
return goog.math.modulo(angle, 360);
};
/**
* Converts degrees to radians.
* @param {number} angleDegrees Angle in degrees.
* @return {number} Angle in radians.
*/
goog.math.toRadians = function(angleDegrees) {
return angleDegrees * Math.PI / 180;
};
/**
* Converts radians to degrees.
* @param {number} angleRadians Angle in radians.
* @return {number} Angle in degrees.
*/
goog.math.toDegrees = function(angleRadians) {
return angleRadians * 180 / Math.PI;
};
/**
* For a given angle and radius, finds the X portion of the offset.
* @param {number} degrees Angle in degrees (zero points in +X direction).
* @param {number} radius Radius.
* @return {number} The x-distance for the angle and radius.
*/
goog.math.angleDx = function(degrees, radius) {
return radius * Math.cos(goog.math.toRadians(degrees));
};
/**
* For a given angle and radius, finds the Y portion of the offset.
* @param {number} degrees Angle in degrees (zero points in +X direction).
* @param {number} radius Radius.
* @return {number} The y-distance for the angle and radius.
*/
goog.math.angleDy = function(degrees, radius) {
return radius * Math.sin(goog.math.toRadians(degrees));
};
/**
* Computes the angle between two points (x1,y1) and (x2,y2).
* Angle zero points in the +X direction, 90 degrees points in the +Y
* direction (down) and from there we grow clockwise towards 360 degrees.
* @param {number} x1 x of first point.
* @param {number} y1 y of first point.
* @param {number} x2 x of second point.
* @param {number} y2 y of second point.
* @return {number} Standardized angle in degrees of the vector from
* x1,y1 to x2,y2.
*/
goog.math.angle = function(x1, y1, x2, y2) {
return goog.math.standardAngle(goog.math.toDegrees(Math.atan2(y2 - y1,
x2 - x1)));
};
/**
* Computes the difference between startAngle and endAngle (angles in degrees).
* @param {number} startAngle Start angle in degrees.
* @param {number} endAngle End angle in degrees.
* @return {number} The number of degrees that when added to
* startAngle will result in endAngle. Positive numbers mean that the
* direction is clockwise. Negative numbers indicate a counter-clockwise
* direction.
* The shortest route (clockwise vs counter-clockwise) between the angles
* is used.
* When the difference is 180 degrees, the function returns 180 (not -180)
* angleDifference(30, 40) is 10, and angleDifference(40, 30) is -10.
* angleDifference(350, 10) is 20, and angleDifference(10, 350) is -20.
*/
goog.math.angleDifference = function(startAngle, endAngle) {
var d = goog.math.standardAngle(endAngle) -
goog.math.standardAngle(startAngle);
if (d > 180) {
d = d - 360;
} else if (d <= -180) {
d = 360 + d;
}
return d;
};
/**
* Returns the sign of a number as per the "sign" or "signum" function.
* @param {number} x The number to take the sign of.
* @return {number} -1 when negative, 1 when positive, 0 when 0.
*/
goog.math.sign = function(x) {
return x == 0 ? 0 : (x < 0 ? -1 : 1);
};
/**
* JavaScript implementation of Longest Common Subsequence problem.
* http://en.wikipedia.org/wiki/Longest_common_subsequence
*
* Returns the longest possible array that is subarray of both of given arrays.
*
* @param {Array.<Object>} array1 First array of objects.
* @param {Array.<Object>} array2 Second array of objects.
* @param {Function=} opt_compareFn Function that acts as a custom comparator
* for the array ojects. Function should return true if objects are equal,
* otherwise false.
* @param {Function=} opt_collectorFn Function used to decide what to return
* as a result subsequence. It accepts 2 arguments: index of common element
* in the first array and index in the second. The default function returns
* element from the first array.
* @return {Array.<Object>} A list of objects that are common to both arrays
* such that there is no common subsequence with size greater than the
* length of the list.
*/
goog.math.longestCommonSubsequence = function(
array1, array2, opt_compareFn, opt_collectorFn) {
var compare = opt_compareFn || function(a, b) {
return a == b;
};
var collect = opt_collectorFn || function(i1, i2) {
return array1[i1];
};
var length1 = array1.length;
var length2 = array2.length;
var arr = [];
for (var i = 0; i < length1 + 1; i++) {
arr[i] = [];
arr[i][0] = 0;
}
for (var j = 0; j < length2 + 1; j++) {
arr[0][j] = 0;
}
for (i = 1; i <= length1; i++) {
for (j = 1; j <= length1; j++) {
if (compare(array1[i - 1], array2[j - 1])) {
arr[i][j] = arr[i - 1][j - 1] + 1;
} else {
arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]);
}
}
}
// Backtracking
var result = [];
var i = length1, j = length2;
while (i > 0 && j > 0) {
if (compare(array1[i - 1], array2[j - 1])) {
result.unshift(collect(i - 1, j - 1));
i--;
j--;
} else {
if (arr[i - 1][j] > arr[i][j - 1]) {
i--;
} else {
j--;
}
}
}
return result;
};
/**
* Returns the sum of the arguments.
* @param {...number} var_args Numbers to add.
* @return {number} The sum of the arguments (0 if no arguments were provided,
* {@code NaN} if any of the arguments is not a valid number).
*/
goog.math.sum = function(var_args) {
return /** @type {number} */ (goog.array.reduce(arguments,
function(sum, value) {
return sum + value;
}, 0));
};
/**
* Returns the arithmetic mean of the arguments.
* @param {...number} var_args Numbers to average.
* @return {number} The average of the arguments ({@code NaN} if no arguments
* were provided or any of the arguments is not a valid number).
*/
goog.math.average = function(var_args) {
return goog.math.sum.apply(null, arguments) / arguments.length;
};
/**
* Returns the sample standard deviation of the arguments. For a definition of
* sample standard deviation, see e.g.
* http://en.wikipedia.org/wiki/Standard_deviation
* @param {...number} var_args Number samples to analyze.
* @return {number} The sample standard deviation of the arguments (0 if fewer
* than two samples were provided, or {@code NaN} if any of the samples is
* not a valid number).
*/
goog.math.standardDeviation = function(var_args) {
var sampleSize = arguments.length;
if (sampleSize < 2) {
return 0;
}
var mean = goog.math.average.apply(null, arguments);
var variance = goog.math.sum.apply(null, goog.array.map(arguments,
function(val) {
return Math.pow(val - mean, 2);
})) / (sampleSize - 1);
return Math.sqrt(variance);
};
/**
* Returns whether the supplied number represents an integer, i.e. that is has
* no fractional component. No range-checking is performed on the number.
* @param {number} num The number to test.
* @return {boolean} Whether {@code num} is an integer.
*/
goog.math.isInt = function(num) {
return isFinite(num) && num % 1 == 0;
};
/**
* Returns whether the supplied number is finite and not NaN.
* @param {number} num The number to test.
* @return {boolean} Whether {@code num} is a finite number.
*/
goog.math.isFiniteNumber = function(num) {
return isFinite(num) && !isNaN(num);
};
/**
* A tweaked variant of {@code Math.floor} which tolerates if the passed number
* is infinitesimally smaller than the closest integer. It often happens with
* the results of floating point calculations because of the finite precision
* of the intermediate results. For example {@code Math.floor(Math.log(1000) /
* Math.LN10) == 2}, not 3 as one would expect.
* @param {number} num A number.
* @param {number=} opt_epsilon An infinitesimally small positive number, the
* rounding error to tolerate.
* @return {number} The largest integer less than or equal to {@code num}.
*/
goog.math.safeFloor = function(num, opt_epsilon) {
goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0);
return Math.floor(num + (opt_epsilon || 2e-15));
};
/**
* A tweaked variant of {@code Math.ceil}. See {@code goog.math.safeFloor} for
* details.
* @param {number} num A number.
* @param {number=} opt_epsilon An infinitesimally small positive number, the
* rounding error to tolerate.
* @return {number} The smallest integer greater than or equal to {@code num}.
*/
goog.math.safeCeil = function(num, opt_epsilon) {
goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0);
return Math.ceil(num - (opt_epsilon || 2e-15));
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utility class to manage the mathematics behind computing an
* exponential backoff model. Given an initial backoff value and a maximum
* backoff value, every call to backoff() will double the value until maximum
* backoff value is reached.
*
*/
goog.provide('goog.math.ExponentialBackoff');
goog.require('goog.asserts');
/**
* @constructor
*
* @param {number} initialValue The initial backoff value.
* @param {number} maxValue The maximum backoff value.
*/
goog.math.ExponentialBackoff = function(initialValue, maxValue) {
goog.asserts.assert(initialValue > 0,
'Initial value must be greater than zero.');
goog.asserts.assert(maxValue >= initialValue,
'Max value should be at least as large as initial value.');
/**
* @type {number}
* @private
*/
this.initialValue_ = initialValue;
/**
* @type {number}
* @private
*/
this.maxValue_ = maxValue;
/**
* The current backoff value.
* @type {number}
* @private
*/
this.currValue_ = initialValue;
};
/**
* The number of backoffs that have happened.
* @type {number}
* @private
*/
goog.math.ExponentialBackoff.prototype.currCount_ = 0;
/**
* Resets the backoff value to its initial value.
*/
goog.math.ExponentialBackoff.prototype.reset = function() {
this.currValue_ = this.initialValue_;
this.currCount_ = 0;
};
/**
* @return {number} The current backoff value.
*/
goog.math.ExponentialBackoff.prototype.getValue = function() {
return this.currValue_;
};
/**
* @return {number} The number of times this class has backed off.
*/
goog.math.ExponentialBackoff.prototype.getBackoffCount = function() {
return this.currCount_;
};
/**
* Initiates a backoff.
*/
goog.math.ExponentialBackoff.prototype.backoff = function() {
this.currValue_ = Math.min(this.maxValue_, this.currValue_ * 2);
this.currCount_++;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The Tridiagonal matrix algorithm solver solves a special
* version of a sparse linear system Ax = b where A is tridiagonal.
*
* See http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
*
*/
goog.provide('goog.math.tdma');
/**
* Solves a linear system where the matrix is square tri-diagonal. That is,
* given a system of equations:
*
* A * result = vecRight,
*
* this class computes result = inv(A) * vecRight, where A has the special form
* of a tri-diagonal matrix:
*
* |dia(0) sup(0) 0 0 ... 0|
* |sub(0) dia(1) sup(1) 0 ... 0|
* A =| ... |
* |0 ... 0 sub(n-2) dia(n-1) sup(n-1)|
* |0 ... 0 0 sub(n-1) dia(n)|
*
* @param {!Array.<number>} subDiag The sub diagonal of the matrix.
* @param {!Array.<number>} mainDiag The main diagonal of the matrix.
* @param {!Array.<number>} supDiag The super diagonal of the matrix.
* @param {!Array.<number>} vecRight The right vector of the system
* of equations.
* @param {Array.<number>=} opt_result The optional array to store the result.
* @return {!Array.<number>} The vector that is the solution to the system.
*/
goog.math.tdma.solve = function(
subDiag, mainDiag, supDiag, vecRight, opt_result) {
// Make a local copy of the main diagonal and the right vector.
mainDiag = mainDiag.slice();
vecRight = vecRight.slice();
// The dimension of the matrix.
var nDim = mainDiag.length;
// Construct a modified linear system of equations with the same solution
// as the input one.
for (var i = 1; i < nDim; ++i) {
var m = subDiag[i - 1] / mainDiag[i - 1];
mainDiag[i] = mainDiag[i] - m * supDiag[i - 1];
vecRight[i] = vecRight[i] - m * vecRight[i - 1];
}
// Solve the new system of equations by simple back-substitution.
var result = opt_result || new Array(vecRight.length);
result[nDim - 1] = vecRight[nDim - 1] / mainDiag[nDim - 1];
for (i = nDim - 2; i >= 0; --i) {
result[i] = (vecRight[i] - supDiag[i] * result[i + 1]) / mainDiag[i];
}
return result;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines a 2-element vector class that can be used for
* coordinate math, useful for animation systems and point manipulation.
*
* Vec2 objects inherit from goog.math.Coordinate and may be used wherever a
* Coordinate is required. Where appropriate, Vec2 functions accept both Vec2
* and Coordinate objects as input.
*
* @author brenneman@google.com (Shawn Brenneman)
*/
goog.provide('goog.math.Vec2');
goog.require('goog.math');
goog.require('goog.math.Coordinate');
/**
* Class for a two-dimensional vector object and assorted functions useful for
* manipulating points.
*
* @param {number} x The x coordinate for the vector.
* @param {number} y The y coordinate for the vector.
* @constructor
* @extends {goog.math.Coordinate}
*/
goog.math.Vec2 = function(x, y) {
/**
* X-value
* @type {number}
*/
this.x = x;
/**
* Y-value
* @type {number}
*/
this.y = y;
};
goog.inherits(goog.math.Vec2, goog.math.Coordinate);
/**
* @return {!goog.math.Vec2} A random unit-length vector.
*/
goog.math.Vec2.randomUnit = function() {
var angle = Math.random() * Math.PI * 2;
return new goog.math.Vec2(Math.cos(angle), Math.sin(angle));
};
/**
* @return {!goog.math.Vec2} A random vector inside the unit-disc.
*/
goog.math.Vec2.random = function() {
var mag = Math.sqrt(Math.random());
var angle = Math.random() * Math.PI * 2;
return new goog.math.Vec2(Math.cos(angle) * mag, Math.sin(angle) * mag);
};
/**
* Returns a new Vec2 object from a given coordinate.
* @param {!goog.math.Coordinate} a The coordinate.
* @return {!goog.math.Vec2} A new vector object.
*/
goog.math.Vec2.fromCoordinate = function(a) {
return new goog.math.Vec2(a.x, a.y);
};
/**
* @return {!goog.math.Vec2} A new vector with the same coordinates as this one.
* @override
*/
goog.math.Vec2.prototype.clone = function() {
return new goog.math.Vec2(this.x, this.y);
};
/**
* Returns the magnitude of the vector measured from the origin.
* @return {number} The length of the vector.
*/
goog.math.Vec2.prototype.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/**
* Returns the squared magnitude of the vector measured from the origin.
* NOTE(brenneman): Leaving out the square root is not a significant
* optimization in JavaScript.
* @return {number} The length of the vector, squared.
*/
goog.math.Vec2.prototype.squaredMagnitude = function() {
return this.x * this.x + this.y * this.y;
};
/**
* @return {!goog.math.Vec2} This coordinate after scaling.
* @override
*/
goog.math.Vec2.prototype.scale =
/** @type {function(number, number=):!goog.math.Vec2} */
(goog.math.Coordinate.prototype.scale);
/**
* Reverses the sign of the vector. Equivalent to scaling the vector by -1.
* @return {!goog.math.Vec2} The inverted vector.
*/
goog.math.Vec2.prototype.invert = function() {
this.x = -this.x;
this.y = -this.y;
return this;
};
/**
* Normalizes the current vector to have a magnitude of 1.
* @return {!goog.math.Vec2} The normalized vector.
*/
goog.math.Vec2.prototype.normalize = function() {
return this.scale(1 / this.magnitude());
};
/**
* Adds another vector to this vector in-place.
* @param {!goog.math.Coordinate} b The vector to add.
* @return {!goog.math.Vec2} This vector with {@code b} added.
*/
goog.math.Vec2.prototype.add = function(b) {
this.x += b.x;
this.y += b.y;
return this;
};
/**
* Subtracts another vector from this vector in-place.
* @param {!goog.math.Coordinate} b The vector to subtract.
* @return {!goog.math.Vec2} This vector with {@code b} subtracted.
*/
goog.math.Vec2.prototype.subtract = function(b) {
this.x -= b.x;
this.y -= b.y;
return this;
};
/**
* Rotates this vector in-place by a given angle, specified in radians.
* @param {number} angle The angle, in radians.
* @return {!goog.math.Vec2} This vector rotated {@code angle} radians.
*/
goog.math.Vec2.prototype.rotate = function(angle) {
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var newX = this.x * cos - this.y * sin;
var newY = this.y * cos + this.x * sin;
this.x = newX;
this.y = newY;
return this;
};
/**
* Rotates a vector by a given angle, specified in radians, relative to a given
* axis rotation point. The returned vector is a newly created instance - no
* in-place changes are done.
* @param {!goog.math.Vec2} v A vector.
* @param {!goog.math.Vec2} axisPoint The rotation axis point.
* @param {number} angle The angle, in radians.
* @return {!goog.math.Vec2} The rotated vector in a newly created instance.
*/
goog.math.Vec2.rotateAroundPoint = function(v, axisPoint, angle) {
var res = v.clone();
return res.subtract(axisPoint).rotate(angle).add(axisPoint);
};
/**
* Compares this vector with another for equality.
* @param {!goog.math.Vec2} b The other vector.
* @return {boolean} Whether this vector has the same x and y as the given
* vector.
*/
goog.math.Vec2.prototype.equals = function(b) {
return this == b || !!b && this.x == b.x && this.y == b.y;
};
/**
* Returns the distance between two vectors.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {number} The distance.
*/
goog.math.Vec2.distance = goog.math.Coordinate.distance;
/**
* Returns the squared distance between two vectors.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {number} The squared distance.
*/
goog.math.Vec2.squaredDistance = goog.math.Coordinate.squaredDistance;
/**
* Compares vectors for equality.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {boolean} Whether the vectors have the same x and y coordinates.
*/
goog.math.Vec2.equals = goog.math.Coordinate.equals;
/**
* Returns the sum of two vectors as a new Vec2.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {!goog.math.Vec2} The sum vector.
*/
goog.math.Vec2.sum = function(a, b) {
return new goog.math.Vec2(a.x + b.x, a.y + b.y);
};
/**
* Returns the difference between two vectors as a new Vec2.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {!goog.math.Vec2} The difference vector.
*/
goog.math.Vec2.difference = function(a, b) {
return new goog.math.Vec2(a.x - b.x, a.y - b.y);
};
/**
* Returns the dot-product of two vectors.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {number} The dot-product of the two vectors.
*/
goog.math.Vec2.dot = function(a, b) {
return a.x * b.x + a.y * b.y;
};
/**
* Returns a new Vec2 that is the linear interpolant between vectors a and b at
* scale-value x.
* @param {!goog.math.Coordinate} a Vector a.
* @param {!goog.math.Coordinate} b Vector b.
* @param {number} x The proportion between a and b.
* @return {!goog.math.Vec2} The interpolated vector.
*/
goog.math.Vec2.lerp = function(a, b, x) {
return new goog.math.Vec2(goog.math.lerp(a.x, b.x, x),
goog.math.lerp(a.y, b.y, x));
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A utility class for representing a numeric range.
*/
goog.provide('goog.math.Range');
/**
* A number range.
* @param {number} a One end of the range.
* @param {number} b The other end of the range.
* @constructor
*/
goog.math.Range = function(a, b) {
/**
* The lowest value in the range.
* @type {number}
*/
this.start = a < b ? a : b;
/**
* The highest value in the range.
* @type {number}
*/
this.end = a < b ? b : a;
};
/**
* @return {!goog.math.Range} A clone of this Range.
*/
goog.math.Range.prototype.clone = function() {
return new goog.math.Range(this.start, this.end);
};
if (goog.DEBUG) {
/**
* Returns a string representing the range.
* @return {string} In the form [-3.5, 8.13].
* @override
*/
goog.math.Range.prototype.toString = function() {
return '[' + this.start + ', ' + this.end + ']';
};
}
/**
* Compares ranges for equality.
* @param {goog.math.Range} a A Range.
* @param {goog.math.Range} b A Range.
* @return {boolean} True iff both the starts and the ends of the ranges are
* equal, or if both ranges are null.
*/
goog.math.Range.equals = function(a, b) {
if (a == b) {
return true;
}
if (!a || !b) {
return false;
}
return a.start == b.start && a.end == b.end;
};
/**
* Given two ranges on the same dimension, this method returns the intersection
* of those ranges.
* @param {goog.math.Range} a A Range.
* @param {goog.math.Range} b A Range.
* @return {goog.math.Range} A new Range representing the intersection of two
* ranges, or null if there is no intersection. Ranges are assumed to
* include their end points, and the intersection can be a point.
*/
goog.math.Range.intersection = function(a, b) {
var c0 = Math.max(a.start, b.start);
var c1 = Math.min(a.end, b.end);
return (c0 <= c1) ? new goog.math.Range(c0, c1) : null;
};
/**
* Given two ranges on the same dimension, determines whether they intersect.
* @param {goog.math.Range} a A Range.
* @param {goog.math.Range} b A Range.
* @return {boolean} Whether they intersect.
*/
goog.math.Range.hasIntersection = function(a, b) {
return Math.max(a.start, b.start) <= Math.min(a.end, b.end);
};
/**
* Given two ranges on the same dimension, this returns a range that covers
* both ranges.
* @param {goog.math.Range} a A Range.
* @param {goog.math.Range} b A Range.
* @return {!goog.math.Range} A new Range representing the bounding
* range.
*/
goog.math.Range.boundingRange = function(a, b) {
return new goog.math.Range(Math.min(a.start, b.start),
Math.max(a.end, b.end));
};
/**
* Given two ranges, returns true if the first range completely overlaps the
* second.
* @param {goog.math.Range} a The first Range.
* @param {goog.math.Range} b The second Range.
* @return {boolean} True if b is contained inside a, false otherwise.
*/
goog.math.Range.contains = function(a, b) {
return a.start <= b.start && a.end >= b.end;
};
/**
* Given a range and a point, returns true if the range contains the point.
* @param {goog.math.Range} range The range.
* @param {number} p The point.
* @return {boolean} True if p is contained inside range, false otherwise.
*/
goog.math.Range.containsPoint = function(range, p) {
return range.start <= p && range.end >= p;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A one dimensional monotone cubic spline interpolator.
*
* See http://en.wikipedia.org/wiki/Monotone_cubic_interpolation.
*
*/
goog.provide('goog.math.interpolator.Pchip1');
goog.require('goog.math');
goog.require('goog.math.interpolator.Spline1');
/**
* A one dimensional monotone cubic spline interpolator.
* @extends {goog.math.interpolator.Spline1}
* @constructor
*/
goog.math.interpolator.Pchip1 = function() {
goog.base(this);
};
goog.inherits(goog.math.interpolator.Pchip1, goog.math.interpolator.Spline1);
/** @override */
goog.math.interpolator.Pchip1.prototype.computeDerivatives = function(
dx, slope) {
var len = dx.length;
var deriv = new Array(len + 1);
for (var i = 1; i < len; ++i) {
if (goog.math.sign(slope[i - 1]) * goog.math.sign(slope[i]) <= 0) {
deriv[i] = 0;
} else {
var w1 = 2 * dx[i] + dx[i - 1];
var w2 = dx[i] + 2 * dx[i - 1];
deriv[i] = (w1 + w2) / (w1 / slope[i - 1] + w2 / slope[i]);
}
}
deriv[0] = this.computeDerivativeAtBoundary_(
dx[0], dx[1], slope[0], slope[1]);
deriv[len] = this.computeDerivativeAtBoundary_(
dx[len - 1], dx[len - 2], slope[len - 1], slope[len - 2]);
return deriv;
};
/**
* Computes the derivative of a data point at a boundary.
* @param {number} dx0 The spacing of the 1st data point.
* @param {number} dx1 The spacing of the 2nd data point.
* @param {number} slope0 The slope of the 1st data point.
* @param {number} slope1 The slope of the 2nd data point.
* @return {number} The derivative at the 1st data point.
* @private
*/
goog.math.interpolator.Pchip1.prototype.computeDerivativeAtBoundary_ = function(
dx0, dx1, slope0, slope1) {
var deriv = ((2 * dx0 + dx1) * slope0 - dx0 * slope1) / (dx0 + dx1);
if (goog.math.sign(deriv) != goog.math.sign(slope0)) {
deriv = 0;
} else if (goog.math.sign(slope0) != goog.math.sign(slope1) &&
Math.abs(deriv) > Math.abs(3 * slope0)) {
deriv = 3 * slope0;
}
return deriv;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The base interface for one-dimensional data interpolation.
*
*/
goog.provide('goog.math.interpolator.Interpolator1');
/**
* An interface for one dimensional data interpolation.
* @interface
*/
goog.math.interpolator.Interpolator1 = function() {
};
/**
* Sets the data to be interpolated. Note that the data points are expected
* to be sorted according to their abscissa values and not have duplicate
* values. E.g. calling setData([0, 0, 1], [1, 1, 3]) may give undefined
* results, the correct call should be setData([0, 1], [1, 3]).
* Calling setData multiple times does not merge the data samples. The last
* call to setData is the one used when computing the interpolation.
* @param {!Array.<number>} x The abscissa of the data points.
* @param {!Array.<number>} y The ordinate of the data points.
*/
goog.math.interpolator.Interpolator1.prototype.setData;
/**
* Computes the interpolated value at abscissa x. If x is outside the range
* of the data points passed in setData, the value is extrapolated.
* @param {number} x The abscissa to sample at.
* @return {number} The interpolated value at abscissa x.
*/
goog.math.interpolator.Interpolator1.prototype.interpolate;
/**
* Computes the inverse interpolator. That is, it returns invInterp s.t.
* this.interpolate(invInterp.interpolate(t))) = t. Note that the inverse
* interpolator is only well defined if the data being interpolated is
* 'invertible', i.e. it represents a bijective function.
* In addition, the returned interpolator is only guaranteed to give the exact
* inverse at the input data passed in getData.
* If 'this' has no data, the returned Interpolator will be empty as well.
* @return {!goog.math.interpolator.Interpolator1} The inverse interpolator.
*/
goog.math.interpolator.Interpolator1.prototype.getInverse;
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A one dimensional cubic spline interpolator with not-a-knot
* boundary conditions.
*
* See http://en.wikipedia.org/wiki/Spline_interpolation.
*
*/
goog.provide('goog.math.interpolator.Spline1');
goog.require('goog.array');
goog.require('goog.math');
goog.require('goog.math.interpolator.Interpolator1');
goog.require('goog.math.tdma');
/**
* A one dimensional cubic spline interpolator with natural boundary conditions.
* @implements {goog.math.interpolator.Interpolator1}
* @constructor
*/
goog.math.interpolator.Spline1 = function() {
/**
* The abscissa of the data points.
* @type {!Array.<number>}
* @private
*/
this.x_ = [];
/**
* The spline interval coefficients.
* Note that, in general, the length of coeffs and x is not the same.
* @type {!Array.<!Array.<number>>}
* @private
*/
this.coeffs_ = [[0, 0, 0, Number.NaN]];
};
/** @override */
goog.math.interpolator.Spline1.prototype.setData = function(x, y) {
goog.asserts.assert(x.length == y.length,
'input arrays to setData should have the same length');
if (x.length > 0) {
this.coeffs_ = this.computeSplineCoeffs_(x, y);
this.x_ = x.slice();
} else {
this.coeffs_ = [[0, 0, 0, Number.NaN]];
this.x_ = [];
}
};
/** @override */
goog.math.interpolator.Spline1.prototype.interpolate = function(x) {
var pos = goog.array.binarySearch(this.x_, x);
if (pos < 0) {
pos = -pos - 2;
}
pos = goog.math.clamp(pos, 0, this.coeffs_.length - 1);
var d = x - this.x_[pos];
var d2 = d * d;
var d3 = d2 * d;
var coeffs = this.coeffs_[pos];
return coeffs[0] * d3 + coeffs[1] * d2 + coeffs[2] * d + coeffs[3];
};
/**
* Solve for the spline coefficients such that the spline precisely interpolates
* the data points.
* @param {Array.<number>} x The abscissa of the spline data points.
* @param {Array.<number>} y The ordinate of the spline data points.
* @return {!Array.<!Array.<number>>} The spline interval coefficients.
* @private
*/
goog.math.interpolator.Spline1.prototype.computeSplineCoeffs_ = function(x, y) {
var nIntervals = x.length - 1;
var dx = new Array(nIntervals);
var delta = new Array(nIntervals);
for (var i = 0; i < nIntervals; ++i) {
dx[i] = x[i + 1] - x[i];
delta[i] = (y[i + 1] - y[i]) / dx[i];
}
// Compute the spline coefficients from the 1st order derivatives.
var coeffs = [];
if (nIntervals == 0) {
// Nearest neighbor interpolation.
coeffs[0] = [0, 0, 0, y[0]];
} else if (nIntervals == 1) {
// Straight line interpolation.
coeffs[0] = [0, 0, delta[0], y[0]];
} else if (nIntervals == 2) {
// Parabola interpolation.
var c3 = 0;
var c2 = (delta[1] - delta[0]) / (dx[0] + dx[1]);
var c1 = delta[0] - c2 * dx[0];
var c0 = y[0];
coeffs[0] = [c3, c2, c1, c0];
} else {
// General Spline interpolation. Compute the 1st order derivatives from
// the Spline equations.
var deriv = this.computeDerivatives(dx, delta);
for (var i = 0; i < nIntervals; ++i) {
var c3 = (deriv[i] - 2 * delta[i] + deriv[i + 1]) / (dx[i] * dx[i]);
var c2 = (3 * delta[i] - 2 * deriv[i] - deriv[i + 1]) / dx[i];
var c1 = deriv[i];
var c0 = y[i];
coeffs[i] = [c3, c2, c1, c0];
}
}
return coeffs;
};
/**
* Computes the derivative at each point of the spline such that
* the curve is C2. It uses not-a-knot boundary conditions.
* @param {Array.<number>} dx The spacing between consecutive data points.
* @param {Array.<number>} slope The slopes between consecutive data points.
* @return {Array.<number>} The Spline derivative at each data point.
* @protected
*/
goog.math.interpolator.Spline1.prototype.computeDerivatives = function(
dx, slope) {
var nIntervals = dx.length;
// Compute the main diagonal of the system of equations.
var mainDiag = new Array(nIntervals + 1);
mainDiag[0] = dx[1];
for (var i = 1; i < nIntervals; ++i) {
mainDiag[i] = 2 * (dx[i] + dx[i - 1]);
}
mainDiag[nIntervals] = dx[nIntervals - 2];
// Compute the sub diagonal of the system of equations.
var subDiag = new Array(nIntervals);
for (var i = 0; i < nIntervals; ++i) {
subDiag[i] = dx[i + 1];
}
subDiag[nIntervals - 1] = dx[nIntervals - 2] + dx[nIntervals - 1];
// Compute the super diagonal of the system of equations.
var supDiag = new Array(nIntervals);
supDiag[0] = dx[0] + dx[1];
for (var i = 1; i < nIntervals; ++i) {
supDiag[i] = dx[i - 1];
}
// Compute the right vector of the system of equations.
var vecRight = new Array(nIntervals + 1);
vecRight[0] = ((dx[0] + 2 * supDiag[0]) * dx[1] * slope[0] +
dx[0] * dx[0] * slope[1]) / supDiag[0];
for (var i = 1; i < nIntervals; ++i) {
vecRight[i] = 3 * (dx[i] * slope[i - 1] + dx[i - 1] * slope[i]);
}
vecRight[nIntervals] = (dx[nIntervals - 1] * dx[nIntervals - 1] *
slope[nIntervals - 2] + (2 * subDiag[nIntervals - 1] +
dx[nIntervals - 1]) * dx[nIntervals - 2] * slope[nIntervals - 1]) /
subDiag[nIntervals - 1];
// Solve the system of equations.
var deriv = goog.math.tdma.solve(
subDiag, mainDiag, supDiag, vecRight);
return deriv;
};
/**
* Note that the inverse of a cubic spline is not a cubic spline in general.
* As a result the inverse implementation is only approximate. In
* particular, it only guarantees the exact inverse at the original input data
* points passed to setData.
* @override
*/
goog.math.interpolator.Spline1.prototype.getInverse = function() {
var interpolator = new goog.math.interpolator.Spline1();
var y = [];
for (var i = 0; i < this.x_.length; i++) {
y[i] = this.interpolate(this.x_[i]);
}
interpolator.setData(y, this.x_);
return interpolator;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A one dimensional linear interpolator.
*
*/
goog.provide('goog.math.interpolator.Linear1');
goog.require('goog.array');
goog.require('goog.math');
goog.require('goog.math.interpolator.Interpolator1');
/**
* A one dimensional linear interpolator.
* @implements {goog.math.interpolator.Interpolator1}
* @constructor
*/
goog.math.interpolator.Linear1 = function() {
/**
* The abscissa of the data points.
* @type {!Array.<number>}
* @private
*/
this.x_ = [];
/**
* The ordinate of the data points.
* @type {!Array.<number>}
* @private
*/
this.y_ = [];
};
/** @override */
goog.math.interpolator.Linear1.prototype.setData = function(x, y) {
goog.asserts.assert(x.length == y.length,
'input arrays to setData should have the same length');
if (x.length == 1) {
this.x_ = [x[0], x[0] + 1];
this.y_ = [y[0], y[0]];
} else {
this.x_ = x.slice();
this.y_ = y.slice();
}
};
/** @override */
goog.math.interpolator.Linear1.prototype.interpolate = function(x) {
var pos = goog.array.binarySearch(this.x_, x);
if (pos < 0) {
pos = -pos - 2;
}
pos = goog.math.clamp(pos, 0, this.x_.length - 2);
var progress = (x - this.x_[pos]) / (this.x_[pos + 1] - this.x_[pos]);
return goog.math.lerp(this.y_[pos], this.y_[pos + 1], progress);
};
/** @override */
goog.math.interpolator.Linear1.prototype.getInverse = function() {
var interpolator = new goog.math.interpolator.Linear1();
interpolator.setData(this.y_, this.x_);
return interpolator;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides facilities for creating and querying tweaks.
* @see http://code.google.com/p/closure-library/wiki/UsingTweaks
*
* @author agrieve@google.com (Andrew Grieve)
*/
goog.provide('goog.tweak');
goog.provide('goog.tweak.ConfigParams');
goog.require('goog.asserts');
goog.require('goog.tweak.BooleanGroup');
goog.require('goog.tweak.BooleanInGroupSetting');
goog.require('goog.tweak.BooleanSetting');
goog.require('goog.tweak.ButtonAction');
goog.require('goog.tweak.NumericSetting');
goog.require('goog.tweak.Registry');
goog.require('goog.tweak.StringSetting');
/**
* Calls to this function are overridden by the compiler by the processTweaks
* pass. It returns the overrides to default values for tweaks set by compiler
* options.
* @return {!Object.<number|string|boolean>} A map of tweakId -> defaultValue.
* @private
*/
goog.tweak.getCompilerOverrides_ = function() {
return {};
};
/**
* The global reference to the registry, if it exists.
* @type {goog.tweak.Registry}
* @private
*/
goog.tweak.registry_ = null;
/**
* The boolean group set by beginBooleanGroup and cleared by endBooleanGroup.
* @type {goog.tweak.BooleanGroup}
* @private
*/
goog.tweak.activeBooleanGroup_ = null;
/**
* Returns/creates the registry singleton.
* @return {!goog.tweak.Registry} The tweak registry.
*/
goog.tweak.getRegistry = function() {
if (!goog.tweak.registry_) {
var queryString = window.location.search;
var overrides = goog.tweak.getCompilerOverrides_();
goog.tweak.registry_ = new goog.tweak.Registry(queryString, overrides);
}
return goog.tweak.registry_;
};
/**
* Type for configParams.
* TODO(agrieve): Remove |Object when optional fields in struct types are
* implemented.
* @typedef {{
* label:(string|undefined),
* validValues:(!Array.<string>|!Array.<number>|undefined),
* paramName:(string|undefined),
* restartRequired:(boolean|undefined),
* callback:(Function|undefined),
* token:(string|undefined)
* }|!Object}
*/
goog.tweak.ConfigParams;
/**
* Silences warning about properties on ConfigParams never being set when
* running JsLibTest.
* @return {goog.tweak.ConfigParams} Dummy return.
* @private
*/
goog.tweak.configParamsNeverCompilerWarningWorkAround_ = function() {
return {
label: '',
validValues: [],
paramName: '',
restartRequired: true,
callback: goog.nullFunction,
token: ''
};
};
/**
* Applies all extra configuration parameters in configParams.
* @param {!goog.tweak.BaseEntry} entry The entry to apply them to.
* @param {!goog.tweak.ConfigParams} configParams Extra configuration
* parameters.
* @private
*/
goog.tweak.applyConfigParams_ = function(entry, configParams) {
if (configParams.label) {
entry.label = configParams.label;
delete configParams.label;
}
if (configParams.validValues) {
goog.asserts.assert(entry instanceof goog.tweak.StringSetting ||
entry instanceof goog.tweak.NumericSetting,
'Cannot set validValues on tweak: %s', entry.getId());
entry.setValidValues(configParams.validValues);
delete configParams.validValues;
}
if (goog.isDef(configParams.paramName)) {
goog.asserts.assertInstanceof(entry, goog.tweak.BaseSetting,
'Cannot set paramName on tweak: %s', entry.getId());
entry.setParamName(configParams.paramName);
delete configParams.paramName;
}
if (goog.isDef(configParams.restartRequired)) {
entry.setRestartRequired(configParams.restartRequired);
delete configParams.restartRequired;
}
if (configParams.callback) {
entry.addCallback(configParams.callback);
delete configParams.callback;
goog.asserts.assert(
!entry.isRestartRequired() || (configParams.restartRequired == false),
'Tweak %s should set restartRequired: false, when adding a callback.',
entry.getId());
}
if (configParams.token) {
goog.asserts.assertInstanceof(entry, goog.tweak.BooleanInGroupSetting,
'Cannot set token on tweak: %s', entry.getId());
entry.setToken(configParams.token);
delete configParams.token;
}
for (var key in configParams) {
goog.asserts.fail('Unknown config options (' + key + '=' +
configParams[key] + ') for tweak ' + entry.getId());
}
};
/**
* Registers a tweak using the given factoryFunc.
* @param {!goog.tweak.BaseEntry} entry The entry to register.
* @param {boolean|string|number=} opt_defaultValue Default value.
* @param {goog.tweak.ConfigParams=} opt_configParams Extra
* configuration parameters.
* @private
*/
goog.tweak.doRegister_ = function(entry, opt_defaultValue, opt_configParams) {
if (opt_configParams) {
goog.tweak.applyConfigParams_(entry, opt_configParams);
}
if (opt_defaultValue != undefined) {
entry.setDefaultValue(opt_defaultValue);
}
if (goog.tweak.activeBooleanGroup_) {
goog.asserts.assertInstanceof(entry, goog.tweak.BooleanInGroupSetting,
'Forgot to end Boolean Group: %s',
goog.tweak.activeBooleanGroup_.getId());
goog.tweak.activeBooleanGroup_.addChild(
/** @type {!goog.tweak.BooleanInGroupSetting} */ (entry));
}
goog.tweak.getRegistry().register(entry);
};
/**
* Creates and registers a group of BooleanSettings that are all set by a
* single query parameter. A call to goog.tweak.endBooleanGroup() must be used
* to close this group. Only goog.tweak.registerBoolean() calls are allowed with
* the beginBooleanGroup()/endBooleanGroup().
* @param {string} id The unique ID for the setting.
* @param {string} description A description of what the setting does.
* @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
* parameters.
*/
goog.tweak.beginBooleanGroup = function(id, description, opt_configParams) {
var entry = new goog.tweak.BooleanGroup(id, description);
goog.tweak.doRegister_(entry, undefined, opt_configParams);
goog.tweak.activeBooleanGroup_ = entry;
};
/**
* Stops adding boolean entries to the active boolean group.
*/
goog.tweak.endBooleanGroup = function() {
goog.tweak.activeBooleanGroup_ = null;
};
/**
* Creates and registers a BooleanSetting.
* @param {string} id The unique ID for the setting.
* @param {string} description A description of what the setting does.
* @param {boolean=} opt_defaultValue The default value for the setting.
* @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
* parameters.
*/
goog.tweak.registerBoolean =
function(id, description, opt_defaultValue, opt_configParams) {
// TODO(agrieve): There is a bug in the compiler that causes these calls not
// to be stripped without this outer if. Might be Issue #90.
if (goog.tweak.activeBooleanGroup_) {
var entry = new goog.tweak.BooleanInGroupSetting(id, description,
goog.tweak.activeBooleanGroup_);
} else {
entry = new goog.tweak.BooleanSetting(id, description);
}
goog.tweak.doRegister_(entry, opt_defaultValue, opt_configParams);
};
/**
* Creates and registers a StringSetting.
* @param {string} id The unique ID for the setting.
* @param {string} description A description of what the setting does.
* @param {string=} opt_defaultValue The default value for the setting.
* @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
* parameters.
*/
goog.tweak.registerString =
function(id, description, opt_defaultValue, opt_configParams) {
goog.tweak.doRegister_(new goog.tweak.StringSetting(id, description),
opt_defaultValue, opt_configParams);
};
/**
* Creates and registers a NumericSetting.
* @param {string} id The unique ID for the setting.
* @param {string} description A description of what the setting does.
* @param {number=} opt_defaultValue The default value for the setting.
* @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
* parameters.
*/
goog.tweak.registerNumber =
function(id, description, opt_defaultValue, opt_configParams) {
goog.tweak.doRegister_(new goog.tweak.NumericSetting(id, description),
opt_defaultValue, opt_configParams);
};
/**
* Creates and registers a ButtonAction.
* @param {string} id The unique ID for the setting.
* @param {string} description A description of what the action does.
* @param {!Function} callback Function to call when the button is clicked.
* @param {string=} opt_label The button text (instead of the ID).
*/
goog.tweak.registerButton = function(id, description, callback, opt_label) {
var tweak = new goog.tweak.ButtonAction(id, description, callback);
tweak.label = opt_label || tweak.label;
goog.tweak.doRegister_(tweak);
};
/**
* Sets a default value to use for the given tweak instead of the one passed
* to the register* function. This function must be called before the tweak is
* registered.
* @param {string} id The unique string that identifies the entry.
* @param {string|number|boolean} value The new default value for the tweak.
*/
goog.tweak.overrideDefaultValue = function(id, value) {
goog.tweak.getRegistry().overrideDefaultValue(id, value);
};
/**
* Returns the value of the boolean setting with the given ID.
* @param {string} id The unique string that identifies this entry.
* @return {boolean} The value of the tweak.
*/
goog.tweak.getBoolean = function(id) {
return goog.tweak.getRegistry().getBooleanSetting(id).getValue();
};
/**
* Returns the value of the string setting with the given ID,
* @param {string} id The unique string that identifies this entry.
* @return {string} The value of the tweak.
*/
goog.tweak.getString = function(id) {
return goog.tweak.getRegistry().getStringSetting(id).getValue();
};
/**
* Returns the value of the numeric setting with the given ID.
* @param {string} id The unique string that identifies this entry.
* @return {number} The value of the tweak.
*/
goog.tweak.getNumber = function(id) {
return goog.tweak.getRegistry().getNumericSetting(id).getValue();
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Common test functions for tweak unit tests.
*
* @author agrieve@google.com (Andrew Grieve)
*/
goog.provide('goog.tweak.testhelpers');
goog.require('goog.tweak');
goog.require('goog.tweak.BooleanGroup');
goog.require('goog.tweak.BooleanInGroupSetting');
goog.require('goog.tweak.BooleanSetting');
goog.require('goog.tweak.ButtonAction');
goog.require('goog.tweak.NumericSetting');
goog.require('goog.tweak.Registry');
goog.require('goog.tweak.StringSetting');
var boolEntry;
var boolEntry2;
var strEntry;
var strEntry2;
var strEnumEntry;
var numEntry;
var numEnumEntry;
var boolGroup;
var boolOneEntry;
var boolTwoEntry;
var buttonEntry;
/**
* Creates a registry with some entries in it.
* @param {string} queryParams The query parameter string to use for the
* registry.
* @param {!Object.<string|number|boolean>=} opt_compilerOverrides Compiler
* overrides.
*/
function createRegistryEntries(queryParams, opt_compilerOverrides) {
// Initialize the registry with the given query string.
var registry =
new goog.tweak.Registry(queryParams, opt_compilerOverrides || {});
goog.tweak.registry_ = registry;
boolEntry = new goog.tweak.BooleanSetting('Bool', 'The bool1');
registry.register(boolEntry);
boolEntry2 = new goog.tweak.BooleanSetting('Bool2', 'The bool2');
boolEntry2.setDefaultValue(true);
registry.register(boolEntry2);
strEntry = new goog.tweak.StringSetting('Str', 'The str1');
strEntry.setParamName('s');
registry.register(strEntry);
strEntry2 = new goog.tweak.StringSetting('Str2', 'The str2');
strEntry2.setDefaultValue('foo');
registry.register(strEntry2);
strEnumEntry = new goog.tweak.StringSetting('Enum', 'The enum');
strEnumEntry.setValidValues(['A', 'B', 'C']);
strEnumEntry.setRestartRequired(false);
registry.register(strEnumEntry);
numEntry = new goog.tweak.NumericSetting('Num', 'The num');
numEntry.setDefaultValue(99);
registry.register(numEntry);
numEnumEntry = new goog.tweak.NumericSetting('Enum2', 'The 2nd enum');
numEnumEntry.setValidValues([1, 2, 3]);
numEnumEntry.setRestartRequired(false);
numEnumEntry.label = 'Enum the second&';
registry.register(numEnumEntry);
boolGroup = new goog.tweak.BooleanGroup('BoolGroup', 'The bool group');
registry.register(boolGroup);
boolOneEntry = new goog.tweak.BooleanInGroupSetting('BoolOne', 'Desc for 1',
boolGroup);
boolOneEntry.setToken('B1');
boolOneEntry.setRestartRequired(false);
boolGroup.addChild(boolOneEntry);
registry.register(boolOneEntry);
boolTwoEntry = new goog.tweak.BooleanInGroupSetting('BoolTwo', 'Desc for 2',
boolGroup);
boolTwoEntry.setDefaultValue(true);
boolGroup.addChild(boolTwoEntry);
registry.register(boolTwoEntry);
buttonEntry = new goog.tweak.ButtonAction('Button', 'The Btn',
goog.nullFunction);
buttonEntry.label = '<btn>';
registry.register(buttonEntry);
var nsBoolGroup = new goog.tweak.BooleanGroup('foo.bar.BoolGroup',
'Namespaced Bool Group');
registry.register(nsBoolGroup);
var nsBool = new goog.tweak.BooleanInGroupSetting('foo.bar.BoolOne',
'Desc for Namespaced 1', nsBoolGroup);
nsBoolGroup.addChild(nsBool);
registry.register(nsBool);
}
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definition for goog.tweak.Registry.
* Most clients should not use this class directly, but instead use the API
* defined in tweak.js. One possible use case for directly using TweakRegistry
* is to register tweaks that are not known at compile time.
*
* @author agrieve@google.com (Andrew Grieve)
*/
goog.provide('goog.tweak.Registry');
goog.require('goog.asserts');
goog.require('goog.debug.Logger');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.tweak.BaseEntry');
goog.require('goog.uri.utils');
/**
* Singleton that manages all tweaks. This should be instantiated only from
* goog.tweak.getRegistry().
* @param {string} queryParams Value of window.location.search.
* @param {!Object.<string|number|boolean>} compilerOverrides Default value
* overrides set by the compiler.
* @constructor
*/
goog.tweak.Registry = function(queryParams, compilerOverrides) {
/**
* A map of entry id -> entry object
* @type {!Object.<!goog.tweak.BaseEntry>}
* @private
*/
this.entryMap_ = {};
/**
* The map of query params to use when initializing entry settings.
* @type {!Object.<string>}
* @private
*/
this.parsedQueryParams_ = goog.tweak.Registry.parseQueryParams(queryParams);
/**
* List of callbacks to call when a new entry is registered.
* @type {!Array.<!Function>}
* @private
*/
this.onRegisterListeners_ = [];
/**
* A map of entry ID -> default value override for overrides set by the
* compiler.
* @type {!Object.<string|number|boolean>}
* @private
*/
this.compilerDefaultValueOverrides_ = compilerOverrides;
/**
* A map of entry ID -> default value override for overrides set by
* goog.tweak.overrideDefaultValue().
* @type {!Object.<string|number|boolean>}
* @private
*/
this.defaultValueOverrides_ = {};
};
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @private
*/
goog.tweak.Registry.prototype.logger_ =
goog.debug.Logger.getLogger('goog.tweak.Registry');
/**
* Simple parser for query params. Makes all keys lower-case.
* @param {string} queryParams The part of the url between the ? and the #.
* @return {!Object.<string>} map of key->value.
*/
goog.tweak.Registry.parseQueryParams = function(queryParams) {
// Strip off the leading ? and split on &.
var parts = queryParams.substr(1).split('&');
var ret = {};
for (var i = 0, il = parts.length; i < il; ++i) {
var entry = parts[i].split('=');
if (entry[0]) {
ret[goog.string.urlDecode(entry[0]).toLowerCase()] =
goog.string.urlDecode(entry[1] || '');
}
}
return ret;
};
/**
* Registers the given tweak setting/action.
* @param {goog.tweak.BaseEntry} entry The entry.
*/
goog.tweak.Registry.prototype.register = function(entry) {
var id = entry.getId();
var oldBaseEntry = this.entryMap_[id];
if (oldBaseEntry) {
if (oldBaseEntry == entry) {
this.logger_.warning('Tweak entry registered twice: ' + id);
return;
}
goog.asserts.fail(
'Tweak entry registered twice and with different types: ' + id);
}
// Check for a default value override, either from compiler flags or from a
// call to overrideDefaultValue().
var defaultValueOverride = (id in this.compilerDefaultValueOverrides_) ?
this.compilerDefaultValueOverrides_[id] : this.defaultValueOverrides_[id];
if (goog.isDef(defaultValueOverride)) {
goog.asserts.assertInstanceof(entry, goog.tweak.BasePrimitiveSetting,
'Cannot set the default value of non-primitive setting %s',
entry.label);
entry.setDefaultValue(defaultValueOverride);
}
// Set its value from the query params.
if (entry instanceof goog.tweak.BaseSetting) {
if (entry.getParamName()) {
entry.setInitialQueryParamValue(
this.parsedQueryParams_[entry.getParamName()]);
}
}
this.entryMap_[id] = entry;
// Call all listeners.
for (var i = 0, callback; callback = this.onRegisterListeners_[i]; ++i) {
callback(entry);
}
};
/**
* Adds a callback to be called whenever a new tweak is added.
* @param {!Function} func The callback.
*/
goog.tweak.Registry.prototype.addOnRegisterListener = function(func) {
this.onRegisterListeners_.push(func);
};
/**
* @param {string} id The unique string that identifies this entry.
* @return {boolean} Whether a tweak with the given ID is registered.
*/
goog.tweak.Registry.prototype.hasEntry = function(id) {
return id in this.entryMap_;
};
/**
* Returns the BaseEntry with the given ID. Asserts if it does not exists.
* @param {string} id The unique string that identifies this entry.
* @return {!goog.tweak.BaseEntry} The entry.
*/
goog.tweak.Registry.prototype.getEntry = function(id) {
var ret = this.entryMap_[id];
goog.asserts.assert(ret, 'Tweak not registered: %s', id);
return ret;
};
/**
* Returns the boolean setting with the given ID. Asserts if the ID does not
* refer to a registered entry or if it refers to one of the wrong type.
* @param {string} id The unique string that identifies this entry.
* @return {!goog.tweak.BooleanSetting} The entry.
*/
goog.tweak.Registry.prototype.getBooleanSetting = function(id) {
var entry = this.getEntry(id);
goog.asserts.assertInstanceof(entry, goog.tweak.BooleanSetting,
'getBooleanSetting called on wrong type of BaseSetting');
return /** @type {!goog.tweak.BooleanSetting} */ (entry);
};
/**
* Returns the string setting with the given ID. Asserts if the ID does not
* refer to a registered entry or if it refers to one of the wrong type.
* @param {string} id The unique string that identifies this entry.
* @return {!goog.tweak.StringSetting} The entry.
*/
goog.tweak.Registry.prototype.getStringSetting = function(id) {
var entry = this.getEntry(id);
goog.asserts.assertInstanceof(entry, goog.tweak.StringSetting,
'getStringSetting called on wrong type of BaseSetting');
return /** @type {!goog.tweak.StringSetting} */ (entry);
};
/**
* Returns the numeric setting with the given ID. Asserts if the ID does not
* refer to a registered entry or if it refers to one of the wrong type.
* @param {string} id The unique string that identifies this entry.
* @return {!goog.tweak.NumericSetting} The entry.
*/
goog.tweak.Registry.prototype.getNumericSetting = function(id) {
var entry = this.getEntry(id);
goog.asserts.assertInstanceof(entry, goog.tweak.NumericSetting,
'getNumericSetting called on wrong type of BaseSetting');
return /** @type {!goog.tweak.NumericSetting} */ (entry);
};
/**
* Creates and returns an array of all BaseSetting objects with an associted
* query parameter.
* @param {boolean} excludeChildEntries Exclude BooleanInGroupSettings.
* @param {boolean} excludeNonSettings Exclude entries that are not subclasses
* of BaseSetting.
* @return {!Array.<!goog.tweak.BaseSetting>} The settings.
*/
goog.tweak.Registry.prototype.extractEntries =
function(excludeChildEntries, excludeNonSettings) {
var entries = [];
for (var id in this.entryMap_) {
var entry = this.entryMap_[id];
if (entry instanceof goog.tweak.BaseSetting) {
if (excludeChildEntries && !entry.getParamName()) {
continue;
}
} else if (excludeNonSettings) {
continue;
}
entries.push(entry);
}
return entries;
};
/**
* Returns the query part of the URL that will apply all set tweaks.
* @param {string=} opt_existingSearchStr The part of the url between the ? and
* the #. Uses window.location.search if not given.
* @return {string} The query string.
*/
goog.tweak.Registry.prototype.makeUrlQuery =
function(opt_existingSearchStr) {
var existingParams = opt_existingSearchStr == undefined ?
window.location.search : opt_existingSearchStr;
var sortedEntries = this.extractEntries(true /* excludeChildEntries */,
true /* excludeNonSettings */);
// Sort the params so that the urlQuery has stable ordering.
sortedEntries.sort(function(a, b) {
return goog.array.defaultCompare(a.getParamName(), b.getParamName());
});
// Add all values that are not set to their defaults.
var keysAndValues = [];
for (var i = 0, entry; entry = sortedEntries[i]; ++i) {
var encodedValue = entry.getNewValueEncoded();
if (encodedValue != null) {
keysAndValues.push(entry.getParamName(), encodedValue);
}
// Strip all tweak query params from the existing query string. This will
// make the final query string contain only the tweak settings that are set
// to their non-default values and also maintain non-tweak related query
// parameters.
existingParams = goog.uri.utils.removeParam(existingParams,
encodeURIComponent(/** @type {string} */ (entry.getParamName())));
}
var tweakParams = goog.uri.utils.buildQueryData(keysAndValues);
// Decode spaces and commas in order to make the URL more readable.
tweakParams = tweakParams.replace(/%2C/g, ',').replace(/%20/g, '+');
return !tweakParams ? existingParams :
existingParams ? existingParams + '&' + tweakParams :
'?' + tweakParams;
};
/**
* Sets a default value to use for the given tweak instead of the one passed
* to the register* function. This function must be called before the tweak is
* registered.
* @param {string} id The unique string that identifies the entry.
* @param {string|number|boolean} value The replacement value to be used as the
* default value for the setting.
*/
goog.tweak.Registry.prototype.overrideDefaultValue = function(id, value) {
goog.asserts.assert(!this.hasEntry(id),
'goog.tweak.overrideDefaultValue must be called before the tweak is ' +
'registered. Tweak: %s', id);
this.defaultValueOverrides_[id] = value;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A UI for editing tweak settings / clicking tweak actions.
*
* @author agrieve@google.com (Andrew Grieve)
*/
goog.provide('goog.tweak.EntriesPanel');
goog.provide('goog.tweak.TweakUi');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.dom.DomHelper');
goog.require('goog.object');
goog.require('goog.style');
goog.require('goog.tweak');
goog.require('goog.ui.Zippy');
goog.require('goog.userAgent');
/**
* A UI for editing tweak settings / clicking tweak actions.
* @param {!goog.tweak.Registry} registry The registry to render.
* @param {goog.dom.DomHelper=} opt_domHelper The DomHelper to render with.
* @constructor
*/
goog.tweak.TweakUi = function(registry, opt_domHelper) {
/**
* The registry to create a UI from.
* @type {!goog.tweak.Registry}
* @private
*/
this.registry_ = registry;
/**
* The element to display when the UI is visible.
* @type {goog.tweak.EntriesPanel|undefined}
* @private
*/
this.entriesPanel_;
/**
* The DomHelper to render with.
* @type {!goog.dom.DomHelper}
* @private
*/
this.domHelper_ = opt_domHelper || goog.dom.getDomHelper();
// Listen for newly registered entries (happens with lazy-loaded modules).
registry.addOnRegisterListener(goog.bind(this.onNewRegisteredEntry_, this));
};
/**
* The CSS class name unique to the root tweak panel div.
* @type {string}
* @private
*/
goog.tweak.TweakUi.ROOT_PANEL_CLASS_ = goog.getCssName('goog-tweak-root');
/**
* The CSS class name unique to the tweak entry div.
* @type {string}
* @private
*/
goog.tweak.TweakUi.ENTRY_CSS_CLASS_ = goog.getCssName('goog-tweak-entry');
/**
* The CSS classes for each tweak entry div.
* @type {string}
* @private
*/
goog.tweak.TweakUi.ENTRY_CSS_CLASSES_ = goog.tweak.TweakUi.ENTRY_CSS_CLASS_ +
' ' + goog.getCssName('goog-inline-block');
/**
* The CSS classes for each namespace tweak entry div.
* @type {string}
* @private
*/
goog.tweak.TweakUi.ENTRY_GROUP_CSS_CLASSES_ =
goog.tweak.TweakUi.ENTRY_CSS_CLASS_;
/**
* Marker that the style sheet has already been installed.
* @type {string}
* @private
*/
goog.tweak.TweakUi.STYLE_SHEET_INSTALLED_MARKER_ =
'__closure_tweak_installed_';
/**
* CSS used by TweakUI.
* @type {string}
* @private
*/
goog.tweak.TweakUi.CSS_STYLES_ = (function() {
var MOBILE = goog.userAgent.MOBILE;
var IE = goog.userAgent.IE;
var ENTRY_CLASS = '.' + goog.tweak.TweakUi.ENTRY_CSS_CLASS_;
var ROOT_PANEL_CLASS = '.' + goog.tweak.TweakUi.ROOT_PANEL_CLASS_;
var GOOG_INLINE_BLOCK_CLASS = '.' + goog.getCssName('goog-inline-block');
var ret = ROOT_PANEL_CLASS + '{background:#ffc; padding:0 4px}';
// Make this work even if the user hasn't included common.css.
if (!IE) {
ret += GOOG_INLINE_BLOCK_CLASS + '{display:inline-block}';
}
// Space things out vertically for touch UIs.
if (MOBILE) {
ret += ROOT_PANEL_CLASS + ',' + ROOT_PANEL_CLASS + ' fieldset{' +
'line-height:2em;' + '}';
}
return ret;
})();
/**
* Creates a TweakUi if tweaks are enabled.
* @param {goog.dom.DomHelper=} opt_domHelper The DomHelper to render with.
* @return {Element|undefined} The root UI element or undefined if tweaks are
* not enabled.
*/
goog.tweak.TweakUi.create = function(opt_domHelper) {
var registry = goog.tweak.getRegistry();
if (registry) {
var ui = new goog.tweak.TweakUi(registry, opt_domHelper);
ui.render();
return ui.getRootElement();
}
};
/**
* Creates a TweakUi inside of a show/hide link.
* @param {goog.dom.DomHelper=} opt_domHelper The DomHelper to render with.
* @return {Element|undefined} The root UI element or undefined if tweaks are
* not enabled.
*/
goog.tweak.TweakUi.createCollapsible = function(opt_domHelper) {
var registry = goog.tweak.getRegistry();
if (registry) {
var dh = opt_domHelper || goog.dom.getDomHelper();
// The following strings are for internal debugging only. No translation
// necessary. Do NOT wrap goog.getMsg() around these strings.
var showLink = dh.createDom('a', {href: 'javascript:;'}, 'Show Tweaks');
var hideLink = dh.createDom('a', {href: 'javascript:;'}, 'Hide Tweaks');
var ret = dh.createDom('div', null, showLink);
var lazyCreate = function() {
// Lazily render the UI.
var ui = new goog.tweak.TweakUi(
/** @type {!goog.tweak.Registry} */ (registry), dh);
ui.render();
// Put the hide link on the same line as the "Show Descriptions" link.
// Set the style lazily because we can.
hideLink.style.marginRight = '10px';
var tweakElem = ui.getRootElement();
tweakElem.insertBefore(hideLink, tweakElem.firstChild);
ret.appendChild(tweakElem);
return tweakElem;
};
new goog.ui.Zippy(showLink, lazyCreate, false /* expanded */, hideLink);
return ret;
}
};
/**
* Compares the given entries. Orders alphabetically and groups buttons and
* expandable groups.
* @param {goog.tweak.BaseEntry} a The first entry to compare.
* @param {goog.tweak.BaseEntry} b The second entry to compare.
* @return {number} Refer to goog.array.defaultCompare.
* @private
*/
goog.tweak.TweakUi.entryCompare_ = function(a, b) {
return (
goog.array.defaultCompare(a instanceof goog.tweak.NamespaceEntry_,
b instanceof goog.tweak.NamespaceEntry_) ||
goog.array.defaultCompare(a instanceof goog.tweak.BooleanGroup,
b instanceof goog.tweak.BooleanGroup) ||
goog.array.defaultCompare(a instanceof goog.tweak.ButtonAction,
b instanceof goog.tweak.ButtonAction) ||
goog.array.defaultCompare(a.label, b.label) ||
goog.array.defaultCompare(a.getId(), b.getId()));
};
/**
* @param {!goog.tweak.BaseEntry} entry The entry.
* @return {boolean} Returns whether the given entry contains sub-entries.
* @private
*/
goog.tweak.TweakUi.isGroupEntry_ = function(entry) {
return entry instanceof goog.tweak.NamespaceEntry_ ||
entry instanceof goog.tweak.BooleanGroup;
};
/**
* Returns the list of entries from the given boolean group.
* @param {!goog.tweak.BooleanGroup} group The group to get the entries from.
* @return {!Array.<!goog.tweak.BaseEntry>} The sorted entries.
* @private
*/
goog.tweak.TweakUi.extractBooleanGroupEntries_ = function(group) {
var ret = goog.object.getValues(group.getChildEntries());
ret.sort(goog.tweak.TweakUi.entryCompare_);
return ret;
};
/**
* @param {!goog.tweak.BaseEntry} entry The entry.
* @return {string} Returns the namespace for the entry, or '' if it is not
* namespaced.
* @private
*/
goog.tweak.TweakUi.extractNamespace_ = function(entry) {
var namespaceMatch = /.+(?=\.)/.exec(entry.getId());
return namespaceMatch ? namespaceMatch[0] : '';
};
/**
* @param {!goog.tweak.BaseEntry} entry The entry.
* @return {string} Returns the part of the label after the last period, unless
* the label has been explicly set (it is different from the ID).
* @private
*/
goog.tweak.TweakUi.getNamespacedLabel_ = function(entry) {
var label = entry.label;
if (label == entry.getId()) {
label = label.substr(label.lastIndexOf('.') + 1);
}
return label;
};
/**
* @return {!Element} The root element. Must not be called before render().
*/
goog.tweak.TweakUi.prototype.getRootElement = function() {
goog.asserts.assert(this.entriesPanel_,
'TweakUi.getRootElement called before render().');
return this.entriesPanel_.getRootElement();
};
/**
* Reloads the page with query parameters set by the UI.
* @private
*/
goog.tweak.TweakUi.prototype.restartWithAppliedTweaks_ = function() {
var queryString = this.registry_.makeUrlQuery();
var wnd = this.domHelper_.getWindow();
if (queryString != wnd.location.search) {
wnd.location.search = queryString;
} else {
wnd.location.reload();
}
};
/**
* Installs the required CSS styles.
* @private
*/
goog.tweak.TweakUi.prototype.installStyles_ = function() {
// Use an marker to install the styles only once per document.
// Styles are injected via JS instead of in a separate style sheet so that
// they are automatically excluded when tweaks are stripped out.
var doc = this.domHelper_.getDocument();
if (!(goog.tweak.TweakUi.STYLE_SHEET_INSTALLED_MARKER_ in doc)) {
goog.style.installStyles(
goog.tweak.TweakUi.CSS_STYLES_, doc);
doc[goog.tweak.TweakUi.STYLE_SHEET_INSTALLED_MARKER_] = true;
}
};
/**
* Creates the element to display when the UI is visible.
* @return {!Element} The root element.
*/
goog.tweak.TweakUi.prototype.render = function() {
this.installStyles_();
var dh = this.domHelper_;
// The submit button
var submitButton = dh.createDom('button', {style: 'font-weight:bold'},
'Apply Tweaks');
submitButton.onclick = goog.bind(this.restartWithAppliedTweaks_, this);
var rootPanel = new goog.tweak.EntriesPanel([], dh);
var rootPanelDiv = rootPanel.render(submitButton);
rootPanelDiv.className += ' ' + goog.tweak.TweakUi.ROOT_PANEL_CLASS_;
this.entriesPanel_ = rootPanel;
var entries = this.registry_.extractEntries(true /* excludeChildEntries */,
false /* excludeNonSettings */);
for (var i = 0, entry; entry = entries[i]; i++) {
this.insertEntry_(entry);
}
return rootPanelDiv;
};
/**
* Updates the UI with the given entry.
* @param {!goog.tweak.BaseEntry} entry The newly registered entry.
* @private
*/
goog.tweak.TweakUi.prototype.onNewRegisteredEntry_ = function(entry) {
if (this.entriesPanel_) {
this.insertEntry_(entry);
}
};
/**
* Updates the UI with the given entry.
* @param {!goog.tweak.BaseEntry} entry The newly registered entry.
* @private
*/
goog.tweak.TweakUi.prototype.insertEntry_ = function(entry) {
var panel = this.entriesPanel_;
var namespace = goog.tweak.TweakUi.extractNamespace_(entry);
if (namespace) {
// Find the NamespaceEntry that the entry belongs to.
var namespaceEntryId = goog.tweak.NamespaceEntry_.ID_PREFIX + namespace;
var nsPanel = panel.childPanels[namespaceEntryId];
if (nsPanel) {
panel = nsPanel;
} else {
entry = new goog.tweak.NamespaceEntry_(namespace, [entry]);
}
}
if (entry instanceof goog.tweak.BooleanInGroupSetting) {
var group = entry.getGroup();
// BooleanGroup entries are always registered before their
// BooleanInGroupSettings.
panel = panel.childPanels[group.getId()];
}
goog.asserts.assert(panel, 'Missing panel for entry %s', entry.getId());
panel.insertEntry(entry);
};
/**
* The body of the tweaks UI and also used for BooleanGroup.
* @param {!Array.<!goog.tweak.BaseEntry>} entries The entries to show in the
* panel.
* @param {goog.dom.DomHelper=} opt_domHelper The DomHelper to render with.
* @constructor
*/
goog.tweak.EntriesPanel = function(entries, opt_domHelper) {
/**
* The entries to show in the panel.
* @type {!Array.<!goog.tweak.BaseEntry>} entries
* @private
*/
this.entries_ = entries;
var self = this;
/**
* The bound onclick handler for the help question marks.
* @this {Element}
* @private
*/
this.boundHelpOnClickHandler_ = function() {
self.onHelpClick_(this.parentNode);
};
/**
* The element that contains the UI.
* @type {Element}
* @private
*/
this.rootElem_;
/**
* The element that contains all of the settings and the endElement.
* @type {Element}
* @private
*/
this.mainPanel_;
/**
* Flips between true/false each time the "Toggle Descriptions" link is
* clicked.
* @type {boolean}
* @private
*/
this.showAllDescriptionsState_;
/**
* The DomHelper to render with.
* @type {!goog.dom.DomHelper}
* @private
*/
this.domHelper_ = opt_domHelper || goog.dom.getDomHelper();
/**
* Map of tweak ID -> EntriesPanel for child panels (BooleanGroups).
* @type {!Object.<!goog.tweak.EntriesPanel>}
*/
this.childPanels = {};
};
/**
* @return {!Element} Returns the expanded element. Must not be called before
* render().
*/
goog.tweak.EntriesPanel.prototype.getRootElement = function() {
goog.asserts.assert(this.rootElem_,
'EntriesPanel.getRootElement called before render().');
return /** @type {!Element} */ (this.rootElem_);
};
/**
* Creates and returns the expanded element.
* The markup looks like:
* <div>
* <a>Show Descriptions</a>
* <div>
* ...
* {endElement}
* </div>
* </div>
* @param {Element|DocumentFragment=} opt_endElement Element to insert after all
* tweak entries.
* @return {!Element} The root element for the panel.
*/
goog.tweak.EntriesPanel.prototype.render = function(opt_endElement) {
var dh = this.domHelper_;
var entries = this.entries_;
var ret = dh.createDom('div');
var showAllDescriptionsLink = dh.createDom('a', {
href: 'javascript:;',
onclick: goog.bind(this.toggleAllDescriptions, this)
}, 'Toggle all Descriptions');
ret.appendChild(showAllDescriptionsLink);
// Add all of the entries.
var mainPanel = dh.createElement('div');
this.mainPanel_ = mainPanel;
for (var i = 0, entry; entry = entries[i]; i++) {
mainPanel.appendChild(this.createEntryElem_(entry));
}
if (opt_endElement) {
mainPanel.appendChild(opt_endElement);
}
ret.appendChild(mainPanel);
this.rootElem_ = ret;
return /** @type {!Element} */ (ret);
};
/**
* Inserts the given entry into the panel.
* @param {!goog.tweak.BaseEntry} entry The entry to insert.
*/
goog.tweak.EntriesPanel.prototype.insertEntry = function(entry) {
var insertIndex = -goog.array.binarySearch(this.entries_, entry,
goog.tweak.TweakUi.entryCompare_) - 1;
goog.asserts.assert(insertIndex >= 0, 'insertEntry failed for %s',
entry.getId());
goog.array.insertAt(this.entries_, entry, insertIndex);
this.mainPanel_.insertBefore(
this.createEntryElem_(entry),
// IE doesn't like 'undefined' here.
this.mainPanel_.childNodes[insertIndex] || null);
};
/**
* Creates and returns a form element for the given entry.
* @param {!goog.tweak.BaseEntry} entry The entry.
* @return {!Element} The root DOM element for the entry.
* @private
*/
goog.tweak.EntriesPanel.prototype.createEntryElem_ = function(entry) {
var dh = this.domHelper_;
var isGroupEntry = goog.tweak.TweakUi.isGroupEntry_(entry);
var classes = isGroupEntry ? goog.tweak.TweakUi.ENTRY_GROUP_CSS_CLASSES_ :
goog.tweak.TweakUi.ENTRY_CSS_CLASSES_;
// Containers should not use label tags or else all descendent inputs will be
// connected on desktop browsers.
var containerNodeName = isGroupEntry ? 'span' : 'label';
var ret = dh.createDom('div', classes,
dh.createDom(containerNodeName, {
// Make the hover text the description.
title: entry.description,
style: 'color:' + (entry.isRestartRequired() ? '' : 'blue')
}, this.createTweakEntryDom_(entry)),
// Add the expandable help question mark.
this.createHelpElem_(entry));
return ret;
};
/**
* Click handler for the help link.
* @param {Node} entryDiv The div that contains the tweak.
* @private
*/
goog.tweak.EntriesPanel.prototype.onHelpClick_ = function(entryDiv) {
this.showDescription_(entryDiv, !entryDiv.style.display);
};
/**
* Twiddle the DOM so that the entry within the given span is shown/hidden.
* @param {Node} entryDiv The div that contains the tweak.
* @param {boolean} show True to show, false to hide.
* @private
*/
goog.tweak.EntriesPanel.prototype.showDescription_ =
function(entryDiv, show) {
var descriptionElem = entryDiv.lastChild.lastChild;
goog.style.setElementShown(/** @type {Element} */ (descriptionElem), show);
entryDiv.style.display = show ? 'block' : '';
};
/**
* Creates and returns a help element for the given entry.
* @param {goog.tweak.BaseEntry} entry The entry.
* @return {!Element} The root element of the created DOM.
* @private
*/
goog.tweak.EntriesPanel.prototype.createHelpElem_ = function(entry) {
// The markup looks like:
// <span onclick=...><b>?</b><span>{description}</span></span>
var ret = this.domHelper_.createElement('span');
ret.innerHTML = '<b style="padding:0 1em 0 .5em">?</b>' +
'<span style="display:none;color:#666"></span>';
ret.onclick = this.boundHelpOnClickHandler_;
var descriptionElem = ret.lastChild;
goog.dom.setTextContent(/** @type {Element} */ (descriptionElem),
entry.description);
if (!entry.isRestartRequired()) {
descriptionElem.innerHTML +=
' <span style="color:blue">(no restart required)</span>';
}
return ret;
};
/**
* Show all entry descriptions (has the same effect as clicking on all ?'s).
*/
goog.tweak.EntriesPanel.prototype.toggleAllDescriptions = function() {
var show = !this.showAllDescriptionsState_;
this.showAllDescriptionsState_ = show;
var entryDivs = this.domHelper_.getElementsByTagNameAndClass('div',
goog.tweak.TweakUi.ENTRY_CSS_CLASS_, this.rootElem_);
for (var i = 0, div; div = entryDivs[i]; i++) {
this.showDescription_(div, show);
}
};
/**
* Creates the DOM element to control the given enum setting.
* @param {!goog.tweak.StringSetting|!goog.tweak.NumericSetting} tweak The
* setting.
* @param {string} label The label for the entry.
* @param {!Function} onchangeFunc onchange event handler.
* @return {!DocumentFragment} The DOM element.
* @private
*/
goog.tweak.EntriesPanel.prototype.createComboBoxDom_ =
function(tweak, label, onchangeFunc) {
// The markup looks like:
// Label: <select><option></option></select>
var dh = this.domHelper_;
var ret = dh.getDocument().createDocumentFragment();
ret.appendChild(dh.createTextNode(label + ': '));
var selectElem = dh.createElement('select');
var values = tweak.getValidValues();
for (var i = 0, il = values.length; i < il; ++i) {
var optionElem = dh.createElement('option');
optionElem.text = String(values[i]);
// Setting the option tag's value is required for selectElem.value to work
// properly.
optionElem.value = String(values[i]);
selectElem.appendChild(optionElem);
}
ret.appendChild(selectElem);
// Set the value and add a callback.
selectElem.value = tweak.getNewValue();
selectElem.onchange = onchangeFunc;
tweak.addCallback(function() {
selectElem.value = tweak.getNewValue();
});
return ret;
};
/**
* Creates the DOM element to control the given boolean setting.
* @param {!goog.tweak.BooleanSetting} tweak The setting.
* @param {string} label The label for the entry.
* @return {!DocumentFragment} The DOM elements.
* @private
*/
goog.tweak.EntriesPanel.prototype.createBooleanSettingDom_ =
function(tweak, label) {
var dh = this.domHelper_;
var ret = dh.getDocument().createDocumentFragment();
var checkbox = dh.createDom('input', {type: 'checkbox'});
ret.appendChild(checkbox);
ret.appendChild(dh.createTextNode(label));
// Needed on IE6 to ensure the textbox doesn't get cleared
// when added to the DOM.
checkbox.defaultChecked = tweak.getNewValue();
checkbox.checked = tweak.getNewValue();
checkbox.onchange = function() {
tweak.setValue(checkbox.checked);
};
tweak.addCallback(function() {
checkbox.checked = tweak.getNewValue();
});
return ret;
};
/**
* Creates the DOM for a BooleanGroup or NamespaceEntry.
* @param {!goog.tweak.BooleanGroup|!goog.tweak.NamespaceEntry_} entry The
* entry.
* @param {string} label The label for the entry.
* @param {!Array.<goog.tweak.BaseEntry>} childEntries The child entries.
* @return {!DocumentFragment} The DOM element.
* @private
*/
goog.tweak.EntriesPanel.prototype.createSubPanelDom_ = function(entry, label,
childEntries) {
var dh = this.domHelper_;
var toggleLink = dh.createDom('a', {href: 'javascript:;'},
label + ' \xBB');
var toggleLink2 = dh.createDom('a', {href: 'javascript:;'},
'\xAB ' + label);
toggleLink2.style.marginRight = '10px';
var innerUi = new goog.tweak.EntriesPanel(childEntries, dh);
this.childPanels[entry.getId()] = innerUi;
var elem = innerUi.render();
// Move the toggle descriptions link into the legend.
var descriptionsLink = elem.firstChild;
var childrenElem = dh.createDom('fieldset',
goog.getCssName('goog-inline-block'),
dh.createDom('legend', null, toggleLink2, descriptionsLink),
elem);
new goog.ui.Zippy(toggleLink, childrenElem, false /* expanded */,
toggleLink2);
var ret = dh.getDocument().createDocumentFragment();
ret.appendChild(toggleLink);
ret.appendChild(childrenElem);
return ret;
};
/**
* Creates the DOM element to control the given string setting.
* @param {!goog.tweak.StringSetting|!goog.tweak.NumericSetting} tweak The
* setting.
* @param {string} label The label for the entry.
* @param {!Function} onchangeFunc onchange event handler.
* @return {!DocumentFragment} The DOM element.
* @private
*/
goog.tweak.EntriesPanel.prototype.createTextBoxDom_ =
function(tweak, label, onchangeFunc) {
var dh = this.domHelper_;
var ret = dh.getDocument().createDocumentFragment();
ret.appendChild(dh.createTextNode(label + ': '));
var textBox = dh.createDom('input', {
value: tweak.getNewValue(),
// TODO(agrieve): Make size configurable or autogrow.
size: 5,
onblur: onchangeFunc
});
ret.appendChild(textBox);
tweak.addCallback(function() {
textBox.value = tweak.getNewValue();
});
return ret;
};
/**
* Creates the DOM element to control the given button action.
* @param {!goog.tweak.ButtonAction} tweak The action.
* @param {string} label The label for the entry.
* @return {!Element} The DOM element.
* @private
*/
goog.tweak.EntriesPanel.prototype.createButtonActionDom_ =
function(tweak, label) {
return this.domHelper_.createDom('button', {
onclick: goog.bind(tweak.fireCallbacks, tweak)
}, label);
};
/**
* Creates the DOM element to control the given entry.
* @param {!goog.tweak.BaseEntry} entry The entry.
* @return {!Element|!DocumentFragment} The DOM element.
* @private
*/
goog.tweak.EntriesPanel.prototype.createTweakEntryDom_ = function(entry) {
var label = goog.tweak.TweakUi.getNamespacedLabel_(entry);
if (entry instanceof goog.tweak.BooleanSetting) {
return this.createBooleanSettingDom_(entry, label);
} else if (entry instanceof goog.tweak.BooleanGroup) {
var childEntries = goog.tweak.TweakUi.extractBooleanGroupEntries_(entry);
return this.createSubPanelDom_(entry, label, childEntries);
} else if (entry instanceof goog.tweak.StringSetting) {
/** @this {Element} */
var setValueFunc = function() {
entry.setValue(this.value);
};
return entry.getValidValues() ?
this.createComboBoxDom_(entry, label, setValueFunc) :
this.createTextBoxDom_(entry, label, setValueFunc);
} else if (entry instanceof goog.tweak.NumericSetting) {
setValueFunc = function() {
// Reset the value if it's not a number.
if (isNaN(this.value)) {
this.value = entry.getNewValue();
} else {
entry.setValue(+this.value);
}
};
return entry.getValidValues() ?
this.createComboBoxDom_(entry, label, setValueFunc) :
this.createTextBoxDom_(entry, label, setValueFunc);
} else if (entry instanceof goog.tweak.NamespaceEntry_) {
return this.createSubPanelDom_(entry, entry.label, entry.entries);
}
goog.asserts.assertInstanceof(entry, goog.tweak.ButtonAction,
'invalid entry: %s', entry);
return this.createButtonActionDom_(
/** @type {!goog.tweak.ButtonAction} */ (entry), label);
};
/**
* Entries used to represent the collapsible namespace links. These entries are
* never registered with the TweakRegistry, but are contained within the
* collection of entries within TweakPanels.
* @param {string} namespace The namespace for the entry.
* @param {!Array.<!goog.tweak.BaseEntry>} entries Entries within the namespace.
* @constructor
* @extends {goog.tweak.BaseEntry}
* @private
*/
goog.tweak.NamespaceEntry_ = function(namespace, entries) {
goog.tweak.BaseEntry.call(this,
goog.tweak.NamespaceEntry_.ID_PREFIX + namespace,
'Tweaks within the ' + namespace + ' namespace.');
/**
* Entries within this namespace.
* @type {!Array.<!goog.tweak.BaseEntry>}
*/
this.entries = entries;
this.label = namespace;
};
goog.inherits(goog.tweak.NamespaceEntry_, goog.tweak.BaseEntry);
/**
* Prefix for the IDs of namespace entries used to ensure that they do not
* conflict with regular entries.
* @type {string}
*/
goog.tweak.NamespaceEntry_.ID_PREFIX = '!';
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definitions for all tweak entries.
* The class hierarchy is as follows (abstract entries are denoted with a *):
* BaseEntry(id, description) *
* -> ButtonAction(buttons in the UI)
* -> BaseSetting(query parameter) *
* -> BooleanGroup(child booleans)
* -> BasePrimitiveSetting(value, defaultValue) *
* -> BooleanSetting
* -> StringSetting
* -> NumericSetting
* -> BooleanInGroupSetting(token)
* Most clients should not use these classes directly, but instead use the API
* defined in tweak.js. One possible use case for directly using them is to
* register tweaks that are not known at compile time.
*
* @author agrieve@google.com (Andrew Grieve)
*/
goog.provide('goog.tweak.BaseEntry');
goog.provide('goog.tweak.BasePrimitiveSetting');
goog.provide('goog.tweak.BaseSetting');
goog.provide('goog.tweak.BooleanGroup');
goog.provide('goog.tweak.BooleanInGroupSetting');
goog.provide('goog.tweak.BooleanSetting');
goog.provide('goog.tweak.ButtonAction');
goog.provide('goog.tweak.NumericSetting');
goog.provide('goog.tweak.StringSetting');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug.Logger');
goog.require('goog.object');
/**
* Base class for all Registry entries.
* @param {string} id The ID for the entry. Must contain only letters,
* numbers, underscores and periods.
* @param {string} description A description of what the entry does.
* @constructor
*/
goog.tweak.BaseEntry = function(id, description) {
/**
* An ID to uniquely identify the entry.
* @type {string}
* @private
*/
this.id_ = id;
/**
* A descriptive label for the entry.
* @type {string}
*/
this.label = id;
/**
* A description of what this entry does.
* @type {string}
*/
this.description = description;
/**
* Functions to be called whenever a setting is changed or a button is
* clicked.
* @type {!Array.<!Function>}
* @private
*/
this.callbacks_ = [];
};
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
*/
goog.tweak.BaseEntry.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.BaseEntry');
/**
* Whether a restart is required for changes to the setting to take effect.
* @type {boolean}
* @private
*/
goog.tweak.BaseEntry.prototype.restartRequired_ = true;
/**
* @return {string} Returns the entry's ID.
*/
goog.tweak.BaseEntry.prototype.getId = function() {
return this.id_;
};
/**
* Returns whether a restart is required for changes to the setting to take
* effect.
* @return {boolean} The value.
*/
goog.tweak.BaseEntry.prototype.isRestartRequired = function() {
return this.restartRequired_;
};
/**
* Sets whether a restart is required for changes to the setting to take
* effect.
* @param {boolean} value The new value.
*/
goog.tweak.BaseEntry.prototype.setRestartRequired = function(value) {
this.restartRequired_ = value;
};
/**
* Adds a callback that should be called when the setting has changed (or when
* an action has been clicked).
* @param {!Function} callback The callback to add.
*/
goog.tweak.BaseEntry.prototype.addCallback = function(callback) {
this.callbacks_.push(callback);
};
/**
* Removes a callback that was added by addCallback.
* @param {!Function} callback The callback to add.
*/
goog.tweak.BaseEntry.prototype.removeCallback = function(callback) {
goog.array.remove(this.callbacks_, callback);
};
/**
* Calls all registered callbacks.
*/
goog.tweak.BaseEntry.prototype.fireCallbacks = function() {
for (var i = 0, callback; callback = this.callbacks_[i]; ++i) {
callback(this);
}
};
/**
* Base class for all tweak entries that are settings. Settings are entries
* that are associated with a query parameter.
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @constructor
* @extends {goog.tweak.BaseEntry}
*/
goog.tweak.BaseSetting = function(id, description) {
goog.tweak.BaseEntry.call(this, id, description);
// Apply this restriction for settings since they turn in to query
// parameters. For buttons, it's not really important.
goog.asserts.assert(!/[^A-Za-z0-9._]/.test(id),
'Tweak id contains illegal characters: ', id);
/**
* The value of this setting's query parameter.
* @type {string|undefined}
* @protected
*/
this.initialQueryParamValue;
/**
* The query parameter that controls this setting.
* @type {?string}
* @private
*/
this.paramName_ = this.getId().toLowerCase();
};
goog.inherits(goog.tweak.BaseSetting, goog.tweak.BaseEntry);
/**
* States of initialization. Entries are initialized lazily in order to allow
* their initialization to happen in multiple statements.
* @enum {number}
* @private
*/
goog.tweak.BaseSetting.InitializeState_ = {
// The start state for all settings.
NOT_INITIALIZED: 0,
// This is used to allow concrete classes to call assertNotInitialized()
// during their initialize() function.
INITIALIZING: 1,
// One a setting is initialized, it may no longer change its configuration
// settings (associated query parameter, token, etc).
INITIALIZED: 2
};
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
* @override
*/
goog.tweak.BaseSetting.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.BaseSetting');
/**
* Whether initialize() has been called (or is in the middle of being called).
* @type {goog.tweak.BaseSetting.InitializeState_}
* @private
*/
goog.tweak.BaseSetting.prototype.initializeState_ =
goog.tweak.BaseSetting.InitializeState_.NOT_INITIALIZED;
/**
* Sets the value of the entry based on the value of the query parameter. Once
* this is called, configuration settings (associated query parameter, token,
* etc) may not be changed.
* @param {?string} value The part of the query param for this setting after
* the '='. Null if it is not present.
* @protected
*/
goog.tweak.BaseSetting.prototype.initialize = goog.abstractMethod;
/**
* Returns the value to be used in the query parameter for this tweak.
* @return {?string} The encoded value. Null if the value is set to its
* default.
*/
goog.tweak.BaseSetting.prototype.getNewValueEncoded = goog.abstractMethod;
/**
* Asserts that this tweak has not been initialized yet.
* @param {string} funcName Function name to use in the assertion message.
* @protected
*/
goog.tweak.BaseSetting.prototype.assertNotInitialized = function(funcName) {
goog.asserts.assert(this.initializeState_ !=
goog.tweak.BaseSetting.InitializeState_.INITIALIZED,
'Cannot call ' + funcName + ' after the tweak as been initialized.');
};
/**
* Returns whether the setting is currently being initialized.
* @return {boolean} Whether the setting is currently being initialized.
* @protected
*/
goog.tweak.BaseSetting.prototype.isInitializing = function() {
return this.initializeState_ ==
goog.tweak.BaseSetting.InitializeState_.INITIALIZING;
};
/**
* Sets the initial query parameter value for this setting. May not be called
* after the setting has been initialized.
* @param {string} value The inital query parameter value for this setting.
*/
goog.tweak.BaseSetting.prototype.setInitialQueryParamValue = function(value) {
this.assertNotInitialized('setInitialQueryParamValue');
this.initialQueryParamValue = value;
};
/**
* Returns the name of the query parameter used for this setting.
* @return {?string} The param name. Null if no query parameter is directly
* associated with the setting.
*/
goog.tweak.BaseSetting.prototype.getParamName = function() {
return this.paramName_;
};
/**
* Sets the name of the query parameter used for this setting. If null is
* passed the the setting will not appear in the top-level query string.
* @param {?string} value The new value.
*/
goog.tweak.BaseSetting.prototype.setParamName = function(value) {
this.assertNotInitialized('setParamName');
this.paramName_ = value;
};
/**
* Applies the default value or query param value if this is the first time
* that the function has been called.
* @protected
*/
goog.tweak.BaseSetting.prototype.ensureInitialized = function() {
if (this.initializeState_ ==
goog.tweak.BaseSetting.InitializeState_.NOT_INITIALIZED) {
// Instead of having only initialized / not initialized, there is a
// separate in-between state so that functions that call
// assertNotInitialized() will not fail when called inside of the
// initialize().
this.initializeState_ =
goog.tweak.BaseSetting.InitializeState_.INITIALIZING;
var value = this.initialQueryParamValue == undefined ? null :
this.initialQueryParamValue;
this.initialize(value);
this.initializeState_ =
goog.tweak.BaseSetting.InitializeState_.INITIALIZED;
}
};
/**
* Base class for all settings that wrap primitive values.
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @param {*} defaultValue The default value for this setting.
* @constructor
* @extends {goog.tweak.BaseSetting}
*/
goog.tweak.BasePrimitiveSetting = function(id, description, defaultValue) {
goog.tweak.BaseSetting.call(this, id, description);
/**
* The default value of the setting.
* @type {*}
* @private
*/
this.defaultValue_ = defaultValue;
/**
* The value of the tweak.
* @type {*}
* @private
*/
this.value_;
/**
* The value of the tweak once "Apply Tweaks" is pressed.
* @type {*}
* @private
*/
this.newValue_;
};
goog.inherits(goog.tweak.BasePrimitiveSetting, goog.tweak.BaseSetting);
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
* @override
*/
goog.tweak.BasePrimitiveSetting.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.BasePrimitiveSetting');
/**
* Returns the query param encoded representation of the setting's value.
* @return {string} The encoded value.
* @protected
*/
goog.tweak.BasePrimitiveSetting.prototype.encodeNewValue =
goog.abstractMethod;
/**
* If the setting has the restartRequired option, then returns its inital
* value. Otherwise, returns its current value.
* @return {*} The value.
*/
goog.tweak.BasePrimitiveSetting.prototype.getValue = function() {
this.ensureInitialized();
return this.value_;
};
/**
* Returns the value of the setting to use once "Apply Tweaks" is clicked.
* @return {*} The value.
*/
goog.tweak.BasePrimitiveSetting.prototype.getNewValue = function() {
this.ensureInitialized();
return this.newValue_;
};
/**
* Sets the value of the setting. If the setting has the restartRequired
* option, then the value will not be changed until the "Apply Tweaks" button
* is clicked. If it does not have the option, the value will be update
* immediately and all registered callbacks will be called.
* @param {*} value The value.
*/
goog.tweak.BasePrimitiveSetting.prototype.setValue = function(value) {
this.ensureInitialized();
var changed = this.newValue_ != value;
this.newValue_ = value;
// Don't fire callbacks if we are currently in the initialize() method.
if (this.isInitializing()) {
this.value_ = value;
} else {
if (!this.isRestartRequired()) {
// Update the current value only if the tweak has been marked as not
// needing a restart.
this.value_ = value;
}
if (changed) {
this.fireCallbacks();
}
}
};
/**
* Returns the default value for this setting.
* @return {*} The default value.
*/
goog.tweak.BasePrimitiveSetting.prototype.getDefaultValue = function() {
return this.defaultValue_;
};
/**
* Sets the default value for the tweak.
* @param {*} value The new value.
*/
goog.tweak.BasePrimitiveSetting.prototype.setDefaultValue =
function(value) {
this.assertNotInitialized('setDefaultValue');
this.defaultValue_ = value;
};
/**
* @override
*/
goog.tweak.BasePrimitiveSetting.prototype.getNewValueEncoded = function() {
this.ensureInitialized();
return this.newValue_ == this.defaultValue_ ? null : this.encodeNewValue();
};
/**
* A registry setting for string values.
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @constructor
* @extends {goog.tweak.BasePrimitiveSetting}
*/
goog.tweak.StringSetting = function(id, description) {
goog.tweak.BasePrimitiveSetting.call(this, id, description, '');
/**
* Valid values for the setting.
* @type {Array.<string>|undefined}
*/
this.validValues_;
};
goog.inherits(goog.tweak.StringSetting, goog.tweak.BasePrimitiveSetting);
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
* @override
*/
goog.tweak.StringSetting.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.StringSetting');
/**
* @override
* @return {string} The tweaks's value.
*/
goog.tweak.StringSetting.prototype.getValue;
/**
* @override
* @return {string} The tweaks's new value.
*/
goog.tweak.StringSetting.prototype.getNewValue;
/**
* @override
* @param {string} value The tweaks's value.
*/
goog.tweak.StringSetting.prototype.setValue;
/**
* @override
* @param {string} value The default value.
*/
goog.tweak.StringSetting.prototype.setDefaultValue;
/**
* @override
* @return {string} The default value.
*/
goog.tweak.StringSetting.prototype.getDefaultValue;
/**
* @override
*/
goog.tweak.StringSetting.prototype.encodeNewValue = function() {
return this.getNewValue();
};
/**
* Sets the valid values for the setting.
* @param {Array.<string>|undefined} values Valid values.
*/
goog.tweak.StringSetting.prototype.setValidValues = function(values) {
this.assertNotInitialized('setValidValues');
this.validValues_ = values;
// Set the default value to the first value in the list if the current
// default value is not within it.
if (values && !goog.array.contains(values, this.getDefaultValue())) {
this.setDefaultValue(values[0]);
}
};
/**
* Returns the valid values for the setting.
* @return {Array.<string>|undefined} Valid values.
*/
goog.tweak.StringSetting.prototype.getValidValues = function() {
return this.validValues_;
};
/**
* @override
*/
goog.tweak.StringSetting.prototype.initialize = function(value) {
if (value == null) {
this.setValue(this.getDefaultValue());
} else {
var validValues = this.validValues_;
if (validValues) {
// Make the query parameter values case-insensitive since users might
// type them by hand. Make the capitalization that is actual used come
// from the list of valid values.
value = value.toLowerCase();
for (var i = 0, il = validValues.length; i < il; ++i) {
if (value == validValues[i].toLowerCase()) {
this.setValue(validValues[i]);
return;
}
}
// Warn if the value is not in the list of allowed values.
this.logger.warning('Tweak ' + this.getId() +
' has value outside of expected range:' + value);
}
this.setValue(value);
}
};
/**
* A registry setting for numeric values.
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @constructor
* @extends {goog.tweak.BasePrimitiveSetting}
*/
goog.tweak.NumericSetting = function(id, description) {
goog.tweak.BasePrimitiveSetting.call(this, id, description, 0);
/**
* Valid values for the setting.
* @type {Array.<number>|undefined}
*/
this.validValues_;
};
goog.inherits(goog.tweak.NumericSetting, goog.tweak.BasePrimitiveSetting);
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
* @override
*/
goog.tweak.NumericSetting.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.NumericSetting');
/**
* @override
* @return {number} The tweaks's value.
*/
goog.tweak.NumericSetting.prototype.getValue;
/**
* @override
* @return {number} The tweaks's new value.
*/
goog.tweak.NumericSetting.prototype.getNewValue;
/**
* @override
* @param {number} value The tweaks's value.
*/
goog.tweak.NumericSetting.prototype.setValue;
/**
* @override
* @param {number} value The default value.
*/
goog.tweak.NumericSetting.prototype.setDefaultValue;
/**
* @override
* @return {number} The default value.
*/
goog.tweak.NumericSetting.prototype.getDefaultValue;
/**
* @override
*/
goog.tweak.NumericSetting.prototype.encodeNewValue = function() {
return '' + this.getNewValue();
};
/**
* Sets the valid values for the setting.
* @param {Array.<number>|undefined} values Valid values.
*/
goog.tweak.NumericSetting.prototype.setValidValues =
function(values) {
this.assertNotInitialized('setValidValues');
this.validValues_ = values;
// Set the default value to the first value in the list if the current
// default value is not within it.
if (values && !goog.array.contains(values, this.getDefaultValue())) {
this.setDefaultValue(values[0]);
}
};
/**
* Returns the valid values for the setting.
* @return {Array.<number>|undefined} Valid values.
*/
goog.tweak.NumericSetting.prototype.getValidValues = function() {
return this.validValues_;
};
/**
* @override
*/
goog.tweak.NumericSetting.prototype.initialize = function(value) {
if (value == null) {
this.setValue(this.getDefaultValue());
} else {
var coercedValue = +value;
// Warn if the value is not in the list of allowed values.
if (this.validValues_ &&
!goog.array.contains(this.validValues_, coercedValue)) {
this.logger.warning('Tweak ' + this.getId() +
' has value outside of expected range: ' + value);
}
if (isNaN(coercedValue)) {
this.logger.warning('Tweak ' + this.getId() +
' has value of NaN, resetting to ' + this.getDefaultValue());
this.setValue(this.getDefaultValue());
} else {
this.setValue(coercedValue);
}
}
};
/**
* A registry setting that can be either true of false.
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @constructor
* @extends {goog.tweak.BasePrimitiveSetting}
*/
goog.tweak.BooleanSetting = function(id, description) {
goog.tweak.BasePrimitiveSetting.call(this, id, description, false);
};
goog.inherits(goog.tweak.BooleanSetting, goog.tweak.BasePrimitiveSetting);
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
* @override
*/
goog.tweak.BooleanSetting.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.BooleanSetting');
/**
* @override
* @return {boolean} The tweaks's value.
*/
goog.tweak.BooleanSetting.prototype.getValue;
/**
* @override
* @return {boolean} The tweaks's new value.
*/
goog.tweak.BooleanSetting.prototype.getNewValue;
/**
* @override
* @param {boolean} value The tweaks's value.
*/
goog.tweak.BooleanSetting.prototype.setValue;
/**
* @override
* @param {boolean} value The default value.
*/
goog.tweak.BooleanSetting.prototype.setDefaultValue;
/**
* @override
* @return {boolean} The default value.
*/
goog.tweak.BooleanSetting.prototype.getDefaultValue;
/**
* @override
*/
goog.tweak.BooleanSetting.prototype.encodeNewValue = function() {
return this.getNewValue() ? '1' : '0';
};
/**
* @override
*/
goog.tweak.BooleanSetting.prototype.initialize = function(value) {
if (value == null) {
this.setValue(this.getDefaultValue());
} else {
value = value.toLowerCase();
this.setValue(value == 'true' || value == '1');
}
};
/**
* An entry in a BooleanGroup.
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @param {!goog.tweak.BooleanGroup} group The group that this entry belongs
* to.
* @constructor
* @extends {goog.tweak.BooleanSetting}
*/
goog.tweak.BooleanInGroupSetting = function(id, description, group) {
goog.tweak.BooleanSetting.call(this, id, description);
/**
* The token to use in the query parameter.
* @type {string}
* @private
*/
this.token_ = this.getId().toLowerCase();
/**
* The BooleanGroup that this setting belongs to.
* @type {!goog.tweak.BooleanGroup}
* @private
*/
this.group_ = group;
// Take setting out of top-level query parameter list.
goog.tweak.BooleanInGroupSetting.superClass_.setParamName.call(this,
null);
};
goog.inherits(goog.tweak.BooleanInGroupSetting, goog.tweak.BooleanSetting);
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
* @override
*/
goog.tweak.BooleanInGroupSetting.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.BooleanInGroupSetting');
/**
* @override
*/
goog.tweak.BooleanInGroupSetting.prototype.setParamName = function(value) {
goog.asserts.fail('Use setToken() for BooleanInGroupSetting.');
};
/**
* Sets the token to use in the query parameter.
* @param {string} value The value.
*/
goog.tweak.BooleanInGroupSetting.prototype.setToken = function(value) {
this.token_ = value;
};
/**
* Returns the token to use in the query parameter.
* @return {string} The value.
*/
goog.tweak.BooleanInGroupSetting.prototype.getToken = function() {
return this.token_;
};
/**
* Returns the BooleanGroup that this setting belongs to.
* @return {!goog.tweak.BooleanGroup} The BooleanGroup that this setting
* belongs to.
*/
goog.tweak.BooleanInGroupSetting.prototype.getGroup = function() {
return this.group_;
};
/**
* A registry setting that contains a group of boolean subfield, where all
* entries modify the same query parameter. For example:
* ?foo=setting1,-setting2
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @constructor
* @extends {goog.tweak.BaseSetting}
*/
goog.tweak.BooleanGroup = function(id, description) {
goog.tweak.BaseSetting.call(this, id, description);
/**
* A map of token->child entry.
* @type {!Object.<!goog.tweak.BooleanSetting>}
* @private
*/
this.entriesByToken_ = {};
/**
* A map of token->true/false for all tokens that appeared in the query
* parameter.
* @type {!Object.<boolean>}
* @private
*/
this.queryParamValues_ = {};
};
goog.inherits(goog.tweak.BooleanGroup, goog.tweak.BaseSetting);
/**
* The logger for this class.
* @type {!goog.debug.Logger}
* @protected
* @override
*/
goog.tweak.BooleanGroup.prototype.logger =
goog.debug.Logger.getLogger('goog.tweak.BooleanGroup');
/**
* Returns the map of token->boolean settings.
* @return {!Object.<!goog.tweak.BooleanSetting>} The child settings.
*/
goog.tweak.BooleanGroup.prototype.getChildEntries = function() {
return this.entriesByToken_;
};
/**
* Adds the given BooleanSetting to the group.
* @param {goog.tweak.BooleanInGroupSetting} boolEntry The entry.
*/
goog.tweak.BooleanGroup.prototype.addChild = function(boolEntry) {
this.ensureInitialized();
var token = boolEntry.getToken();
var lcToken = token.toLowerCase();
goog.asserts.assert(!this.entriesByToken_[lcToken],
'Multiple bools registered with token "%s" in group: %s', token,
this.getId());
this.entriesByToken_[lcToken] = boolEntry;
// Initialize from query param.
var value = this.queryParamValues_[lcToken];
if (value != undefined) {
boolEntry.initialQueryParamValue = value ? '1' : '0';
}
};
/**
* @override
*/
goog.tweak.BooleanGroup.prototype.initialize = function(value) {
var queryParamValues = {};
if (value) {
var tokens = value.split(/\s*,\s*/);
for (var i = 0; i < tokens.length; ++i) {
var token = tokens[i].toLowerCase();
var negative = token.charAt(0) == '-';
if (negative) {
token = token.substr(1);
}
queryParamValues[token] = !negative;
}
}
this.queryParamValues_ = queryParamValues;
};
/**
* @override
*/
goog.tweak.BooleanGroup.prototype.getNewValueEncoded = function() {
this.ensureInitialized();
var nonDefaultValues = [];
// Sort the keys so that the generate value is stable.
var keys = goog.object.getKeys(this.entriesByToken_);
keys.sort();
for (var i = 0, entry; entry = this.entriesByToken_[keys[i]]; ++i) {
var encodedValue = entry.getNewValueEncoded();
if (encodedValue != null) {
nonDefaultValues.push((entry.getNewValue() ? '' : '-') +
entry.getToken());
}
}
return nonDefaultValues.length ? nonDefaultValues.join(',') : null;
};
/**
* A registry action (a button).
* @param {string} id The ID for the setting.
* @param {string} description A description of what the setting does.
* @param {!Function} callback Function to call when the button is clicked.
* @constructor
* @extends {goog.tweak.BaseEntry}
*/
goog.tweak.ButtonAction = function(id, description, callback) {
goog.tweak.BaseEntry.call(this, id, description);
this.addCallback(callback);
this.setRestartRequired(false);
};
goog.inherits(goog.tweak.ButtonAction, goog.tweak.BaseEntry);
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Names of standard colors with their associated hex values.
*/
goog.provide('goog.color.names');
/**
* A map that contains a lot of colors that are recognised by various browsers.
* This list is way larger than the minimal one dictated by W3C.
* The keys of this map are the lowercase "readable" names of the colors, while
* the values are the "hex" values.
*/
goog.color.names = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgreen': '#006400',
'darkgrey': '#a9a9a9',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkslategrey': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dimgrey': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'grey': '#808080',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgray': '#d3d3d3',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightslategrey': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370db',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#db7093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'slategrey': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities related to color and color conversion.
*/
goog.provide('goog.color');
goog.require('goog.color.names');
goog.require('goog.math');
/**
* RGB color representation. An array containing three elements [r, g, b],
* each an integer in [0, 255], representing the red, green, and blue components
* of the color respectively.
* @typedef {Array.<number>}
*/
goog.color.Rgb;
/**
* HSV color representation. An array containing three elements [h, s, v]:
* h (hue) must be an integer in [0, 360], cyclic.
* s (saturation) must be a number in [0, 1].
* v (value/brightness) must be an integer in [0, 255].
* @typedef {Array.<number>}
*/
goog.color.Hsv;
/**
* HSL color representation. An array containing three elements [h, s, l]:
* h (hue) must be an integer in [0, 360], cyclic.
* s (saturation) must be a number in [0, 1].
* l (lightness) must be a number in [0, 1].
* @typedef {Array.<number>}
*/
goog.color.Hsl;
/**
* Parses a color out of a string.
* @param {string} str Color in some format.
* @return {Object} Contains two properties: 'hex', which is a string containing
* a hex representation of the color, as well as 'type', which is a string
* containing the type of color format passed in ('hex', 'rgb', 'named').
*/
goog.color.parse = function(str) {
var result = {};
str = String(str);
var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
if (goog.color.isValidHexColor_(maybeHex)) {
result.hex = goog.color.normalizeHex(maybeHex);
result.type = 'hex';
return result;
} else {
var rgb = goog.color.isValidRgbColor_(str);
if (rgb.length) {
result.hex = goog.color.rgbArrayToHex(rgb);
result.type = 'rgb';
return result;
} else if (goog.color.names) {
var hex = goog.color.names[str.toLowerCase()];
if (hex) {
result.hex = hex;
result.type = 'named';
return result;
}
}
}
throw Error(str + ' is not a valid color string');
};
/**
* Determines if the given string can be parsed as a color.
* {@see goog.color.parse}.
* @param {string} str Potential color string.
* @return {boolean} True if str is in a format that can be parsed to a color.
*/
goog.color.isValidColor = function(str) {
var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
return !!(goog.color.isValidHexColor_(maybeHex) ||
goog.color.isValidRgbColor_(str).length ||
goog.color.names && goog.color.names[str.toLowerCase()]);
};
/**
* Parses red, green, blue components out of a valid rgb color string.
* Throws Error if the color string is invalid.
* @param {string} str RGB representation of a color.
* {@see goog.color.isValidRgbColor_}.
* @return {!goog.color.Rgb} rgb representation of the color.
*/
goog.color.parseRgb = function(str) {
var rgb = goog.color.isValidRgbColor_(str);
if (!rgb.length) {
throw Error(str + ' is not a valid RGB color');
}
return rgb;
};
/**
* Converts a hex representation of a color to RGB.
* @param {string} hexColor Color to convert.
* @return {string} string of the form 'rgb(R,G,B)' which can be used in
* styles.
*/
goog.color.hexToRgbStyle = function(hexColor) {
return goog.color.rgbStyle_(goog.color.hexToRgb(hexColor));
};
/**
* Regular expression for extracting the digits in a hex color triplet.
* @type {RegExp}
* @private
*/
goog.color.hexTripletRe_ = /#(.)(.)(.)/;
/**
* Normalize an hex representation of a color
* @param {string} hexColor an hex color string.
* @return {string} hex color in the format '#rrggbb' with all lowercase
* literals.
*/
goog.color.normalizeHex = function(hexColor) {
if (!goog.color.isValidHexColor_(hexColor)) {
throw Error("'" + hexColor + "' is not a valid hex color");
}
if (hexColor.length == 4) { // of the form #RGB
hexColor = hexColor.replace(goog.color.hexTripletRe_, '#$1$1$2$2$3$3');
}
return hexColor.toLowerCase();
};
/**
* Converts a hex representation of a color to RGB.
* @param {string} hexColor Color to convert.
* @return {!goog.color.Rgb} rgb representation of the color.
*/
goog.color.hexToRgb = function(hexColor) {
hexColor = goog.color.normalizeHex(hexColor);
var r = parseInt(hexColor.substr(1, 2), 16);
var g = parseInt(hexColor.substr(3, 2), 16);
var b = parseInt(hexColor.substr(5, 2), 16);
return [r, g, b];
};
/**
* Converts a color from RGB to hex representation.
* @param {number} r Amount of red, int between 0 and 255.
* @param {number} g Amount of green, int between 0 and 255.
* @param {number} b Amount of blue, int between 0 and 255.
* @return {string} hex representation of the color.
*/
goog.color.rgbToHex = function(r, g, b) {
r = Number(r);
g = Number(g);
b = Number(b);
if (isNaN(r) || r < 0 || r > 255 ||
isNaN(g) || g < 0 || g > 255 ||
isNaN(b) || b < 0 || b > 255) {
throw Error('"(' + r + ',' + g + ',' + b + '") is not a valid RGB color');
}
var hexR = goog.color.prependZeroIfNecessaryHelper(r.toString(16));
var hexG = goog.color.prependZeroIfNecessaryHelper(g.toString(16));
var hexB = goog.color.prependZeroIfNecessaryHelper(b.toString(16));
return '#' + hexR + hexG + hexB;
};
/**
* Converts a color from RGB to hex representation.
* @param {goog.color.Rgb} rgb rgb representation of the color.
* @return {string} hex representation of the color.
*/
goog.color.rgbArrayToHex = function(rgb) {
return goog.color.rgbToHex(rgb[0], rgb[1], rgb[2]);
};
/**
* Converts a color from RGB color space to HSL color space.
* Modified from {@link http://en.wikipedia.org/wiki/HLS_color_space}.
* @param {number} r Value of red, in [0, 255].
* @param {number} g Value of green, in [0, 255].
* @param {number} b Value of blue, in [0, 255].
* @return {!goog.color.Hsl} hsl representation of the color.
*/
goog.color.rgbToHsl = function(r, g, b) {
// First must normalize r, g, b to be between 0 and 1.
var normR = r / 255;
var normG = g / 255;
var normB = b / 255;
var max = Math.max(normR, normG, normB);
var min = Math.min(normR, normG, normB);
var h = 0;
var s = 0;
// Luminosity is the average of the max and min rgb color intensities.
var l = 0.5 * (max + min);
// The hue and saturation are dependent on which color intensity is the max.
// If max and min are equal, the color is gray and h and s should be 0.
if (max != min) {
if (max == normR) {
h = 60 * (normG - normB) / (max - min);
} else if (max == normG) {
h = 60 * (normB - normR) / (max - min) + 120;
} else if (max == normB) {
h = 60 * (normR - normG) / (max - min) + 240;
}
if (0 < l && l <= 0.5) {
s = (max - min) / (2 * l);
} else {
s = (max - min) / (2 - 2 * l);
}
}
// Make sure the hue falls between 0 and 360.
return [Math.round(h + 360) % 360, s, l];
};
/**
* Converts a color from RGB color space to HSL color space.
* @param {goog.color.Rgb} rgb rgb representation of the color.
* @return {!goog.color.Hsl} hsl representation of the color.
*/
goog.color.rgbArrayToHsl = function(rgb) {
return goog.color.rgbToHsl(rgb[0], rgb[1], rgb[2]);
};
/**
* Helper for hslToRgb.
* @param {number} v1 Helper variable 1.
* @param {number} v2 Helper variable 2.
* @param {number} vH Helper variable 3.
* @return {number} Appropriate RGB value, given the above.
* @private
*/
goog.color.hueToRgb_ = function(v1, v2, vH) {
if (vH < 0) {
vH += 1;
} else if (vH > 1) {
vH -= 1;
}
if ((6 * vH) < 1) {
return (v1 + (v2 - v1) * 6 * vH);
} else if (2 * vH < 1) {
return v2;
} else if (3 * vH < 2) {
return (v1 + (v2 - v1) * ((2 / 3) - vH) * 6);
}
return v1;
};
/**
* Converts a color from HSL color space to RGB color space.
* Modified from {@link http://www.easyrgb.com/math.html}
* @param {number} h Hue, in [0, 360].
* @param {number} s Saturation, in [0, 1].
* @param {number} l Luminosity, in [0, 1].
* @return {!goog.color.Rgb} rgb representation of the color.
*/
goog.color.hslToRgb = function(h, s, l) {
var r = 0;
var g = 0;
var b = 0;
var normH = h / 360; // normalize h to fall in [0, 1]
if (s == 0) {
r = g = b = l * 255;
} else {
var temp1 = 0;
var temp2 = 0;
if (l < 0.5) {
temp2 = l * (1 + s);
} else {
temp2 = l + s - (s * l);
}
temp1 = 2 * l - temp2;
r = 255 * goog.color.hueToRgb_(temp1, temp2, normH + (1 / 3));
g = 255 * goog.color.hueToRgb_(temp1, temp2, normH);
b = 255 * goog.color.hueToRgb_(temp1, temp2, normH - (1 / 3));
}
return [Math.round(r), Math.round(g), Math.round(b)];
};
/**
* Converts a color from HSL color space to RGB color space.
* @param {goog.color.Hsl} hsl hsl representation of the color.
* @return {!goog.color.Rgb} rgb representation of the color.
*/
goog.color.hslArrayToRgb = function(hsl) {
return goog.color.hslToRgb(hsl[0], hsl[1], hsl[2]);
};
/**
* Helper for isValidHexColor_.
* @type {RegExp}
* @private
*/
goog.color.validHexColorRe_ = /^#(?:[0-9a-f]{3}){1,2}$/i;
/**
* Checks if a string is a valid hex color. We expect strings of the format
* #RRGGBB (ex: #1b3d5f) or #RGB (ex: #3CA == #33CCAA).
* @param {string} str String to check.
* @return {boolean} Whether the string is a valid hex color.
* @private
*/
goog.color.isValidHexColor_ = function(str) {
return goog.color.validHexColorRe_.test(str);
};
/**
* Helper for isNormalizedHexColor_.
* @type {RegExp}
* @private
*/
goog.color.normalizedHexColorRe_ = /^#[0-9a-f]{6}$/;
/**
* Checks if a string is a normalized hex color.
* We expect strings of the format #RRGGBB (ex: #1b3d5f)
* using only lowercase letters.
* @param {string} str String to check.
* @return {boolean} Whether the string is a normalized hex color.
* @private
*/
goog.color.isNormalizedHexColor_ = function(str) {
return goog.color.normalizedHexColorRe_.test(str);
};
/**
* Regular expression for matching and capturing RGB style strings. Helper for
* isValidRgbColor_.
* @type {RegExp}
* @private
*/
goog.color.rgbColorRe_ =
/^(?:rgb)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\)$/i;
/**
* Checks if a string is a valid rgb color. We expect strings of the format
* '(r, g, b)', or 'rgb(r, g, b)', where each color component is an int in
* [0, 255].
* @param {string} str String to check.
* @return {!goog.color.Rgb} the rgb representation of the color if it is
* a valid color, or the empty array otherwise.
* @private
*/
goog.color.isValidRgbColor_ = function(str) {
// Each component is separate (rather than using a repeater) so we can
// capture the match. Also, we explicitly set each component to be either 0,
// or start with a non-zero, to prevent octal numbers from slipping through.
var regExpResultArray = str.match(goog.color.rgbColorRe_);
if (regExpResultArray) {
var r = Number(regExpResultArray[1]);
var g = Number(regExpResultArray[2]);
var b = Number(regExpResultArray[3]);
if (r >= 0 && r <= 255 &&
g >= 0 && g <= 255 &&
b >= 0 && b <= 255) {
return [r, g, b];
}
}
return [];
};
/**
* Takes a hex value and prepends a zero if it's a single digit.
* Small helper method for use by goog.color and friends.
* @param {string} hex Hex value to prepend if single digit.
* @return {string} hex value prepended with zero if it was single digit,
* otherwise the same value that was passed in.
*/
goog.color.prependZeroIfNecessaryHelper = function(hex) {
return hex.length == 1 ? '0' + hex : hex;
};
/**
* Takes a string a prepends a '#' sign if one doesn't exist.
* Small helper method for use by goog.color and friends.
* @param {string} str String to check.
* @return {string} The value passed in, prepended with a '#' if it didn't
* already have one.
*/
goog.color.prependHashIfNecessaryHelper = function(str) {
return str.charAt(0) == '#' ? str : '#' + str;
};
/**
* Takes an array of [r, g, b] and converts it into a string appropriate for
* CSS styles.
* @param {goog.color.Rgb} rgb rgb representation of the color.
* @return {string} string of the form 'rgb(r,g,b)'.
* @private
*/
goog.color.rgbStyle_ = function(rgb) {
return 'rgb(' + rgb.join(',') + ')';
};
/**
* Converts an HSV triplet to an RGB array. V is brightness because b is
* reserved for blue in RGB.
* @param {number} h Hue value in [0, 360].
* @param {number} s Saturation value in [0, 1].
* @param {number} brightness brightness in [0, 255].
* @return {!goog.color.Rgb} rgb representation of the color.
*/
goog.color.hsvToRgb = function(h, s, brightness) {
var red = 0;
var green = 0;
var blue = 0;
if (s == 0) {
red = brightness;
green = brightness;
blue = brightness;
} else {
var sextant = Math.floor(h / 60);
var remainder = (h / 60) - sextant;
var val1 = brightness * (1 - s);
var val2 = brightness * (1 - (s * remainder));
var val3 = brightness * (1 - (s * (1 - remainder)));
switch (sextant) {
case 1:
red = val2;
green = brightness;
blue = val1;
break;
case 2:
red = val1;
green = brightness;
blue = val3;
break;
case 3:
red = val1;
green = val2;
blue = brightness;
break;
case 4:
red = val3;
green = val1;
blue = brightness;
break;
case 5:
red = brightness;
green = val1;
blue = val2;
break;
case 6:
case 0:
red = brightness;
green = val3;
blue = val1;
break;
}
}
return [Math.floor(red), Math.floor(green), Math.floor(blue)];
};
/**
* Converts from RGB values to an array of HSV values.
* @param {number} red Red value in [0, 255].
* @param {number} green Green value in [0, 255].
* @param {number} blue Blue value in [0, 255].
* @return {!goog.color.Hsv} hsv representation of the color.
*/
goog.color.rgbToHsv = function(red, green, blue) {
var max = Math.max(Math.max(red, green), blue);
var min = Math.min(Math.min(red, green), blue);
var hue;
var saturation;
var value = max;
if (min == max) {
hue = 0;
saturation = 0;
} else {
var delta = (max - min);
saturation = delta / max;
if (red == max) {
hue = (green - blue) / delta;
} else if (green == max) {
hue = 2 + ((blue - red) / delta);
} else {
hue = 4 + ((red - green) / delta);
}
hue *= 60;
if (hue < 0) {
hue += 360;
}
if (hue > 360) {
hue -= 360;
}
}
return [hue, saturation, value];
};
/**
* Converts from an array of RGB values to an array of HSV values.
* @param {goog.color.Rgb} rgb rgb representation of the color.
* @return {!goog.color.Hsv} hsv representation of the color.
*/
goog.color.rgbArrayToHsv = function(rgb) {
return goog.color.rgbToHsv(rgb[0], rgb[1], rgb[2]);
};
/**
* Converts an HSV triplet to an RGB array.
* @param {goog.color.Hsv} hsv hsv representation of the color.
* @return {!goog.color.Rgb} rgb representation of the color.
*/
goog.color.hsvArrayToRgb = function(hsv) {
return goog.color.hsvToRgb(hsv[0], hsv[1], hsv[2]);
};
/**
* Converts a hex representation of a color to HSL.
* @param {string} hex Color to convert.
* @return {!goog.color.Hsv} hsv representation of the color.
*/
goog.color.hexToHsl = function(hex) {
var rgb = goog.color.hexToRgb(hex);
return goog.color.rgbToHsl(rgb[0], rgb[1], rgb[2]);
};
/**
* Converts from h,s,l values to a hex string
* @param {number} h Hue, in [0, 360].
* @param {number} s Saturation, in [0, 1].
* @param {number} l Luminosity, in [0, 1].
* @return {string} hex representation of the color.
*/
goog.color.hslToHex = function(h, s, l) {
return goog.color.rgbArrayToHex(goog.color.hslToRgb(h, s, l));
};
/**
* Converts from an hsl array to a hex string
* @param {goog.color.Hsl} hsl hsl representation of the color.
* @return {string} hex representation of the color.
*/
goog.color.hslArrayToHex = function(hsl) {
return goog.color.rgbArrayToHex(goog.color.hslToRgb(hsl[0], hsl[1], hsl[2]));
};
/**
* Converts a hex representation of a color to HSV
* @param {string} hex Color to convert.
* @return {!goog.color.Hsv} hsv representation of the color.
*/
goog.color.hexToHsv = function(hex) {
return goog.color.rgbArrayToHsv(goog.color.hexToRgb(hex));
};
/**
* Converts from h,s,v values to a hex string
* @param {number} h Hue, in [0, 360].
* @param {number} s Saturation, in [0, 1].
* @param {number} v Value, in [0, 255].
* @return {string} hex representation of the color.
*/
goog.color.hsvToHex = function(h, s, v) {
return goog.color.rgbArrayToHex(goog.color.hsvToRgb(h, s, v));
};
/**
* Converts from an HSV array to a hex string
* @param {goog.color.Hsv} hsv hsv representation of the color.
* @return {string} hex representation of the color.
*/
goog.color.hsvArrayToHex = function(hsv) {
return goog.color.hsvToHex(hsv[0], hsv[1], hsv[2]);
};
/**
* Calculates the Euclidean distance between two color vectors on an HSL sphere.
* A demo of the sphere can be found at:
* http://en.wikipedia.org/wiki/HSL_color_space
* In short, a vector for color (H, S, L) in this system can be expressed as
* (S*L'*cos(2*PI*H), S*L'*sin(2*PI*H), L), where L' = abs(L - 0.5), and we
* simply calculate the 1-2 distance using these coordinates
* @param {goog.color.Hsl} hsl1 First color in hsl representation.
* @param {goog.color.Hsl} hsl2 Second color in hsl representation.
* @return {number} Distance between the two colors, in the range [0, 1].
*/
goog.color.hslDistance = function(hsl1, hsl2) {
var sl1, sl2;
if (hsl1[2] <= 0.5) {
sl1 = hsl1[1] * hsl1[2];
} else {
sl1 = hsl1[1] * (1.0 - hsl1[2]);
}
if (hsl2[2] <= 0.5) {
sl2 = hsl2[1] * hsl2[2];
} else {
sl2 = hsl2[1] * (1.0 - hsl2[2]);
}
var h1 = hsl1[0] / 360.0;
var h2 = hsl2[0] / 360.0;
var dh = (h1 - h2) * 2.0 * Math.PI;
return (hsl1[2] - hsl2[2]) * (hsl1[2] - hsl2[2]) +
sl1 * sl1 + sl2 * sl2 - 2 * sl1 * sl2 * Math.cos(dh);
};
/**
* Blend two colors together, using the specified factor to indicate the weight
* given to the first color
* @param {goog.color.Rgb} rgb1 First color represented in rgb.
* @param {goog.color.Rgb} rgb2 Second color represented in rgb.
* @param {number} factor The weight to be given to rgb1 over rgb2. Values
* should be in the range [0, 1]. If less than 0, factor will be set to 0.
* If greater than 1, factor will be set to 1.
* @return {!goog.color.Rgb} Combined color represented in rgb.
*/
goog.color.blend = function(rgb1, rgb2, factor) {
factor = goog.math.clamp(factor, 0, 1);
return [
Math.round(factor * rgb1[0] + (1.0 - factor) * rgb2[0]),
Math.round(factor * rgb1[1] + (1.0 - factor) * rgb2[1]),
Math.round(factor * rgb1[2] + (1.0 - factor) * rgb2[2])
];
};
/**
* Adds black to the specified color, darkening it
* @param {goog.color.Rgb} rgb rgb representation of the color.
* @param {number} factor Number in the range [0, 1]. 0 will do nothing, while
* 1 will return black. If less than 0, factor will be set to 0. If greater
* than 1, factor will be set to 1.
* @return {!goog.color.Rgb} Combined rgb color.
*/
goog.color.darken = function(rgb, factor) {
var black = [0, 0, 0];
return goog.color.blend(black, rgb, factor);
};
/**
* Adds white to the specified color, lightening it
* @param {goog.color.Rgb} rgb rgb representation of the color.
* @param {number} factor Number in the range [0, 1]. 0 will do nothing, while
* 1 will return white. If less than 0, factor will be set to 0. If greater
* than 1, factor will be set to 1.
* @return {!goog.color.Rgb} Combined rgb color.
*/
goog.color.lighten = function(rgb, factor) {
var white = [255, 255, 255];
return goog.color.blend(white, rgb, factor);
};
/**
* Find the "best" (highest-contrast) of the suggested colors for the prime
* color. Uses W3C formula for judging readability and visual accessibility:
* http://www.w3.org/TR/AERT#color-contrast
* @param {goog.color.Rgb} prime Color represented as a rgb array.
* @param {Array.<goog.color.Rgb>} suggestions Array of colors,
* each representing a rgb array.
* @return {!goog.color.Rgb} Highest-contrast color represented by an array..
*/
goog.color.highContrast = function(prime, suggestions) {
var suggestionsWithDiff = [];
for (var i = 0; i < suggestions.length; i++) {
suggestionsWithDiff.push({
color: suggestions[i],
diff: goog.color.yiqBrightnessDiff_(suggestions[i], prime) +
goog.color.colorDiff_(suggestions[i], prime)
});
}
suggestionsWithDiff.sort(function(a, b) {
return b.diff - a.diff;
});
return suggestionsWithDiff[0].color;
};
/**
* Calculate brightness of a color according to YIQ formula (brightness is Y).
* More info on YIQ here: http://en.wikipedia.org/wiki/YIQ. Helper method for
* goog.color.highContrast()
* @param {goog.color.Rgb} rgb Color represented by a rgb array.
* @return {number} brightness (Y).
* @private
*/
goog.color.yiqBrightness_ = function(rgb) {
return Math.round((rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000);
};
/**
* Calculate difference in brightness of two colors. Helper method for
* goog.color.highContrast()
* @param {goog.color.Rgb} rgb1 Color represented by a rgb array.
* @param {goog.color.Rgb} rgb2 Color represented by a rgb array.
* @return {number} Brightness difference.
* @private
*/
goog.color.yiqBrightnessDiff_ = function(rgb1, rgb2) {
return Math.abs(goog.color.yiqBrightness_(rgb1) -
goog.color.yiqBrightness_(rgb2));
};
/**
* Calculate color difference between two colors. Helper method for
* goog.color.highContrast()
* @param {goog.color.Rgb} rgb1 Color represented by a rgb array.
* @param {goog.color.Rgb} rgb2 Color represented by a rgb array.
* @return {number} Color difference.
* @private
*/
goog.color.colorDiff_ = function(rgb1, rgb2) {
return Math.abs(rgb1[0] - rgb2[0]) + Math.abs(rgb1[1] - rgb2[1]) +
Math.abs(rgb1[2] - rgb2[2]);
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities related to alpha/transparent colors and alpha color
* conversion.
*/
goog.provide('goog.color.alpha');
goog.require('goog.color');
/**
* Parses an alpha color out of a string.
* @param {string} str Color in some format.
* @return {Object} Contains two properties: 'hex', which is a string containing
* a hex representation of the color, as well as 'type', which is a string
* containing the type of color format passed in ('hex', 'rgb', 'named').
*/
goog.color.alpha.parse = function(str) {
var result = {};
str = String(str);
var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
if (goog.color.alpha.isValidAlphaHexColor_(maybeHex)) {
result.hex = goog.color.alpha.normalizeAlphaHex_(maybeHex);
result.type = 'hex';
return result;
} else {
var rgba = goog.color.alpha.isValidRgbaColor_(str);
if (rgba.length) {
result.hex = goog.color.alpha.rgbaArrayToHex(rgba);
result.type = 'rgba';
return result;
} else {
var hsla = goog.color.alpha.isValidHslaColor_(str);
if (hsla.length) {
result.hex = goog.color.alpha.hslaArrayToHex(hsla);
result.type = 'hsla';
return result;
}
}
}
throw Error(str + ' is not a valid color string');
};
/**
* Converts a hex representation of a color to RGBA.
* @param {string} hexColor Color to convert.
* @return {string} string of the form 'rgba(R,G,B,A)' which can be used in
* styles.
*/
goog.color.alpha.hexToRgbaStyle = function(hexColor) {
return goog.color.alpha.rgbaStyle_(goog.color.alpha.hexToRgba(hexColor));
};
/**
* Gets the hex color part of an alpha hex color. For example, from '#abcdef55'
* return '#abcdef'.
* @param {string} colorWithAlpha The alpha hex color to get the hex color from.
* @return {string} The hex color where the alpha part has been stripped off.
*/
goog.color.alpha.extractHexColor = function(colorWithAlpha) {
if (goog.color.alpha.isValidAlphaHexColor_(colorWithAlpha)) {
var fullColor = goog.color.prependHashIfNecessaryHelper(colorWithAlpha);
var normalizedColor = goog.color.alpha.normalizeAlphaHex_(fullColor);
return normalizedColor.substring(0, 7);
} else {
throw Error(colorWithAlpha + ' is not a valid 8-hex color string');
}
};
/**
* Gets the alpha color part of an alpha hex color. For example, from
* '#abcdef55' return '55'. The result is guaranteed to be two characters long.
* @param {string} colorWithAlpha The alpha hex color to get the hex color from.
* @return {string} The hex color where the alpha part has been stripped off.
*/
goog.color.alpha.extractAlpha = function(colorWithAlpha) {
if (goog.color.alpha.isValidAlphaHexColor_(colorWithAlpha)) {
var fullColor = goog.color.prependHashIfNecessaryHelper(colorWithAlpha);
var normalizedColor = goog.color.alpha.normalizeAlphaHex_(fullColor);
return normalizedColor.substring(7, 9);
} else {
throw Error(colorWithAlpha + ' is not a valid 8-hex color string');
}
};
/**
* Regular expression for extracting the digits in a hex color quadruplet.
* @type {RegExp}
* @private
*/
goog.color.alpha.hexQuadrupletRe_ = /#(.)(.)(.)(.)/;
/**
* Normalize a hex representation of an alpha color.
* @param {string} hexColor an alpha hex color string.
* @return {string} hex color in the format '#rrggbbaa' with all lowercase
* literals.
* @private
*/
goog.color.alpha.normalizeAlphaHex_ = function(hexColor) {
if (!goog.color.alpha.isValidAlphaHexColor_(hexColor)) {
throw Error("'" + hexColor + "' is not a valid alpha hex color");
}
if (hexColor.length == 5) { // of the form #RGBA
hexColor = hexColor.replace(goog.color.alpha.hexQuadrupletRe_,
'#$1$1$2$2$3$3$4$4');
}
return hexColor.toLowerCase();
};
/**
* Converts an 8-hex representation of a color to RGBA.
* @param {string} hexColor Color to convert.
* @return {Array} array containing [r, g, b] as ints in [0, 255].
*/
goog.color.alpha.hexToRgba = function(hexColor) {
// TODO(user): Enhance code sharing with goog.color, for example by
// adding a goog.color.genericHexToRgb method.
hexColor = goog.color.alpha.normalizeAlphaHex_(hexColor);
var r = parseInt(hexColor.substr(1, 2), 16);
var g = parseInt(hexColor.substr(3, 2), 16);
var b = parseInt(hexColor.substr(5, 2), 16);
var a = parseInt(hexColor.substr(7, 2), 16);
return [r, g, b, a / 255];
};
/**
* Converts a color from RGBA to hex representation.
* @param {number} r Amount of red, int between 0 and 255.
* @param {number} g Amount of green, int between 0 and 255.
* @param {number} b Amount of blue, int between 0 and 255.
* @param {number} a Amount of alpha, float between 0 and 1.
* @return {string} hex representation of the color.
*/
goog.color.alpha.rgbaToHex = function(r, g, b, a) {
var intAlpha = Math.floor(a * 255);
if (isNaN(intAlpha) || intAlpha < 0 || intAlpha > 255) {
// TODO(user): The CSS spec says the value should be clamped.
throw Error('"(' + r + ',' + g + ',' + b + ',' + a +
'") is not a valid RGBA color');
}
var hexA = goog.color.prependZeroIfNecessaryHelper(intAlpha.toString(16));
return goog.color.rgbToHex(r, g, b) + hexA;
};
/**
* Converts a color from HSLA to hex representation.
* @param {number} h Amount of hue, int between 0 and 360.
* @param {number} s Amount of saturation, int between 0 and 100.
* @param {number} l Amount of lightness, int between 0 and 100.
* @param {number} a Amount of alpha, float between 0 and 1.
* @return {string} hex representation of the color.
*/
goog.color.alpha.hslaToHex = function(h, s, l, a) {
var intAlpha = Math.floor(a * 255);
if (isNaN(intAlpha) || intAlpha < 0 || intAlpha > 255) {
// TODO(user): The CSS spec says the value should be clamped.
throw Error('"(' + h + ',' + s + ',' + l + ',' + a +
'") is not a valid HSLA color');
}
var hexA = goog.color.prependZeroIfNecessaryHelper(intAlpha.toString(16));
return goog.color.hslToHex(h, s / 100, l / 100) + hexA;
};
/**
* Converts a color from RGBA to hex representation.
* @param {Array.<number>} rgba Array of [r, g, b, a], with r, g, b in [0, 255]
* and a in [0, 1].
* @return {string} hex representation of the color.
*/
goog.color.alpha.rgbaArrayToHex = function(rgba) {
return goog.color.alpha.rgbaToHex(rgba[0], rgba[1], rgba[2], rgba[3]);
};
/**
* Converts a color from RGBA to an RGBA style string.
* @param {number} r Value of red, in [0, 255].
* @param {number} g Value of green, in [0, 255].
* @param {number} b Value of blue, in [0, 255].
* @param {number} a Value of alpha, in [0, 1].
* @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
*/
goog.color.alpha.rgbaToRgbaStyle = function(r, g, b, a) {
if (isNaN(r) || r < 0 || r > 255 ||
isNaN(g) || g < 0 || g > 255 ||
isNaN(b) || b < 0 || b > 255 ||
isNaN(a) || a < 0 || a > 1) {
throw Error('"(' + r + ',' + g + ',' + b + ',' + a +
')" is not a valid RGBA color');
}
return goog.color.alpha.rgbaStyle_([r, g, b, a]);
};
/**
* Converts a color from RGBA to an RGBA style string.
* @param {(Array.<number>|Float32Array)} rgba Array of [r, g, b, a],
* with r, g, b in [0, 255] and a in [0, 1].
* @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
*/
goog.color.alpha.rgbaArrayToRgbaStyle = function(rgba) {
return goog.color.alpha.rgbaToRgbaStyle(rgba[0], rgba[1], rgba[2], rgba[3]);
};
/**
* Converts a color from HSLA to hex representation.
* @param {Array.<number>} hsla Array of [h, s, l, a], where h is an integer in
* [0, 360], s and l are integers in [0, 100], and a is in [0, 1].
* @return {string} hex representation of the color, such as '#af457eff'.
*/
goog.color.alpha.hslaArrayToHex = function(hsla) {
return goog.color.alpha.hslaToHex(hsla[0], hsla[1], hsla[2], hsla[3]);
};
/**
* Converts a color from HSLA to an RGBA style string.
* @param {Array.<number>} hsla Array of [h, s, l, a], where h is and integer in
* [0, 360], s and l are integers in [0, 100], and a is in [0, 1].
* @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
*/
goog.color.alpha.hslaArrayToRgbaStyle = function(hsla) {
return goog.color.alpha.hslaToRgbaStyle(hsla[0], hsla[1], hsla[2], hsla[3]);
};
/**
* Converts a color from HSLA to an RGBA style string.
* @param {number} h Amount of hue, int between 0 and 360.
* @param {number} s Amount of saturation, int between 0 and 100.
* @param {number} l Amount of lightness, int between 0 and 100.
* @param {number} a Amount of alpha, float between 0 and 1.
* @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
* styles.
*/
goog.color.alpha.hslaToRgbaStyle = function(h, s, l, a) {
return goog.color.alpha.rgbaStyle_(goog.color.alpha.hslaToRgba(h, s, l, a));
};
/**
* Converts a color from HSLA color space to RGBA color space.
* @param {number} h Amount of hue, int between 0 and 360.
* @param {number} s Amount of saturation, int between 0 and 100.
* @param {number} l Amount of lightness, int between 0 and 100.
* @param {number} a Amount of alpha, float between 0 and 1.
* @return {Array.<number>} [r, g, b, a] values for the color, where r, g, b
* are integers in [0, 255] and a is a float in [0, 1].
*/
goog.color.alpha.hslaToRgba = function(h, s, l, a) {
return goog.color.hslToRgb(h, s / 100, l / 100).concat(a);
};
/**
* Converts a color from RGBA color space to HSLA color space.
* Modified from {@link http://en.wikipedia.org/wiki/HLS_color_space}.
* @param {number} r Value of red, in [0, 255].
* @param {number} g Value of green, in [0, 255].
* @param {number} b Value of blue, in [0, 255].
* @param {number} a Value of alpha, in [0, 255].
* @return {Array.<number>} [h, s, l, a] values for the color, with h an int in
* [0, 360] and s, l and a in [0, 1].
*/
goog.color.alpha.rgbaToHsla = function(r, g, b, a) {
return goog.color.rgbToHsl(r, g, b).concat(a);
};
/**
* Converts a color from RGBA color space to HSLA color space.
* @param {Array.<number>} rgba [r, g, b, a] values for the color, each in
* [0, 255].
* @return {Array.<number>} [h, s, l, a] values for the color, with h in
* [0, 360] and s, l and a in [0, 1].
*/
goog.color.alpha.rgbaArrayToHsla = function(rgba) {
return goog.color.alpha.rgbaToHsla(rgba[0], rgba[1], rgba[2], rgba[3]);
};
/**
* Helper for isValidAlphaHexColor_.
* @type {RegExp}
* @private
*/
goog.color.alpha.validAlphaHexColorRe_ = /^#(?:[0-9a-f]{4}){1,2}$/i;
/**
* Checks if a string is a valid alpha hex color. We expect strings of the
* format #RRGGBBAA (ex: #1b3d5f5b) or #RGBA (ex: #3CAF == #33CCAAFF).
* @param {string} str String to check.
* @return {boolean} Whether the string is a valid alpha hex color.
* @private
*/
// TODO(user): Support percentages when goog.color also supports them.
goog.color.alpha.isValidAlphaHexColor_ = function(str) {
return goog.color.alpha.validAlphaHexColorRe_.test(str);
};
/**
* Helper for isNormalizedAlphaHexColor_.
* @type {RegExp}
* @private
*/
goog.color.alpha.normalizedAlphaHexColorRe_ = /^#[0-9a-f]{8}$/;
/**
* Checks if a string is a normalized alpha hex color.
* We expect strings of the format #RRGGBBAA (ex: #1b3d5f5b)
* using only lowercase letters.
* @param {string} str String to check.
* @return {boolean} Whether the string is a normalized hex color.
* @private
*/
goog.color.alpha.isNormalizedAlphaHexColor_ = function(str) {
return goog.color.alpha.normalizedAlphaHexColorRe_.test(str);
};
/**
* Regular expression for matching and capturing RGBA style strings. Helper for
* isValidRgbaColor_.
* @type {RegExp}
* @private
*/
goog.color.alpha.rgbaColorRe_ =
/^(?:rgba)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|1|0\.\d{0,10})\)$/i;
/**
* Regular expression for matching and capturing HSLA style strings. Helper for
* isValidHslaColor_.
* @type {RegExp}
* @private
*/
goog.color.alpha.hslaColorRe_ =
/^(?:hsla)\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\%,\s?(0|[1-9]\d{0,2})\%,\s?(0|1|0\.\d{0,10})\)$/i;
/**
* Checks if a string is a valid rgba color. We expect strings of the format
* '(r, g, b, a)', or 'rgba(r, g, b, a)', where r, g, b are ints in [0, 255]
* and a is a float in [0, 1].
* @param {string} str String to check.
* @return {Array.<number>} the integers [r, g, b, a] for valid colors or the
* empty array for invalid colors.
* @private
*/
goog.color.alpha.isValidRgbaColor_ = function(str) {
// Each component is separate (rather than using a repeater) so we can
// capture the match. Also, we explicitly set each component to be either 0,
// or start with a non-zero, to prevent octal numbers from slipping through.
var regExpResultArray = str.match(goog.color.alpha.rgbaColorRe_);
if (regExpResultArray) {
var r = Number(regExpResultArray[1]);
var g = Number(regExpResultArray[2]);
var b = Number(regExpResultArray[3]);
var a = Number(regExpResultArray[4]);
if (r >= 0 && r <= 255 &&
g >= 0 && g <= 255 &&
b >= 0 && b <= 255 &&
a >= 0 && a <= 1) {
return [r, g, b, a];
}
}
return [];
};
/**
* Checks if a string is a valid hsla color. We expect strings of the format
* 'hsla(h, s, l, a)', where s in an int in [0, 360], s and l are percentages
* between 0 and 100 such as '50%' or '70%', and a is a float in [0, 1].
* @param {string} str String to check.
* @return {Array.<number>} the integers [h, s, l, a] for valid colors or the
* empty array for invalid colors.
* @private
*/
goog.color.alpha.isValidHslaColor_ = function(str) {
// Each component is separate (rather than using a repeater) so we can
// capture the match. Also, we explicitly set each component to be either 0,
// or start with a non-zero, to prevent octal numbers from slipping through.
var regExpResultArray = str.match(goog.color.alpha.hslaColorRe_);
if (regExpResultArray) {
var h = Number(regExpResultArray[1]);
var s = Number(regExpResultArray[2]);
var l = Number(regExpResultArray[3]);
var a = Number(regExpResultArray[4]);
if (h >= 0 && h <= 360 &&
s >= 0 && s <= 100 &&
l >= 0 && l <= 100 &&
a >= 0 && a <= 1) {
return [h, s, l, a];
}
}
return [];
};
/**
* Takes an array of [r, g, b, a] and converts it into a string appropriate for
* CSS styles.
* @param {Array.<number>} rgba [r, g, b, a] with r, g, b in [0, 255] and a
* in [0, 1].
* @return {string} string of the form 'rgba(r,g,b,a)'.
* @private
*/
goog.color.alpha.rgbaStyle_ = function(rgba) {
return 'rgba(' + rgba.join(',') + ')';
};
/**
* Converts from h,s,v,a values to a hex string
* @param {number} h Hue, in [0, 1].
* @param {number} s Saturation, in [0, 1].
* @param {number} v Value, in [0, 255].
* @param {number} a Alpha, in [0, 1].
* @return {string} hex representation of the color.
*/
goog.color.alpha.hsvaToHex = function(h, s, v, a) {
var alpha = Math.floor(a * 255);
return goog.color.hsvArrayToHex([h, s, v]) +
goog.color.prependZeroIfNecessaryHelper(alpha.toString(16));
};
/**
* Converts from an HSVA array to a hex string
* @param {Array} hsva Array of [h, s, v, a] in
* [[0, 1], [0, 1], [0, 255], [0, 1]].
* @return {string} hex representation of the color.
*/
goog.color.alpha.hsvaArrayToHex = function(hsva) {
return goog.color.alpha.hsvaToHex(hsva[0], hsva[1], hsva[2], hsva[3]);
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview An interface for a listenable JavaScript object.
*
* WARNING(chrishenry): DO NOT USE! SUPPORT NOT FULLY IMPLEMENTED.
*/
goog.provide('goog.events.Listenable');
goog.provide('goog.events.ListenableKey');
/**
* A listenable interface. Also see goog.events.EventTarget.
* @interface
*/
goog.events.Listenable = function() {};
/**
* Whether to use the new listenable interface and mechanism in
* goog.events and goog.events.EventTarget.
*
* TODO(user): Remove this once launched and stable.
*
* @type {boolean}
*/
goog.events.Listenable.USE_LISTENABLE_INTERFACE = false;
/**
* An expando property to indicate that an object implements
* goog.events.Listenable.
*
* See addImplementation/isImplementedBy.
*
* @type {string}
* @const
* @private
*/
goog.events.Listenable.IMPLEMENTED_BY_PROP_ = '__closure_listenable';
/**
* Marks a given class (constructor) as an implementation of
* Listenable, do that we can query that fact at runtime. The class
* must have already implemented the interface.
* @param {!Function} cls The class constructor. The corresponding
* class must have already implemented the interface.
*/
goog.events.Listenable.addImplementation = function(cls) {
cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP_] = true;
};
/**
* @param {Object} obj The object to check.
* @return {boolean} Whether a given instance implements
* Listenable. The class/superclass of the instance must call
* addImplementation.
*/
goog.events.Listenable.isImplementedBy = function(obj) {
return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP_]);
};
/**
* Adds an event listener. A listener can only be added once to an
* object and if it is added again the key for the listener is
* returned. Note that if the existing listener is a one-off listener
* (registered via listenOnce), it will no longer be a one-off
* listener after a call to listen().
*
* @param {string} type Event type or array of event types.
* @param {!Function} listener Callback method, or an object
* with a handleEvent function.
* @param {boolean=} opt_useCapture Whether to fire in capture phase
* (defaults to false).
* @param {Object=} opt_listenerScope Object in whose scope to call the
* listener.
* @return {goog.events.ListenableKey} Unique key for the listener.
*/
goog.events.Listenable.prototype.listen;
/**
* Adds an event listener that is removed automatically after the
* listener fired once.
*
* If an existing listener already exists, listenOnce will do
* nothing. In particular, if the listener was previously registered
* via listen(), listenOnce() will not turn the listener into a
* one-off listener. Similarly, if there is already an existing
* one-off listener, listenOnce does not modify the listeners (it is
* still a once listener).
*
* @param {string} type Event type or array of event types.
* @param {!Function} listener Callback method, or an object
* with a handleEvent function.
* @param {boolean=} opt_useCapture Whether to fire in capture phase
* (defaults to false).
* @param {Object=} opt_listenerScope Object in whose scope to call the
* listener.
* @return {goog.events.ListenableKey} Unique key for the listener.
*/
goog.events.Listenable.prototype.listenOnce;
/**
* Removes an event listener which was added with listen() or listenOnce().
*
* Implementation needs to call goog.events.cleanUp.
*
* @param {string} type Event type or array of event types.
* @param {!Function} listener Callback method, or an object
* with a handleEvent function. TODO(user): Consider whether
* we can remove Object.
* @param {boolean=} opt_useCapture Whether to fire in capture phase
* (defaults to false).
* @param {Object=} opt_listenerScope Object in whose scope to call
* the listener.
* @return {boolean} Whether any listener was removed.
*/
goog.events.Listenable.prototype.unlisten;
/**
* Removes an event listener which was added with listen() by the key
* returned by listen().
*
* Implementation needs to call goog.events.cleanUp.
*
* @param {goog.events.ListenableKey} key The key returned by
* listen() or listenOnce().
* @return {boolean} Whether any listener was removed.
*/
goog.events.Listenable.prototype.unlistenByKey;
/**
* Dispatches an event (or event like object) and calls all listeners
* listening for events of this type. The type of the event is decided by the
* type property on the event object.
*
* If any of the listeners returns false OR calls preventDefault then this
* function will return false. If one of the capture listeners calls
* stopPropagation, then the bubble listeners won't fire.
*
* @param {goog.events.EventLike} e Event object.
* @return {boolean} If anyone called preventDefault on the event object (or
* if any of the listeners returns false this will also return false.
*/
goog.events.Listenable.prototype.dispatchEvent;
/**
* Removes all listeners from this listenable. If type is specified,
* it will only remove listeners of the particular type. otherwise all
* registered listeners will be removed.
*
* Implementation needs to call goog.events.cleanUp for each removed
* listener.
*
* @param {string=} opt_type Type of event to remove, default is to
* remove all types.
* @return {number} Number of listeners removed.
*/
goog.events.Listenable.prototype.removeAllListeners;
/**
* Fires all registered listeners in this listenable for the given
* type and capture mode, passing them the given eventObject. This
* does not perform actual capture/bubble. Only implementors of the
* interface should be using this.
*
* @param {string} type The type of the listeners to fire.
* @param {boolean} capture The capture mode of the listeners to fire.
* @param {goog.events.Event} eventObject The event object to fire.
* @return {boolean} Whether all listeners succeeded without
* attempting to prevent default behavior. If any listener returns
* false or called goog.events.Event#preventDefault, this returns
* false.
*/
goog.events.Listenable.prototype.fireListeners;
/**
* Gets all listeners in this listenable for the given type and
* capture mode.
*
* @param {string} type The type of the listeners to fire.
* @param {boolean} capture The capture mode of the listeners to fire.
* @return {!Array.<goog.events.ListenableKey>} An array of registered
* listeners.
*/
goog.events.Listenable.prototype.getListeners;
/**
* Gets the goog.events.ListenableKey for the event or null if no such
* listener is in use.
*
* @param {string} type The name of the event without the 'on' prefix.
* @param {!Function} listener The listener function to get.
* @param {boolean=} capture Whether the listener is a capturing listener.
* @param {Object=} opt_listenerScope Object in whose scope to call the
* listener.
* @return {goog.events.ListenableKey} the found listener or null if not found.
*/
goog.events.Listenable.prototype.getListener;
/**
* Whether there is any active listeners matching the specified
* signature. If either the type or capture parameters are
* unspecified, the function will match on the remaining criteria.
*
* @param {string=} opt_type Event type.
* @param {boolean=} opt_capture Whether to check for capture or bubble
* listeners.
* @return {boolean} Whether there is any active listeners matching
* the requested type and/or capture phase.
*/
goog.events.Listenable.prototype.hasListener;
/**
* An interface that describes a single registered listener.
* @interface
*/
goog.events.ListenableKey = function() {};
/**
* Counter used to create a unique key
* @type {number}
* @private
*/
goog.events.ListenableKey.counter_ = 0;
/**
* Reserves a key to be used for ListenableKey#key field.
* @return {number} A number to be used to fill ListenableKey#key
* field.
*/
goog.events.ListenableKey.reserveKey = function() {
return ++goog.events.ListenableKey.counter_;
};
/**
* The source event target.
* @type {!(Object|goog.events.Listenable|goog.events.EventTarget)}
*/
goog.events.ListenableKey.prototype.src;
/**
* The event type the listener is listening to.
* @type {string}
*/
goog.events.ListenableKey.prototype.type;
/**
* The listener function.
* TODO(user): Narrow the type if possible.
* @type {Function|Object}
*/
goog.events.ListenableKey.prototype.listener;
/**
* Whether the listener works on capture phase.
* @type {boolean}
*/
goog.events.ListenableKey.prototype.capture;
/**
* The 'this' object for the listener function's scope.
* @type {Object}
*/
goog.events.ListenableKey.prototype.handler;
/**
* A globally unique number to identify the key.
* @type {number}
*/
goog.events.ListenableKey.prototype.key;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains a class for working with keyboard events
* that repeat consistently across browsers and platforms. It also unifies the
* key code so that it is the same in all browsers and platforms.
*
* Different web browsers have very different keyboard event handling. Most
* importantly is that only certain browsers repeat keydown events:
* IE, Opera, FF/Win32, and Safari 3 repeat keydown events.
* FF/Mac and Safari 2 do not.
*
* For the purposes of this code, "Safari 3" means WebKit 525+, when WebKit
* decided that they should try to match IE's key handling behavior.
* Safari 3.0.4, which shipped with Leopard (WebKit 523), has the
* Safari 2 behavior.
*
* Firefox, Safari, Opera prevent on keypress
*
* IE prevents on keydown
*
* Firefox does not fire keypress for shift, ctrl, alt
* Firefox does fire keydown for shift, ctrl, alt, meta
* Firefox does not repeat keydown for shift, ctrl, alt, meta
*
* Firefox does not fire keypress for up and down in an input
*
* Opera fires keypress for shift, ctrl, alt, meta
* Opera does not repeat keypress for shift, ctrl, alt, meta
*
* Safari 2 and 3 do not fire keypress for shift, ctrl, alt
* Safari 2 does not fire keydown for shift, ctrl, alt
* Safari 3 *does* fire keydown for shift, ctrl, alt
*
* IE provides the keycode for keyup/down events and the charcode (in the
* keycode field) for keypress.
*
* Mozilla provides the keycode for keyup/down and the charcode for keypress
* unless it's a non text modifying key in which case the keycode is provided.
*
* Safari 3 provides the keycode and charcode for all events.
*
* Opera provides the keycode for keyup/down event and either the charcode or
* the keycode (in the keycode field) for keypress events.
*
* Firefox x11 doesn't fire keydown events if a another key is already held down
* until the first key is released. This can cause a key event to be fired with
* a keyCode for the first key and a charCode for the second key.
*
* Safari in keypress
*
* charCode keyCode which
* ENTER: 13 13 13
* F1: 63236 63236 63236
* F8: 63243 63243 63243
* ...
* p: 112 112 112
* P: 80 80 80
*
* Firefox, keypress:
*
* charCode keyCode which
* ENTER: 0 13 13
* F1: 0 112 0
* F8: 0 119 0
* ...
* p: 112 0 112
* P: 80 0 80
*
* Opera, Mac+Win32, keypress:
*
* charCode keyCode which
* ENTER: undefined 13 13
* F1: undefined 112 0
* F8: undefined 119 0
* ...
* p: undefined 112 112
* P: undefined 80 80
*
* IE7, keydown
*
* charCode keyCode which
* ENTER: undefined 13 undefined
* F1: undefined 112 undefined
* F8: undefined 119 undefined
* ...
* p: undefined 80 undefined
* P: undefined 80 undefined
*
* @author arv@google.com (Erik Arvidsson)
* @author eae@google.com (Emil A Eklund)
* @see ../demos/keyhandler.html
*/
goog.provide('goog.events.KeyEvent');
goog.provide('goog.events.KeyHandler');
goog.provide('goog.events.KeyHandler.EventType');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.userAgent');
/**
* A wrapper around an element that you want to listen to keyboard events on.
* @param {Element|Document=} opt_element The element or document to listen on.
* @param {boolean=} opt_capture Whether to listen for browser events in
* capture phase (defaults to false).
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.events.KeyHandler = function(opt_element, opt_capture) {
goog.events.EventTarget.call(this);
if (opt_element) {
this.attach(opt_element, opt_capture);
}
};
goog.inherits(goog.events.KeyHandler, goog.events.EventTarget);
/**
* This is the element that we will listen to the real keyboard events on.
* @type {Element|Document|null}
* @private
*/
goog.events.KeyHandler.prototype.element_ = null;
/**
* The key for the key press listener.
* @type {goog.events.Key}
* @private
*/
goog.events.KeyHandler.prototype.keyPressKey_ = null;
/**
* The key for the key down listener.
* @type {goog.events.Key}
* @private
*/
goog.events.KeyHandler.prototype.keyDownKey_ = null;
/**
* The key for the key up listener.
* @type {goog.events.Key}
* @private
*/
goog.events.KeyHandler.prototype.keyUpKey_ = null;
/**
* Used to detect keyboard repeat events.
* @private
* @type {number}
*/
goog.events.KeyHandler.prototype.lastKey_ = -1;
/**
* Keycode recorded for key down events. As most browsers don't report the
* keycode in the key press event we need to record it in the key down phase.
* @private
* @type {number}
*/
goog.events.KeyHandler.prototype.keyCode_ = -1;
/**
* Alt key recorded for key down events. FF on Mac does not report the alt key
* flag in the key press event, we need to record it in the key down phase.
* @type {boolean}
* @private
*/
goog.events.KeyHandler.prototype.altKey_ = false;
/**
* Enum type for the events fired by the key handler
* @enum {string}
*/
goog.events.KeyHandler.EventType = {
KEY: 'key'
};
/**
* An enumeration of key codes that Safari 2 does incorrectly
* @type {Object}
* @private
*/
goog.events.KeyHandler.safariKey_ = {
'3': goog.events.KeyCodes.ENTER, // 13
'12': goog.events.KeyCodes.NUMLOCK, // 144
'63232': goog.events.KeyCodes.UP, // 38
'63233': goog.events.KeyCodes.DOWN, // 40
'63234': goog.events.KeyCodes.LEFT, // 37
'63235': goog.events.KeyCodes.RIGHT, // 39
'63236': goog.events.KeyCodes.F1, // 112
'63237': goog.events.KeyCodes.F2, // 113
'63238': goog.events.KeyCodes.F3, // 114
'63239': goog.events.KeyCodes.F4, // 115
'63240': goog.events.KeyCodes.F5, // 116
'63241': goog.events.KeyCodes.F6, // 117
'63242': goog.events.KeyCodes.F7, // 118
'63243': goog.events.KeyCodes.F8, // 119
'63244': goog.events.KeyCodes.F9, // 120
'63245': goog.events.KeyCodes.F10, // 121
'63246': goog.events.KeyCodes.F11, // 122
'63247': goog.events.KeyCodes.F12, // 123
'63248': goog.events.KeyCodes.PRINT_SCREEN, // 44
'63272': goog.events.KeyCodes.DELETE, // 46
'63273': goog.events.KeyCodes.HOME, // 36
'63275': goog.events.KeyCodes.END, // 35
'63276': goog.events.KeyCodes.PAGE_UP, // 33
'63277': goog.events.KeyCodes.PAGE_DOWN, // 34
'63289': goog.events.KeyCodes.NUMLOCK, // 144
'63302': goog.events.KeyCodes.INSERT // 45
};
/**
* An enumeration of key identifiers currently part of the W3C draft for DOM3
* and their mappings to keyCodes.
* http://www.w3.org/TR/DOM-Level-3-Events/keyset.html#KeySet-Set
* This is currently supported in Safari and should be platform independent.
* @type {Object}
* @private
*/
goog.events.KeyHandler.keyIdentifier_ = {
'Up': goog.events.KeyCodes.UP, // 38
'Down': goog.events.KeyCodes.DOWN, // 40
'Left': goog.events.KeyCodes.LEFT, // 37
'Right': goog.events.KeyCodes.RIGHT, // 39
'Enter': goog.events.KeyCodes.ENTER, // 13
'F1': goog.events.KeyCodes.F1, // 112
'F2': goog.events.KeyCodes.F2, // 113
'F3': goog.events.KeyCodes.F3, // 114
'F4': goog.events.KeyCodes.F4, // 115
'F5': goog.events.KeyCodes.F5, // 116
'F6': goog.events.KeyCodes.F6, // 117
'F7': goog.events.KeyCodes.F7, // 118
'F8': goog.events.KeyCodes.F8, // 119
'F9': goog.events.KeyCodes.F9, // 120
'F10': goog.events.KeyCodes.F10, // 121
'F11': goog.events.KeyCodes.F11, // 122
'F12': goog.events.KeyCodes.F12, // 123
'U+007F': goog.events.KeyCodes.DELETE, // 46
'Home': goog.events.KeyCodes.HOME, // 36
'End': goog.events.KeyCodes.END, // 35
'PageUp': goog.events.KeyCodes.PAGE_UP, // 33
'PageDown': goog.events.KeyCodes.PAGE_DOWN, // 34
'Insert': goog.events.KeyCodes.INSERT // 45
};
/**
* If true, the KeyEvent fires on keydown. Otherwise, it fires on keypress.
*
* @type {boolean}
* @private
*/
goog.events.KeyHandler.USES_KEYDOWN_ = goog.userAgent.IE ||
goog.userAgent.WEBKIT && goog.userAgent.isVersion('525');
/**
* If true, the alt key flag is saved during the key down and reused when
* handling the key press. FF on Mac does not set the alt flag in the key press
* event.
* @type {boolean}
* @private
*/
goog.events.KeyHandler.SAVE_ALT_FOR_KEYPRESS_ = goog.userAgent.MAC &&
goog.userAgent.GECKO;
/**
* Records the keycode for browsers that only returns the keycode for key up/
* down events. For browser/key combinations that doesn't trigger a key pressed
* event it also fires the patched key event.
* @param {goog.events.BrowserEvent} e The key down event.
* @private
*/
goog.events.KeyHandler.prototype.handleKeyDown_ = function(e) {
// Ctrl-Tab and Alt-Tab can cause the focus to be moved to another window
// before we've caught a key-up event. If the last-key was one of these we
// reset the state.
if (goog.userAgent.WEBKIT) {
if (this.lastKey_ == goog.events.KeyCodes.CTRL && !e.ctrlKey ||
this.lastKey_ == goog.events.KeyCodes.ALT && !e.altKey ||
goog.userAgent.MAC &&
this.lastKey_ == goog.events.KeyCodes.META && !e.metaKey) {
this.lastKey_ = -1;
this.keyCode_ = -1;
}
}
if (this.lastKey_ == -1) {
if (e.ctrlKey && e.keyCode != goog.events.KeyCodes.CTRL) {
this.lastKey_ = goog.events.KeyCodes.CTRL;
} else if (e.altKey && e.keyCode != goog.events.KeyCodes.ALT) {
this.lastKey_ = goog.events.KeyCodes.ALT;
} else if (e.metaKey && e.keyCode != goog.events.KeyCodes.META) {
this.lastKey_ = goog.events.KeyCodes.META;
}
}
if (goog.events.KeyHandler.USES_KEYDOWN_ &&
!goog.events.KeyCodes.firesKeyPressEvent(e.keyCode,
this.lastKey_, e.shiftKey, e.ctrlKey, e.altKey)) {
this.handleEvent(e);
} else {
this.keyCode_ = goog.userAgent.GECKO ?
goog.events.KeyCodes.normalizeGeckoKeyCode(e.keyCode) :
e.keyCode;
if (goog.events.KeyHandler.SAVE_ALT_FOR_KEYPRESS_) {
this.altKey_ = e.altKey;
}
}
};
/**
* Resets the stored previous values. Needed to be called for webkit which will
* not generate a key up for meta key operations. This should only be called
* when having finished with repeat key possiblities.
*/
goog.events.KeyHandler.prototype.resetState = function() {
this.lastKey_ = -1;
this.keyCode_ = -1;
};
/**
* Clears the stored previous key value, resetting the key repeat status. Uses
* -1 because the Safari 3 Windows beta reports 0 for certain keys (like Home
* and End.)
* @param {goog.events.BrowserEvent} e The keyup event.
* @private
*/
goog.events.KeyHandler.prototype.handleKeyup_ = function(e) {
this.resetState();
this.altKey_ = e.altKey;
};
/**
* Handles the events on the element.
* @param {goog.events.BrowserEvent} e The keyboard event sent from the
* browser.
*/
goog.events.KeyHandler.prototype.handleEvent = function(e) {
var be = e.getBrowserEvent();
var keyCode, charCode;
var altKey = be.altKey;
// IE reports the character code in the keyCode field for keypress events.
// There are two exceptions however, Enter and Escape.
if (goog.userAgent.IE && e.type == goog.events.EventType.KEYPRESS) {
keyCode = this.keyCode_;
charCode = keyCode != goog.events.KeyCodes.ENTER &&
keyCode != goog.events.KeyCodes.ESC ?
be.keyCode : 0;
// Safari reports the character code in the keyCode field for keypress
// events but also has a charCode field.
} else if (goog.userAgent.WEBKIT &&
e.type == goog.events.EventType.KEYPRESS) {
keyCode = this.keyCode_;
charCode = be.charCode >= 0 && be.charCode < 63232 &&
goog.events.KeyCodes.isCharacterKey(keyCode) ?
be.charCode : 0;
// Opera reports the keycode or the character code in the keyCode field.
} else if (goog.userAgent.OPERA) {
keyCode = this.keyCode_;
charCode = goog.events.KeyCodes.isCharacterKey(keyCode) ?
be.keyCode : 0;
// Mozilla reports the character code in the charCode field.
} else {
keyCode = be.keyCode || this.keyCode_;
charCode = be.charCode || 0;
if (goog.events.KeyHandler.SAVE_ALT_FOR_KEYPRESS_) {
altKey = this.altKey_;
}
// On the Mac, shift-/ triggers a question mark char code and no key code
// (normalized to WIN_KEY), so we synthesize the latter.
if (goog.userAgent.MAC &&
charCode == goog.events.KeyCodes.QUESTION_MARK &&
keyCode == goog.events.KeyCodes.WIN_KEY) {
keyCode = goog.events.KeyCodes.SLASH;
}
}
var key = keyCode;
var keyIdentifier = be.keyIdentifier;
// Correct the key value for certain browser-specific quirks.
if (keyCode) {
if (keyCode >= 63232 && keyCode in goog.events.KeyHandler.safariKey_) {
// NOTE(nicksantos): Safari 3 has fixed this problem,
// this is only needed for Safari 2.
key = goog.events.KeyHandler.safariKey_[keyCode];
} else {
// Safari returns 25 for Shift+Tab instead of 9.
if (keyCode == 25 && e.shiftKey) {
key = 9;
}
}
} else if (keyIdentifier &&
keyIdentifier in goog.events.KeyHandler.keyIdentifier_) {
// This is needed for Safari Windows because it currently doesn't give a
// keyCode/which for non printable keys.
key = goog.events.KeyHandler.keyIdentifier_[keyIdentifier];
}
// If we get the same keycode as a keydown/keypress without having seen a
// keyup event, then this event was caused by key repeat.
var repeat = key == this.lastKey_;
this.lastKey_ = key;
var event = new goog.events.KeyEvent(key, charCode, repeat, be);
event.altKey = altKey;
this.dispatchEvent(event);
};
/**
* Returns the element listened on for the real keyboard events.
* @return {Element|Document|null} The element listened on for the real
* keyboard events.
*/
goog.events.KeyHandler.prototype.getElement = function() {
return this.element_;
};
/**
* Adds the proper key event listeners to the element.
* @param {Element|Document} element The element to listen on.
* @param {boolean=} opt_capture Whether to listen for browser events in
* capture phase (defaults to false).
*/
goog.events.KeyHandler.prototype.attach = function(element, opt_capture) {
if (this.keyUpKey_) {
this.detach();
}
this.element_ = element;
this.keyPressKey_ = goog.events.listen(this.element_,
goog.events.EventType.KEYPRESS,
this,
opt_capture);
// Most browsers (Safari 2 being the notable exception) doesn't include the
// keyCode in keypress events (IE has the char code in the keyCode field and
// Mozilla only included the keyCode if there's no charCode). Thus we have to
// listen for keydown to capture the keycode.
this.keyDownKey_ = goog.events.listen(this.element_,
goog.events.EventType.KEYDOWN,
this.handleKeyDown_,
opt_capture,
this);
this.keyUpKey_ = goog.events.listen(this.element_,
goog.events.EventType.KEYUP,
this.handleKeyup_,
opt_capture,
this);
};
/**
* Removes the listeners that may exist.
*/
goog.events.KeyHandler.prototype.detach = function() {
if (this.keyPressKey_) {
goog.events.unlistenByKey(this.keyPressKey_);
goog.events.unlistenByKey(this.keyDownKey_);
goog.events.unlistenByKey(this.keyUpKey_);
this.keyPressKey_ = null;
this.keyDownKey_ = null;
this.keyUpKey_ = null;
}
this.element_ = null;
this.lastKey_ = -1;
this.keyCode_ = -1;
};
/** @override */
goog.events.KeyHandler.prototype.disposeInternal = function() {
goog.events.KeyHandler.superClass_.disposeInternal.call(this);
this.detach();
};
/**
* This class is used for the goog.events.KeyHandler.EventType.KEY event and
* it overrides the key code with the fixed key code.
* @param {number} keyCode The adjusted key code.
* @param {number} charCode The unicode character code.
* @param {boolean} repeat Whether this event was generated by keyboard repeat.
* @param {Event} browserEvent Browser event object.
* @constructor
* @extends {goog.events.BrowserEvent}
*/
goog.events.KeyEvent = function(keyCode, charCode, repeat, browserEvent) {
goog.events.BrowserEvent.call(this, browserEvent);
this.type = goog.events.KeyHandler.EventType.KEY;
/**
* Keycode of key press.
* @type {number}
*/
this.keyCode = keyCode;
/**
* Unicode character code.
* @type {number}
*/
this.charCode = charCode;
/**
* True if this event was generated by keyboard auto-repeat (i.e., the user is
* holding the key down.)
* @type {boolean}
*/
this.repeat = repeat;
};
goog.inherits(goog.events.KeyEvent, goog.events.BrowserEvent);
| JavaScript |
// Copyright 2005 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A patched, standardized event object for browser events.
*
* <pre>
* The patched event object contains the following members:
* - type {string} Event type, e.g. 'click'
* - timestamp {Date} A date object for when the event was fired
* - target {Object} The element that actually triggered the event
* - currentTarget {Object} The element the listener is attached to
* - relatedTarget {Object} For mouseover and mouseout, the previous object
* - offsetX {number} X-coordinate relative to target
* - offsetY {number} Y-coordinate relative to target
* - clientX {number} X-coordinate relative to viewport
* - clientY {number} Y-coordinate relative to viewport
* - screenX {number} X-coordinate relative to the edge of the screen
* - screenY {number} Y-coordinate relative to the edge of the screen
* - button {number} Mouse button. Use isButton() to test.
* - keyCode {number} Key-code
* - ctrlKey {boolean} Was ctrl key depressed
* - altKey {boolean} Was alt key depressed
* - shiftKey {boolean} Was shift key depressed
* - metaKey {boolean} Was meta key depressed
* - defaultPrevented {boolean} Whether the default action has been prevented
* - state {Object} History state object
*
* NOTE: The keyCode member contains the raw browser keyCode. For normalized
* key and character code use {@link goog.events.KeyHandler}.
* </pre>
*
*/
goog.provide('goog.events.BrowserEvent');
goog.provide('goog.events.BrowserEvent.MouseButton');
goog.require('goog.events.BrowserFeature');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('goog.reflect');
goog.require('goog.userAgent');
/**
* Accepts a browser event object and creates a patched, cross browser event
* object.
* The content of this object will not be initialized if no event object is
* provided. If this is the case, init() needs to be invoked separately.
* @param {Event=} opt_e Browser event object.
* @param {EventTarget=} opt_currentTarget Current target for event.
* @constructor
* @extends {goog.events.Event}
*/
goog.events.BrowserEvent = function(opt_e, opt_currentTarget) {
if (opt_e) {
this.init(opt_e, opt_currentTarget);
}
};
goog.inherits(goog.events.BrowserEvent, goog.events.Event);
/**
* Normalized button constants for the mouse.
* @enum {number}
*/
goog.events.BrowserEvent.MouseButton = {
LEFT: 0,
MIDDLE: 1,
RIGHT: 2
};
/**
* Static data for mapping mouse buttons.
* @type {Array.<number>}
*/
goog.events.BrowserEvent.IEButtonMap = [
1, // LEFT
4, // MIDDLE
2 // RIGHT
];
/**
* Target that fired the event.
* @override
* @type {Node}
*/
goog.events.BrowserEvent.prototype.target = null;
/**
* Node that had the listener attached.
* @override
* @type {Node|undefined}
*/
goog.events.BrowserEvent.prototype.currentTarget;
/**
* For mouseover and mouseout events, the related object for the event.
* @type {Node}
*/
goog.events.BrowserEvent.prototype.relatedTarget = null;
/**
* X-coordinate relative to target.
* @type {number}
*/
goog.events.BrowserEvent.prototype.offsetX = 0;
/**
* Y-coordinate relative to target.
* @type {number}
*/
goog.events.BrowserEvent.prototype.offsetY = 0;
/**
* X-coordinate relative to the window.
* @type {number}
*/
goog.events.BrowserEvent.prototype.clientX = 0;
/**
* Y-coordinate relative to the window.
* @type {number}
*/
goog.events.BrowserEvent.prototype.clientY = 0;
/**
* X-coordinate relative to the monitor.
* @type {number}
*/
goog.events.BrowserEvent.prototype.screenX = 0;
/**
* Y-coordinate relative to the monitor.
* @type {number}
*/
goog.events.BrowserEvent.prototype.screenY = 0;
/**
* Which mouse button was pressed.
* @type {number}
*/
goog.events.BrowserEvent.prototype.button = 0;
/**
* Keycode of key press.
* @type {number}
*/
goog.events.BrowserEvent.prototype.keyCode = 0;
/**
* Keycode of key press.
* @type {number}
*/
goog.events.BrowserEvent.prototype.charCode = 0;
/**
* Whether control was pressed at time of event.
* @type {boolean}
*/
goog.events.BrowserEvent.prototype.ctrlKey = false;
/**
* Whether alt was pressed at time of event.
* @type {boolean}
*/
goog.events.BrowserEvent.prototype.altKey = false;
/**
* Whether shift was pressed at time of event.
* @type {boolean}
*/
goog.events.BrowserEvent.prototype.shiftKey = false;
/**
* Whether the meta key was pressed at time of event.
* @type {boolean}
*/
goog.events.BrowserEvent.prototype.metaKey = false;
/**
* History state object, only set for PopState events where it's a copy of the
* state object provided to pushState or replaceState.
* @type {Object}
*/
goog.events.BrowserEvent.prototype.state;
/**
* Whether the default platform modifier key was pressed at time of event.
* (This is control for all platforms except Mac, where it's Meta.
* @type {boolean}
*/
goog.events.BrowserEvent.prototype.platformModifierKey = false;
/**
* The browser event object.
* @type {Event}
* @private
*/
goog.events.BrowserEvent.prototype.event_ = null;
/**
* Accepts a browser event object and creates a patched, cross browser event
* object.
* @param {Event} e Browser event object.
* @param {EventTarget=} opt_currentTarget Current target for event.
*/
goog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {
var type = this.type = e.type;
goog.events.Event.call(this, type);
// TODO(nicksantos): Change this.target to type EventTarget.
this.target = /** @type {Node} */ (e.target) || e.srcElement;
// TODO(nicksantos): Change this.currentTarget to type EventTarget.
this.currentTarget = /** @type {Node} */ (opt_currentTarget);
var relatedTarget = /** @type {Node} */ (e.relatedTarget);
if (relatedTarget) {
// There's a bug in FireFox where sometimes, relatedTarget will be a
// chrome element, and accessing any property of it will get a permission
// denied exception. See:
// https://bugzilla.mozilla.org/show_bug.cgi?id=497780
if (goog.userAgent.GECKO) {
if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {
relatedTarget = null;
}
}
// TODO(arv): Use goog.events.EventType when it has been refactored into its
// own file.
} else if (type == goog.events.EventType.MOUSEOVER) {
relatedTarget = e.fromElement;
} else if (type == goog.events.EventType.MOUSEOUT) {
relatedTarget = e.toElement;
}
this.relatedTarget = relatedTarget;
// Webkit emits a lame warning whenever layerX/layerY is accessed.
// http://code.google.com/p/chromium/issues/detail?id=101733
this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?
e.offsetX : e.layerX;
this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?
e.offsetY : e.layerY;
this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;
this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;
this.screenX = e.screenX || 0;
this.screenY = e.screenY || 0;
this.button = e.button;
this.keyCode = e.keyCode || 0;
this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);
this.ctrlKey = e.ctrlKey;
this.altKey = e.altKey;
this.shiftKey = e.shiftKey;
this.metaKey = e.metaKey;
this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;
this.state = e.state;
this.event_ = e;
if (e.defaultPrevented) {
this.preventDefault();
}
delete this.propagationStopped_;
};
/**
* Tests to see which button was pressed during the event. This is really only
* useful in IE and Gecko browsers. And in IE, it's only useful for
* mousedown/mouseup events, because click only fires for the left mouse button.
*
* Safari 2 only reports the left button being clicked, and uses the value '1'
* instead of 0. Opera only reports a mousedown event for the middle button, and
* no mouse events for the right button. Opera has default behavior for left and
* middle click that can only be overridden via a configuration setting.
*
* There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.
*
* @param {goog.events.BrowserEvent.MouseButton} button The button
* to test for.
* @return {boolean} True if button was pressed.
*/
goog.events.BrowserEvent.prototype.isButton = function(button) {
if (!goog.events.BrowserFeature.HAS_W3C_BUTTON) {
if (this.type == 'click') {
return button == goog.events.BrowserEvent.MouseButton.LEFT;
} else {
return !!(this.event_.button &
goog.events.BrowserEvent.IEButtonMap[button]);
}
} else {
return this.event_.button == button;
}
};
/**
* Whether this has an "action"-producing mouse button.
*
* By definition, this includes left-click on windows/linux, and left-click
* without the ctrl key on Macs.
*
* @return {boolean} The result.
*/
goog.events.BrowserEvent.prototype.isMouseActionButton = function() {
// Webkit does not ctrl+click to be a right-click, so we
// normalize it to behave like Gecko and Opera.
return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&
!(goog.userAgent.WEBKIT && goog.userAgent.MAC && this.ctrlKey);
};
/**
* @override
*/
goog.events.BrowserEvent.prototype.stopPropagation = function() {
goog.events.BrowserEvent.superClass_.stopPropagation.call(this);
if (this.event_.stopPropagation) {
this.event_.stopPropagation();
} else {
this.event_.cancelBubble = true;
}
};
/**
* @override
*/
goog.events.BrowserEvent.prototype.preventDefault = function() {
goog.events.BrowserEvent.superClass_.preventDefault.call(this);
var be = this.event_;
if (!be.preventDefault) {
be.returnValue = false;
if (goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT) {
/** @preserveTry */
try {
// Most keys can be prevented using returnValue. Some special keys
// require setting the keyCode to -1 as well:
//
// In IE7:
// F3, F5, F10, F11, Ctrl+P, Crtl+O, Ctrl+F (these are taken from IE6)
//
// In IE8:
// Ctrl+P, Crtl+O, Ctrl+F (F1-F12 cannot be stopped through the event)
//
// We therefore do this for all function keys as well as when Ctrl key
// is pressed.
var VK_F1 = 112;
var VK_F12 = 123;
if (be.ctrlKey || be.keyCode >= VK_F1 && be.keyCode <= VK_F12) {
be.keyCode = -1;
}
} catch (ex) {
// IE throws an 'access denied' exception when trying to change
// keyCode in some situations (e.g. srcElement is input[type=file],
// or srcElement is an anchor tag rewritten by parent's innerHTML).
// Do nothing in this case.
}
}
} else {
be.preventDefault();
}
};
/**
* @return {Event} The underlying browser event object.
*/
goog.events.BrowserEvent.prototype.getBrowserEvent = function() {
return this.event_;
};
/** @override */
goog.events.BrowserEvent.prototype.disposeInternal = function() {
};
| JavaScript |
// Copyright 2005 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A base class for event objects.
*
*/
goog.provide('goog.events.Event');
goog.provide('goog.events.EventLike');
// goog.events.Event no longer depends on goog.Disposable. Keep requiring
// goog.Disposable here to not break projects which assume this dependency.
goog.require('goog.Disposable');
/**
* A typedef for event like objects that are dispatchable via the
* goog.events.dispatchEvent function. strings are treated as the type for a
* goog.events.Event. Objects are treated as an extension of a new
* goog.events.Event with the type property of the object being used as the type
* of the Event.
* @typedef {string|Object|goog.events.Event}
*/
goog.events.EventLike;
/**
* A base class for event objects, so that they can support preventDefault and
* stopPropagation.
*
* @param {string} type Event Type.
* @param {Object=} opt_target Reference to the object that is the target of
* this event. It has to implement the {@code EventTarget} interface
* declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.
* @constructor
*/
goog.events.Event = function(type, opt_target) {
/**
* Event type.
* @type {string}
*/
this.type = type;
/**
* Target of the event.
* @type {Object|undefined}
*/
this.target = opt_target;
/**
* Object that had the listener attached.
* @type {Object|undefined}
*/
this.currentTarget = this.target;
};
/**
* For backwards compatibility (goog.events.Event used to inherit
* goog.Disposable).
* @deprecated Events don't need to be disposed.
*/
goog.events.Event.prototype.disposeInternal = function() {
};
/**
* For backwards compatibility (goog.events.Event used to inherit
* goog.Disposable).
* @deprecated Events don't need to be disposed.
*/
goog.events.Event.prototype.dispose = function() {
};
/**
* Whether to cancel the event in internal capture/bubble processing for IE.
* @type {boolean}
* @suppress {underscore} Technically public, but referencing this outside
* this package is strongly discouraged.
*/
goog.events.Event.prototype.propagationStopped_ = false;
/**
* Whether the default action has been prevented.
* This is a property to match the W3C specification at {@link
* http://www.w3.org/TR/DOM-Level-3-Events/#events-event-type-defaultPrevented}.
* Must be treated as read-only outside the class.
* @type {boolean}
*/
goog.events.Event.prototype.defaultPrevented = false;
/**
* Return value for in internal capture/bubble processing for IE.
* @type {boolean}
* @suppress {underscore} Technically public, but referencing this outside
* this package is strongly discouraged.
*/
goog.events.Event.prototype.returnValue_ = true;
/**
* Stops event propagation.
*/
goog.events.Event.prototype.stopPropagation = function() {
this.propagationStopped_ = true;
};
/**
* Prevents the default action, for example a link redirecting to a url.
*/
goog.events.Event.prototype.preventDefault = function() {
this.defaultPrevented = true;
this.returnValue_ = false;
};
/**
* Stops the propagation of the event. It is equivalent to
* {@code e.stopPropagation()}, but can be used as the callback argument of
* {@link goog.events.listen} without declaring another function.
* @param {!goog.events.Event} e An event.
*/
goog.events.Event.stopPropagation = function(e) {
e.stopPropagation();
};
/**
* Prevents the default action. It is equivalent to
* {@code e.preventDefault()}, but can be used as the callback argument of
* {@link goog.events.listen} without declaring another function.
* @param {!goog.events.Event} e An event.
*/
goog.events.Event.preventDefault = function(e) {
e.preventDefault();
};
| JavaScript |
// Copyright 2005 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Implementation of EventTarget as defined by W3C DOM 2/3.
*
* @author arv@google.com (Erik Arvidsson) [Original implementation]
* @author pupius@google.com (Daniel Pupius) [Port to use goog.events]
* @see ../demos/eventtarget.html
*/
goog.provide('goog.events.EventTarget');
goog.require('goog.Disposable');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.Listenable');
goog.require('goog.events.Listener');
goog.require('goog.object');
/**
* Inherit from this class to give your object the ability to dispatch events.
* Note that this class provides event <em>sending</em> behaviour, not event
* receiving behaviour: your object will be able to broadcast events, and other
* objects will be able to listen for those events using goog.events.listen().
*
* <p>The name "EventTarget" reflects the fact that this class implements the
* <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">
* EventTarget interface</a> as defined by W3C DOM 2/3, with a few differences:
* <ul>
* <li>Event objects do not have to implement the Event interface. An object
* is treated as an event object if it has a 'type' property.
* <li>You can use a plain string instead of an event object; an event-like
* object will be created with the 'type' set to the string value.
* </ul>
*
* <p>Unless propagation is stopped, an event dispatched by an EventTarget
* will bubble to the parent returned by <code>getParentEventTarget</code>.
* To set the parent, call <code>setParentEventTarget</code> or override
* <code>getParentEventTarget</code> in a subclass. Subclasses that don't
* support changing the parent should override the setter to throw an error.
*
* <p>Example usage:
* <pre>
* var source = new goog.events.EventTarget();
* function handleEvent(event) {
* alert('Type: ' + e.type + '\nTarget: ' + e.target);
* }
* goog.events.listen(source, 'foo', handleEvent);
* ...
* source.dispatchEvent({type: 'foo'}); // will call handleEvent
* // or source.dispatchEvent('foo');
* ...
* goog.events.unlisten(source, 'foo', handleEvent);
*
* // You can also use the Listener interface:
* var listener = {
* handleEvent: function(event) {
* ...
* }
* };
* goog.events.listen(source, 'bar', listener);
* </pre>
*
* @constructor
* @extends {goog.Disposable}
* @implements {goog.events.Listenable}
*/
goog.events.EventTarget = function() {
goog.Disposable.call(this);
/**
* Maps of event type to an array of listeners.
*
* @type {Object.<string, !Array.<!goog.events.ListenableKey>>}
* @private
*/
this.eventTargetListeners_ = {};
/**
* The object to use for event.target. Useful when mixing in an
* EventTarget to another object.
* @type {!Object}
* @private
*/
this.actualEventTarget_ = this;
};
goog.inherits(goog.events.EventTarget, goog.Disposable);
if (goog.events.Listenable.USE_LISTENABLE_INTERFACE) {
goog.events.Listenable.addImplementation(goog.events.EventTarget);
}
/**
* An artificial cap on the number of ancestors you can have. This is mainly
* for loop detection.
* @const {number}
* @private
*/
goog.events.EventTarget.MAX_ANCESTORS_ = 1000;
/**
* Used to tell if an event is a real event in goog.events.listen() so we don't
* get listen() calling addEventListener() and vice-versa.
* @type {boolean}
* @private
*/
goog.events.EventTarget.prototype[goog.events.CUSTOM_EVENT_ATTR] = true;
/**
* Parent event target, used during event bubbling.
* @type {goog.events.EventTarget?}
* @private
*/
goog.events.EventTarget.prototype.parentEventTarget_ = null;
/**
* Returns the parent of this event target to use for bubbling.
*
* @return {goog.events.EventTarget} The parent EventTarget or null if there
* is no parent.
*/
goog.events.EventTarget.prototype.getParentEventTarget = function() {
return this.parentEventTarget_;
};
/**
* Sets the parent of this event target to use for bubbling.
*
* @param {goog.events.EventTarget?} parent Parent EventTarget (null if none).
*/
goog.events.EventTarget.prototype.setParentEventTarget = function(parent) {
this.parentEventTarget_ = parent;
};
/**
* Adds an event listener to the event target. The same handler can only be
* added once per the type. Even if you add the same handler multiple times
* using the same type then it will only be called once when the event is
* dispatched.
*
* Supported for legacy but use goog.events.listen(src, type, handler) instead.
*
* @param {string} type The type of the event to listen for.
* @param {Function|Object} handler The function to handle the event. The
* handler can also be an object that implements the handleEvent method
* which takes the event object as argument.
* @param {boolean=} opt_capture In DOM-compliant browsers, this determines
* whether the listener is fired during the capture or bubble phase
* of the event.
* @param {Object=} opt_handlerScope Object in whose scope to call
* the listener.
*/
goog.events.EventTarget.prototype.addEventListener = function(
type, handler, opt_capture, opt_handlerScope) {
goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);
};
/**
* Removes an event listener from the event target. The handler must be the
* same object as the one added. If the handler has not been added then
* nothing is done.
* @param {string} type The type of the event to listen for.
* @param {Function|Object} handler The function to handle the event. The
* handler can also be an object that implements the handleEvent method
* which takes the event object as argument.
* @param {boolean=} opt_capture In DOM-compliant browsers, this determines
* whether the listener is fired during the capture or bubble phase
* of the event.
* @param {Object=} opt_handlerScope Object in whose scope to call
* the listener.
*/
goog.events.EventTarget.prototype.removeEventListener = function(
type, handler, opt_capture, opt_handlerScope) {
goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);
};
/** @override */
goog.events.EventTarget.prototype.dispatchEvent = function(e) {
if (goog.events.Listenable.USE_LISTENABLE_INTERFACE) {
this.assertInitialized();
var ancestorsTree, ancestor = this.getParentEventTarget();
if (ancestor) {
ancestorsTree = [];
var ancestorCount = 1;
for (; ancestor; ancestor = ancestor.getParentEventTarget()) {
ancestorsTree.push(ancestor);
goog.asserts.assert(
(++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),
'infinite loop');
}
}
return goog.events.EventTarget.dispatchEventInternal_(
this.actualEventTarget_, e, ancestorsTree);
} else {
return goog.events.dispatchEvent(this, e);
}
};
/**
* Unattach listeners from this object. Classes that extend EventTarget may
* need to override this method in order to remove references to DOM Elements
* and additional listeners, it should be something like this:
* <pre>
* MyClass.prototype.disposeInternal = function() {
* MyClass.superClass_.disposeInternal.call(this);
* // Dispose logic for MyClass
* };
* </pre>
* @override
* @protected
*/
goog.events.EventTarget.prototype.disposeInternal = function() {
goog.events.EventTarget.superClass_.disposeInternal.call(this);
if (goog.events.Listenable.USE_LISTENABLE_INTERFACE) {
this.removeAllListeners();
} else {
goog.events.removeAll(this);
}
this.parentEventTarget_ = null;
};
/**
* Asserts that the event target instance is initialized properly.
*/
goog.events.EventTarget.prototype.assertInitialized = function() {
if (goog.events.STRICT_EVENT_TARGET) {
goog.asserts.assert(
this.eventTargetListeners_,
'Event target is not initialized. Did you call superclass ' +
'(goog.events.EventTarget) constructor?');
}
};
if (goog.events.Listenable.USE_LISTENABLE_INTERFACE) {
/** @override */
goog.events.EventTarget.prototype.listen = function(
type, listener, opt_useCapture, opt_listenerScope) {
return this.listenInternal_(
type, listener, false /* callOnce */, opt_useCapture, opt_listenerScope);
};
/** @override */
goog.events.EventTarget.prototype.listenOnce = function(
type, listener, opt_useCapture, opt_listenerScope) {
return this.listenInternal_(
type, listener, true /* callOnce */, opt_useCapture, opt_listenerScope);
};
/**
* Adds an event listener. A listener can only be added once to an
* object and if it is added again the key for the listener is
* returned.
*
* Note that a one-off listener will not change an existing listener,
* if any. On the other hand a normal listener will change existing
* one-off listener to become a normal listener.
*
* @param {string} type Event type to listen to.
* @param {!Function} listener Callback method.
* @param {boolean} callOnce Whether the listener is a one-off
* listener or otherwise.
* @param {boolean=} opt_useCapture Whether to fire in capture phase
* (defaults to false).
* @param {Object=} opt_listenerScope Object in whose scope to call the
* listener.
* @return {goog.events.ListenableKey} Unique key for the listener.
* @private
*/
goog.events.EventTarget.prototype.listenInternal_ = function(
type, listener, callOnce, opt_useCapture, opt_listenerScope) {
this.assertInitialized();
var listenerArray = this.eventTargetListeners_[type] ||
(this.eventTargetListeners_[type] = []);
var listenerObj;
var index = goog.events.EventTarget.findListenerIndex_(
listenerArray, listener, opt_useCapture, opt_listenerScope);
if (index > -1) {
listenerObj = listenerArray[index];
if (!callOnce) {
// Ensure that, if there is an existing callOnce listener, it is no
// longer a callOnce listener.
listenerObj.callOnce = false;
}
return listenerObj;
}
listenerObj = new goog.events.Listener();
listenerObj.init(
listener, null, this, type, !!opt_useCapture, opt_listenerScope);
listenerObj.callOnce = callOnce;
listenerArray.push(listenerObj);
return listenerObj;
};
/** @override */
goog.events.EventTarget.prototype.unlisten = function(
type, listener, opt_useCapture, opt_listenerScope) {
if (!(type in this.eventTargetListeners_)) {
return false;
}
var listenerArray = this.eventTargetListeners_[type];
var index = goog.events.EventTarget.findListenerIndex_(
listenerArray, listener, opt_useCapture, opt_listenerScope);
if (index > -1) {
var listenerObj = listenerArray[index];
goog.events.cleanUp(listenerObj);
listenerObj.removed = true;
return goog.array.removeAt(listenerArray, index);
}
return false;
};
/** @override */
goog.events.EventTarget.prototype.unlistenByKey = function(key) {
var type = key.type;
if (!(type in this.eventTargetListeners_)) {
return false;
}
var removed = goog.array.remove(this.eventTargetListeners_[type], key);
if (removed) {
goog.events.cleanUp(key);
key.removed = true;
}
return removed;
};
/** @override */
goog.events.EventTarget.prototype.removeAllListeners = function(
opt_type, opt_capture) {
var count = 0;
for (var type in this.eventTargetListeners_) {
if (!opt_type || type == opt_type) {
var listenerArray = this.eventTargetListeners_[type];
for (var i = 0; i < listenerArray.length; i++) {
++count;
goog.events.cleanUp(listenerArray[i]);
listenerArray[i].removed = true;
}
listenerArray.length = 0;
}
}
return count;
};
/** @override */
goog.events.EventTarget.prototype.fireListeners = function(
type, capture, eventObject) {
if (!(type in this.eventTargetListeners_)) {
return true;
}
var rv = true;
var listenerArray = goog.array.clone(this.eventTargetListeners_[type]);
for (var i = 0; i < listenerArray.length; ++i) {
var listener = listenerArray[i];
// We might not have a listener if the listener was removed.
if (listener && !listener.removed && listener.capture == capture) {
// TODO(user): This logic probably should be in the Listener
// object instead.
if (listener.callOnce) {
this.unlistenByKey(listener);
}
rv = listener.handleEvent(eventObject) !== false && rv;
}
}
return rv && eventObject.returnValue_ != false;
};
/** @override */
goog.events.EventTarget.prototype.getListeners = function(type, capture) {
var listenerArray = this.eventTargetListeners_[type];
var rv = [];
if (listenerArray) {
for (var i = 0; i < listenerArray.length; ++i) {
var listenerObj = listenerArray[i];
if (listenerObj.capture == capture) {
rv.push(listenerObj);
}
}
}
return rv;
};
/** @override */
goog.events.EventTarget.prototype.getListener = function(
type, listener, capture, opt_listenerScope) {
var listenerArray = this.eventTargetListeners_[type];
var i = -1;
if (listenerArray) {
i = goog.events.EventTarget.findListenerIndex_(
listenerArray, listener, capture, opt_listenerScope);
}
return i > -1 ? listenerArray[i] : null;
};
/** @override */
goog.events.EventTarget.prototype.hasListener = function(
opt_type, opt_capture) {
var hasType = goog.isDef(opt_type);
var hasCapture = goog.isDef(opt_capture);
return goog.object.some(
this.eventTargetListeners_, function(listenersArray, type) {
for (var i = 0; i < listenersArray.length; ++i) {
if ((!hasType || listenersArray[i].type == opt_type) &&
(!hasCapture || listenersArray[i].capture == opt_capture)) {
return true;
}
}
return false;
});
};
/**
* Sets the target to be used for {@code event.target} when firing
* event. Mainly used for testing. For example, see
* {@code goog.testing.events.mixinListenable}.
* @param {!Object} target The target.
*/
goog.events.EventTarget.prototype.setTargetForTesting = function(target) {
this.actualEventTarget_ = target;
};
/**
* Dispatches the given event on the ancestorsTree.
*
* TODO(user): Look for a way to reuse this logic in
* goog.events, if possible.
*
* @param {!Object} target The target to dispatch on.
* @param {goog.events.Event|Object|string} e The event object.
* @param {Array.<goog.events.Listenable>=} opt_ancestorsTree The ancestors
* tree of the target, in reverse order from the closest ancestor
* to the root event target. May be null if the target has no ancestor.
* @return {boolean} If anyone called preventDefault on the event object (or
* if any of the listeners returns false this will also return false.
* @private
*/
goog.events.EventTarget.dispatchEventInternal_ = function(
target, e, opt_ancestorsTree) {
var type = e.type || /** @type {string} */ (e);
// If accepting a string or object, create a custom event object so that
// preventDefault and stopPropagation work with the event.
if (goog.isString(e)) {
e = new goog.events.Event(e, target);
} else if (!(e instanceof goog.events.Event)) {
var oldEvent = e;
e = new goog.events.Event(type, target);
goog.object.extend(e, oldEvent);
} else {
e.target = e.target || target;
}
var rv = true, currentTarget;
// Executes all capture listeners on the ancestors, if any.
if (opt_ancestorsTree) {
for (var i = opt_ancestorsTree.length - 1; !e.propagationStopped_ && i >= 0;
i--) {
currentTarget = e.currentTarget = opt_ancestorsTree[i];
rv = currentTarget.fireListeners(type, true, e) && rv;
}
}
// Executes capture and bubble listeners on the target.
if (!e.propagationStopped_) {
currentTarget = e.currentTarget = target;
rv = currentTarget.fireListeners(type, true, e) && rv;
if (!e.propagationStopped_) {
rv = currentTarget.fireListeners(type, false, e) && rv;
}
}
// Executes all bubble listeners on the ancestors, if any.
if (opt_ancestorsTree) {
for (i = 0; !e.propagationStopped_ && i < opt_ancestorsTree.length; i++) {
currentTarget = e.currentTarget = opt_ancestorsTree[i];
rv = currentTarget.fireListeners(type, false, e) && rv;
}
}
return rv;
};
/**
* Finds the index of a matching goog.events.Listener in the given
* listenerArray.
* @param {!Array.<!goog.events.Listener>} listenerArray Array of listener.
* @param {!Function} listener The listener function.
* @param {boolean=} opt_useCapture The capture flag for the listener.
* @param {Object=} opt_listenerScope The listener scope.
* @return {number} The index of the matching listener within the
* listenerArray.
* @private
*/
goog.events.EventTarget.findListenerIndex_ = function(
listenerArray, listener, opt_useCapture, opt_listenerScope) {
for (var i = 0; i < listenerArray.length; ++i) {
var listenerObj = listenerArray[i];
if (listenerObj.listener == listener &&
listenerObj.capture == !!opt_useCapture &&
listenerObj.handler == opt_listenerScope) {
return i;
}
}
return -1;
};
} // if (goog.events.Listenable.USE_LISTENABLE_INTERFACE)
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains a class to provide a unified mechanism for
* CLICK and enter KEYDOWN events. This provides better accessibility by
* providing the given functionality to a keyboard user which is otherwise
* would be available only via a mouse click.
*
* If there is an existing CLICK listener or planning to be added as below -
*
* <code>this.eventHandler_.listen(el, CLICK, this.onClick_);<code>
*
* it can be replaced with an ACTION listener as follows:
*
* <code>this.eventHandler_.listen(
* new goog.events.ActionHandler(el),
* ACTION,
* this.onAction_);<code>
*
*/
goog.provide('goog.events.ActionEvent');
goog.provide('goog.events.ActionHandler');
goog.provide('goog.events.ActionHandler.EventType');
goog.provide('goog.events.BeforeActionEvent');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.userAgent');
/**
* A wrapper around an element that you want to listen to ACTION events on.
* @param {Element|Document} element The element or document to listen on.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.events.ActionHandler = function(element) {
goog.events.EventTarget.call(this);
/**
* This is the element that we will listen to events on.
* @type {Element|Document}
* @private
*/
this.element_ = element;
goog.events.listen(element, goog.events.ActionHandler.KEY_EVENT_TYPE_,
this.handleKeyDown_, false, this);
goog.events.listen(element, goog.events.EventType.CLICK,
this.handleClick_, false, this);
};
goog.inherits(goog.events.ActionHandler, goog.events.EventTarget);
/**
* Enum type for the events fired by the action handler
* @enum {string}
*/
goog.events.ActionHandler.EventType = {
ACTION: 'action',
BEFOREACTION: 'beforeaction'
};
/**
* Key event type to listen for.
* @type {string}
* @private
*/
goog.events.ActionHandler.KEY_EVENT_TYPE_ = goog.userAgent.GECKO ?
goog.events.EventType.KEYPRESS :
goog.events.EventType.KEYDOWN;
/**
* Handles key press events.
* @param {!goog.events.BrowserEvent} e The key press event.
* @private
*/
goog.events.ActionHandler.prototype.handleKeyDown_ = function(e) {
if (e.keyCode == goog.events.KeyCodes.ENTER ||
goog.userAgent.WEBKIT && e.keyCode == goog.events.KeyCodes.MAC_ENTER) {
this.dispatchEvents_(e);
}
};
/**
* Handles mouse events.
* @param {!goog.events.BrowserEvent} e The click event.
* @private
*/
goog.events.ActionHandler.prototype.handleClick_ = function(e) {
this.dispatchEvents_(e);
};
/**
* Dispatches BeforeAction and Action events to the element
* @param {!goog.events.BrowserEvent} e The event causing dispatches.
* @private
*/
goog.events.ActionHandler.prototype.dispatchEvents_ = function(e) {
var beforeActionEvent = new goog.events.BeforeActionEvent(e);
// Allow application specific logic here before the ACTION event.
// For example, Gmail uses this event to restore keyboard focus
if (!this.dispatchEvent(beforeActionEvent)) {
// If the listener swallowed the BEFOREACTION event, don't dispatch the
// ACTION event.
return;
}
// Wrap up original event and send it off
var actionEvent = new goog.events.ActionEvent(e);
try {
this.dispatchEvent(actionEvent);
} finally {
// Stop propagating the event
e.stopPropagation();
}
};
/** @override */
goog.events.ActionHandler.prototype.disposeInternal = function() {
goog.events.ActionHandler.superClass_.disposeInternal.call(this);
goog.events.unlisten(this.element_, goog.events.ActionHandler.KEY_EVENT_TYPE_,
this.handleKeyDown_, false, this);
goog.events.unlisten(this.element_, goog.events.EventType.CLICK,
this.handleClick_, false, this);
delete this.element_;
};
/**
* This class is used for the goog.events.ActionHandler.EventType.ACTION event.
* @param {!goog.events.BrowserEvent} browserEvent Browser event object.
* @constructor
* @extends {goog.events.BrowserEvent}
*/
goog.events.ActionEvent = function(browserEvent) {
goog.events.BrowserEvent.call(this, browserEvent.getBrowserEvent());
this.type = goog.events.ActionHandler.EventType.ACTION;
};
goog.inherits(goog.events.ActionEvent, goog.events.BrowserEvent);
/**
* This class is used for the goog.events.ActionHandler.EventType.BEFOREACTION
* event. BEFOREACTION gives a chance to the application so the keyboard focus
* can be restored back, if required.
* @param {!goog.events.BrowserEvent} browserEvent Browser event object.
* @constructor
* @extends {goog.events.BrowserEvent}
*/
goog.events.BeforeActionEvent = function(browserEvent) {
goog.events.BrowserEvent.call(this, browserEvent.getBrowserEvent());
this.type = goog.events.ActionHandler.EventType.BEFOREACTION;
};
goog.inherits(goog.events.BeforeActionEvent, goog.events.BrowserEvent);
| JavaScript |
// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Input Method Editors (IMEs) are OS-level widgets that make
* it easier to type non-ascii characters on ascii keyboards (in particular,
* characters that require more than one keystroke).
*
* When the user wants to type such a character, a modal menu pops up and
* suggests possible "next" characters in the IME character sequence. After
* typing N characters, the user hits "enter" to commit the IME to the field.
* N differs from language to language.
*
* This class offers high-level events for how the user is interacting with the
* IME in editable regions.
*
* Known Issues:
*
* Firefox always fires an extra pair of compositionstart/compositionend events.
* We do not normalize for this.
*
* Opera does not fire any IME events.
*
* Spurious UPDATE events are common on all browsers.
*
* We currently do a bad job detecting when the IME closes on IE, and
* make a "best effort" guess on when we know it's closed.
*
*/
goog.provide('goog.events.ImeHandler');
goog.provide('goog.events.ImeHandler.Event');
goog.provide('goog.events.ImeHandler.EventType');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
/**
* Dispatches high-level events for IMEs.
* @param {Element} el The element to listen on.
* @extends {goog.events.EventTarget}
* @constructor
*/
goog.events.ImeHandler = function(el) {
goog.base(this);
/**
* The element to listen on.
* @type {Element}
* @private
*/
this.el_ = el;
/**
* Tracks the keyup event only, because it has a different life-cycle from
* other events.
* @type {goog.events.EventHandler}
* @private
*/
this.keyUpHandler_ = new goog.events.EventHandler(this);
/**
* Tracks all the browser events.
* @type {goog.events.EventHandler}
* @private
*/
this.handler_ = new goog.events.EventHandler(this);
if (goog.events.ImeHandler.USES_COMPOSITION_EVENTS) {
this.handler_.
listen(el, 'compositionstart', this.handleCompositionStart_).
listen(el, 'compositionend', this.handleCompositionEnd_).
listen(el, 'compositionupdate', this.handleTextModifyingInput_);
}
this.handler_.
listen(el, 'textInput', this.handleTextInput_).
listen(el, 'text', this.handleTextModifyingInput_).
listen(el, goog.events.EventType.KEYDOWN, this.handleKeyDown_);
};
goog.inherits(goog.events.ImeHandler, goog.events.EventTarget);
/**
* Event types fired by ImeHandler. These events do not make any guarantees
* about whether they were fired before or after the event in question.
* @enum {string}
*/
goog.events.ImeHandler.EventType = {
// After the IME opens.
START: 'startIme',
// An update to the state of the IME. An 'update' does not necessarily mean
// that the text contents of the field were modified in any way.
UPDATE: 'updateIme',
// After the IME closes.
END: 'endIme'
};
/**
* An event fired by ImeHandler.
* @param {goog.events.ImeHandler.EventType} type The type.
* @param {goog.events.BrowserEvent} reason The trigger for this event.
* @constructor
* @extends {goog.events.Event}
*/
goog.events.ImeHandler.Event = function(type, reason) {
goog.base(this, type);
/**
* The event that triggered this.
* @type {goog.events.BrowserEvent}
*/
this.reason = reason;
};
goog.inherits(goog.events.ImeHandler.Event, goog.events.Event);
/**
* Whether to use the composition events.
* @type {boolean}
*/
goog.events.ImeHandler.USES_COMPOSITION_EVENTS =
goog.userAgent.GECKO ||
(goog.userAgent.WEBKIT && goog.userAgent.isVersion(532));
/**
* Stores whether IME mode is active.
* @type {boolean}
* @private
*/
goog.events.ImeHandler.prototype.imeMode_ = false;
/**
* The keyCode value of the last keyDown event. This value is used for
* identiying whether or not a textInput event is sent by an IME.
* @type {number}
* @private
*/
goog.events.ImeHandler.prototype.lastKeyCode_ = 0;
/**
* @return {boolean} Whether an IME is active.
*/
goog.events.ImeHandler.prototype.isImeMode = function() {
return this.imeMode_;
};
/**
* Handles the compositionstart event.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleCompositionStart_ =
function(e) {
this.handleImeActivate_(e);
};
/**
* Handles the compositionend event.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleCompositionEnd_ = function(e) {
this.handleImeDeactivate_(e);
};
/**
* Handles the compositionupdate and text events.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleTextModifyingInput_ =
function(e) {
if (this.isImeMode()) {
this.processImeComposition_(e);
}
};
/**
* Handles IME activation.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleImeActivate_ = function(e) {
if (this.imeMode_) {
return;
}
// Listens for keyup events to handle unexpected IME keydown events on older
// versions of webkit.
//
// In those versions, we currently use textInput events deactivate IME
// (see handleTextInput_() for the reason). However,
// Safari fires a keydown event (as a result of pressing keys to commit IME
// text) with keyCode == WIN_IME after textInput event. This activates IME
// mode again unnecessarily. To prevent this problem, listens keyup events
// which can use to determine whether IME text has been committed.
if (goog.userAgent.WEBKIT &&
!goog.events.ImeHandler.USES_COMPOSITION_EVENTS) {
this.keyUpHandler_.listen(this.el_,
goog.events.EventType.KEYUP, this.handleKeyUpSafari4_);
}
this.imeMode_ = true;
this.dispatchEvent(
new goog.events.ImeHandler.Event(
goog.events.ImeHandler.EventType.START, e));
};
/**
* Handles the IME compose changes.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.processImeComposition_ = function(e) {
this.dispatchEvent(
new goog.events.ImeHandler.Event(
goog.events.ImeHandler.EventType.UPDATE, e));
};
/**
* Handles IME deactivation.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleImeDeactivate_ = function(e) {
this.imeMode_ = false;
this.keyUpHandler_.removeAll();
this.dispatchEvent(
new goog.events.ImeHandler.Event(
goog.events.ImeHandler.EventType.END, e));
};
/**
* Handles a key down event.
* @param {!goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleKeyDown_ = function(e) {
// Firefox and Chrome have a separate event for IME composition ('text'
// and 'compositionupdate', respectively), other browsers do not.
if (!goog.events.ImeHandler.USES_COMPOSITION_EVENTS) {
var imeMode = this.isImeMode();
// If we're in IE and we detect an IME input on keyDown then activate
// the IME, otherwise if the imeMode was previously active, deactivate.
if (!imeMode && e.keyCode == goog.events.KeyCodes.WIN_IME) {
this.handleImeActivate_(e);
} else if (imeMode && e.keyCode != goog.events.KeyCodes.WIN_IME) {
if (goog.events.ImeHandler.isImeDeactivateKeyEvent_(e)) {
this.handleImeDeactivate_(e);
}
} else if (imeMode) {
this.processImeComposition_(e);
}
}
// Safari on Mac doesn't send IME events in the right order so that we must
// ignore some modifier key events to insert IME text correctly.
if (goog.events.ImeHandler.isImeDeactivateKeyEvent_(e)) {
this.lastKeyCode_ = e.keyCode;
}
};
/**
* Handles a textInput event.
* @param {!goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleTextInput_ = function(e) {
// Some WebKit-based browsers including Safari 4 don't send composition
// events. So, we turn down IME mode when it's still there.
if (!goog.events.ImeHandler.USES_COMPOSITION_EVENTS &&
goog.userAgent.WEBKIT &&
this.lastKeyCode_ == goog.events.KeyCodes.WIN_IME &&
this.isImeMode()) {
this.handleImeDeactivate_(e);
}
};
/**
* Handles the key up event for any IME activity. This handler is just used to
* prevent activating IME unnecessary in Safari at this time.
* @param {!goog.events.BrowserEvent} e The event.
* @private
*/
goog.events.ImeHandler.prototype.handleKeyUpSafari4_ = function(e) {
if (this.isImeMode()) {
switch (e.keyCode) {
// These keyup events indicates that IME text has been committed or
// cancelled. We should turn off IME mode when these keyup events
// received.
case goog.events.KeyCodes.ENTER:
case goog.events.KeyCodes.TAB:
case goog.events.KeyCodes.ESC:
this.handleImeDeactivate_(e);
break;
}
}
};
/**
* Returns whether the given event should be treated as an IME
* deactivation trigger.
* @param {!goog.events.Event} e The event.
* @return {boolean} Whether the given event is an IME deactivate trigger.
* @private
*/
goog.events.ImeHandler.isImeDeactivateKeyEvent_ = function(e) {
// Which key events involve IME deactivation depends on the user's
// environment (i.e. browsers, platforms, and IMEs). Usually Shift key
// and Ctrl key does not involve IME deactivation, so we currently assume
// that these keys are not IME deactivation trigger.
switch (e.keyCode) {
case goog.events.KeyCodes.SHIFT:
case goog.events.KeyCodes.CTRL:
return false;
default:
return true;
}
};
/** @override */
goog.events.ImeHandler.prototype.disposeInternal = function() {
this.handler_.dispose();
this.keyUpHandler_.dispose();
this.el_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definition of the goog.events.EventWrapper interface.
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.events.EventWrapper');
/**
* Interface for event wrappers.
* @interface
*/
goog.events.EventWrapper = function() {
};
/**
* Adds an event listener using the wrapper on a DOM Node or an object that has
* implemented {@link goog.events.EventTarget}. A listener can only be added
* once to an object.
*
* @param {EventTarget|goog.events.EventTarget} src The node to listen to
* events on.
* @param {Function|Object} listener Callback method, or an object with a
* handleEvent function.
* @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
* false).
* @param {Object=} opt_scope Element in whose scope to call the listener.
* @param {goog.events.EventHandler=} opt_eventHandler Event handler to add
* listener to.
*/
goog.events.EventWrapper.prototype.listen = function(src, listener, opt_capt,
opt_scope, opt_eventHandler) {
};
/**
* Removes an event listener added using goog.events.EventWrapper.listen.
*
* @param {EventTarget|goog.events.EventTarget} src The node to remove listener
* from.
* @param {Function|Object} listener Callback method, or an object with a
* handleEvent function.
* @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
* false).
* @param {Object=} opt_scope Element in whose scope to call the listener.
* @param {goog.events.EventHandler=} opt_eventHandler Event handler to remove
* listener from.
*/
goog.events.EventWrapper.prototype.unlisten = function(src, listener, opt_capt,
opt_scope, opt_eventHandler) {
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This event wrapper will dispatch an event when the user uses
* the mouse wheel to scroll an element. You can get the direction by checking
* the deltaX and deltaY properties of the event.
*
* This class aims to smooth out inconsistencies between browser platforms with
* regards to mousewheel events, but we do not cover every possible
* software/hardware combination out there, some of which occasionally produce
* very large deltas in mousewheel events. If your application wants to guard
* against extremely large deltas, use the setMaxDeltaX and setMaxDeltaY APIs
* to set maximum values that make sense for your application.
*
* @author arv@google.com (Erik Arvidsson)
* @see ../demos/mousewheelhandler.html
*/
goog.provide('goog.events.MouseWheelEvent');
goog.provide('goog.events.MouseWheelHandler');
goog.provide('goog.events.MouseWheelHandler.EventType');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventTarget');
goog.require('goog.math');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* This event handler allows you to catch mouse wheel events in a consistent
* manner.
* @param {Element|Document} element The element to listen to the mouse wheel
* event on.
* @param {boolean=} opt_capture Whether to handle the mouse wheel event in
* capture phase.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.events.MouseWheelHandler = function(element, opt_capture) {
goog.events.EventTarget.call(this);
/**
* This is the element that we will listen to the real mouse wheel events on.
* @type {Element|Document}
* @private
*/
this.element_ = element;
var rtlElement = goog.dom.isElement(this.element_) ?
/** @type {Element} */ (this.element_) :
(this.element_ ? /** @type {Document} */ (this.element_).body : null);
/**
* True if the element exists and is RTL, false otherwise.
* @type {boolean}
* @private
*/
this.isRtl_ = !!rtlElement && goog.style.isRightToLeft(rtlElement);
var type = goog.userAgent.GECKO ? 'DOMMouseScroll' : 'mousewheel';
/**
* The key returned from the goog.events.listen.
* @type {goog.events.Key}
* @private
*/
this.listenKey_ = goog.events.listen(this.element_, type, this, opt_capture);
};
goog.inherits(goog.events.MouseWheelHandler, goog.events.EventTarget);
/**
* Enum type for the events fired by the mouse wheel handler.
* @enum {string}
*/
goog.events.MouseWheelHandler.EventType = {
MOUSEWHEEL: 'mousewheel'
};
/**
* Optional maximum magnitude for x delta on each mousewheel event.
* @type {number|undefined}
* @private
*/
goog.events.MouseWheelHandler.prototype.maxDeltaX_;
/**
* Optional maximum magnitude for y delta on each mousewheel event.
* @type {number|undefined}
* @private
*/
goog.events.MouseWheelHandler.prototype.maxDeltaY_;
/**
* @param {number} maxDeltaX Maximum magnitude for x delta on each mousewheel
* event. Should be non-negative.
*/
goog.events.MouseWheelHandler.prototype.setMaxDeltaX = function(maxDeltaX) {
this.maxDeltaX_ = maxDeltaX;
};
/**
* @param {number} maxDeltaY Maximum magnitude for y delta on each mousewheel
* event. Should be non-negative.
*/
goog.events.MouseWheelHandler.prototype.setMaxDeltaY = function(maxDeltaY) {
this.maxDeltaY_ = maxDeltaY;
};
/**
* Handles the events on the element.
* @param {goog.events.BrowserEvent} e The underlying browser event.
*/
goog.events.MouseWheelHandler.prototype.handleEvent = function(e) {
var deltaX = 0;
var deltaY = 0;
var detail = 0;
var be = e.getBrowserEvent();
if (be.type == 'mousewheel') {
var wheelDeltaScaleFactor = 1;
if (goog.userAgent.IE ||
goog.userAgent.WEBKIT &&
(goog.userAgent.WINDOWS || goog.userAgent.isVersion('532.0'))) {
// In IE we get a multiple of 120; we adjust to a multiple of 3 to
// represent number of lines scrolled (like Gecko).
// Newer versions of Webkit match IE behavior, and WebKit on
// Windows also matches IE behavior.
// See bug https://bugs.webkit.org/show_bug.cgi?id=24368
wheelDeltaScaleFactor = 40;
}
detail = goog.events.MouseWheelHandler.smartScale_(
-be.wheelDelta, wheelDeltaScaleFactor);
if (goog.isDef(be.wheelDeltaX)) {
// Webkit has two properties to indicate directional scroll, and
// can scroll both directions at once.
deltaX = goog.events.MouseWheelHandler.smartScale_(
-be.wheelDeltaX, wheelDeltaScaleFactor);
deltaY = goog.events.MouseWheelHandler.smartScale_(
-be.wheelDeltaY, wheelDeltaScaleFactor);
} else {
deltaY = detail;
}
// Historical note: Opera (pre 9.5) used to negate the detail value.
} else { // Gecko
// Gecko returns multiple of 3 (representing the number of lines scrolled)
detail = be.detail;
// Gecko sometimes returns really big values if the user changes settings to
// scroll a whole page per scroll
if (detail > 100) {
detail = 3;
} else if (detail < -100) {
detail = -3;
}
// Firefox 3.1 adds an axis field to the event to indicate direction of
// scroll. See https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
if (goog.isDef(be.axis) && be.axis === be.HORIZONTAL_AXIS) {
deltaX = detail;
} else {
deltaY = detail;
}
}
if (goog.isNumber(this.maxDeltaX_)) {
deltaX = goog.math.clamp(deltaX, -this.maxDeltaX_, this.maxDeltaX_);
}
if (goog.isNumber(this.maxDeltaY_)) {
deltaY = goog.math.clamp(deltaY, -this.maxDeltaY_, this.maxDeltaY_);
}
// Don't clamp 'detail', since it could be ambiguous which axis it refers to
// and because it's informally deprecated anyways.
// For horizontal scrolling we need to flip the value for RTL grids.
if (this.isRtl_) {
deltaX = -deltaX;
}
var newEvent = new goog.events.MouseWheelEvent(detail, be, deltaX, deltaY);
this.dispatchEvent(newEvent);
};
/**
* Helper for scaling down a mousewheel delta by a scale factor, if appropriate.
* @param {number} mouseWheelDelta Delta from a mouse wheel event. Expected to
* be an integer.
* @param {number} scaleFactor Factor to scale the delta down by. Expected to
* be an integer.
* @return {number} Scaled-down delta value, or the original delta if the
* scaleFactor does not appear to be applicable.
* @private
*/
goog.events.MouseWheelHandler.smartScale_ = function(mouseWheelDelta,
scaleFactor) {
// The basic problem here is that in Webkit on Mac and Linux, we can get two
// very different types of mousewheel events: from continuous devices
// (touchpads, Mighty Mouse) or non-continuous devices (normal wheel mice).
//
// Non-continuous devices in Webkit get their wheel deltas scaled up to
// behave like IE. Continuous devices return much smaller unscaled values
// (which most of the time will not be cleanly divisible by the IE scale
// factor), so we should not try to normalize them down.
//
// Detailed discussion:
// https://bugs.webkit.org/show_bug.cgi?id=29601
// http://trac.webkit.org/browser/trunk/WebKit/chromium/src/mac/WebInputEventFactory.mm#L1063
if (goog.userAgent.WEBKIT &&
(goog.userAgent.MAC || goog.userAgent.LINUX) &&
(mouseWheelDelta % scaleFactor) != 0) {
return mouseWheelDelta;
} else {
return mouseWheelDelta / scaleFactor;
}
};
/** @override */
goog.events.MouseWheelHandler.prototype.disposeInternal = function() {
goog.events.MouseWheelHandler.superClass_.disposeInternal.call(this);
goog.events.unlistenByKey(this.listenKey_);
this.listenKey_ = null;
};
/**
* A base class for mouse wheel events. This is used with the
* MouseWheelHandler.
*
* @param {number} detail The number of rows the user scrolled.
* @param {Event} browserEvent Browser event object.
* @param {number} deltaX The number of rows the user scrolled in the X
* direction.
* @param {number} deltaY The number of rows the user scrolled in the Y
* direction.
* @constructor
* @extends {goog.events.BrowserEvent}
*/
goog.events.MouseWheelEvent = function(detail, browserEvent, deltaX, deltaY) {
goog.events.BrowserEvent.call(this, browserEvent);
this.type = goog.events.MouseWheelHandler.EventType.MOUSEWHEEL;
/**
* The number of lines the user scrolled
* @type {number}
* NOTE: Informally deprecated. Use deltaX and deltaY instead, they provide
* more information.
*/
this.detail = detail;
/**
* The number of "lines" scrolled in the X direction.
*
* Note that not all browsers provide enough information to distinguish
* horizontal and vertical scroll events, so for these unsupported browsers,
* we will always have a deltaX of 0, even if the user scrolled their mouse
* wheel or trackpad sideways.
*
* Currently supported browsers are Webkit and Firefox 3.1 or later.
*
* @type {number}
*/
this.deltaX = deltaX;
/**
* The number of lines scrolled in the Y direction.
* @type {number}
*/
this.deltaY = deltaY;
};
goog.inherits(goog.events.MouseWheelEvent, goog.events.BrowserEvent);
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a 'paste' event detector that works consistently
* across different browsers.
*
* IE5, IE6, IE7, Safari3.0 and FF3.0 all fire 'paste' events on textareas.
* FF2 doesn't. This class uses 'paste' events when they are available
* and uses heuristics to detect the 'paste' event when they are not available.
*
* Known issue: will not detect paste events in FF2 if you pasted exactly the
* same existing text.
* Known issue: Opera + Mac doesn't work properly because of the meta key. We
* can probably fix that. TODO(user): {@link KeyboardShortcutHandler} does not
* work either very well with opera + mac. fix that.
*
* @supported IE5, IE6, IE7, Safari3.0, Chrome, FF2.0 (linux) and FF3.0 and
* Opera (mac and windows).
*
* @see ../demos/pastehandler.html
*/
goog.provide('goog.events.PasteHandler');
goog.provide('goog.events.PasteHandler.EventType');
goog.provide('goog.events.PasteHandler.State');
goog.require('goog.Timer');
goog.require('goog.async.ConditionalDelay');
goog.require('goog.debug.Logger');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
/**
* A paste event detector. Gets an {@code element} as parameter and fires
* {@code goog.events.PasteHandler.EventType.PASTE} events when text is
* pasted in the {@code element}. Uses heuristics to detect paste events in FF2.
* See more details of the heuristic on {@link #handleEvent_}.
*
* @param {Element} element The textarea element we are listening on.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.events.PasteHandler = function(element) {
goog.events.EventTarget.call(this);
/**
* The element that you want to listen for paste events on.
* @type {Element}
* @private
*/
this.element_ = element;
/**
* The last known value of the element. Kept to check if things changed. See
* more details on {@link #handleEvent_}.
* @type {string}
* @private
*/
this.oldValue_ = this.element_.value;
/**
* Handler for events.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
/**
* The last time an event occurred on the element. Kept to check whether the
* last event was generated by two input events or by multiple fast key events
* that got swallowed. See more details on {@link #handleEvent_}.
* @type {number}
* @private
*/
this.lastTime_ = goog.now();
if (goog.userAgent.WEBKIT ||
goog.userAgent.IE ||
goog.userAgent.GECKO && goog.userAgent.isVersion('1.9')) {
// Most modern browsers support the paste event.
this.eventHandler_.listen(element, goog.events.EventType.PASTE,
this.dispatch_);
} else {
// But FF2 and Opera doesn't. we listen for a series of events to try to
// find out if a paste occurred. We enumerate and cover all known ways to
// paste text on textareas. See more details on {@link #handleEvent_}.
var events = [
goog.events.EventType.KEYDOWN,
goog.events.EventType.BLUR,
goog.events.EventType.FOCUS,
goog.events.EventType.MOUSEOVER,
'input'
];
this.eventHandler_.listen(element, events, this.handleEvent_);
}
/**
* ConditionalDelay used to poll for changes in the text element once users
* paste text. Browsers fire paste events BEFORE the text is actually present
* in the element.value property.
* @type {goog.async.ConditionalDelay}
* @private
*/
this.delay_ = new goog.async.ConditionalDelay(
goog.bind(this.checkUpdatedText_, this));
};
goog.inherits(goog.events.PasteHandler, goog.events.EventTarget);
/**
* The types of events fired by this class.
* @enum {string}
*/
goog.events.PasteHandler.EventType = {
/**
* Dispatched as soon as the paste event is detected, but before the pasted
* text has been added to the text element we're listening to.
*/
PASTE: 'paste',
/**
* Dispatched after detecting a change to the value of text element
* (within 200msec of receiving the PASTE event).
*/
AFTER_PASTE: 'after_paste'
};
/**
* The mandatory delay we expect between two {@code input} events, used to
* differentiated between non key paste events and key events.
* @type {number}
*/
goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER =
400;
/**
* The period between each time we check whether the pasted text appears in the
* text element or not.
* @type {number}
* @private
*/
goog.events.PasteHandler.PASTE_POLLING_PERIOD_MS_ = 50;
/**
* The maximum amount of time we want to poll for changes.
* @type {number}
* @private
*/
goog.events.PasteHandler.PASTE_POLLING_TIMEOUT_MS_ = 200;
/**
* The states that this class can be found, on the paste detection algorithm.
* @enum {string}
*/
goog.events.PasteHandler.State = {
INIT: 'init',
FOCUSED: 'focused',
TYPING: 'typing'
};
/**
* The initial state of the paste detection algorithm.
* @type {goog.events.PasteHandler.State}
* @private
*/
goog.events.PasteHandler.prototype.state_ =
goog.events.PasteHandler.State.INIT;
/**
* The previous event that caused us to be on the current state.
* @type {?string}
* @private
*/
goog.events.PasteHandler.prototype.previousEvent_;
/**
* A logger, used to help us debug the algorithm.
* @type {goog.debug.Logger}
* @private
*/
goog.events.PasteHandler.prototype.logger_ =
goog.debug.Logger.getLogger('goog.events.PasteHandler');
/** @override */
goog.events.PasteHandler.prototype.disposeInternal = function() {
goog.events.PasteHandler.superClass_.disposeInternal.call(this);
this.eventHandler_.dispose();
this.eventHandler_ = null;
this.delay_.dispose();
this.delay_ = null;
};
/**
* Returns the current state of the paste detection algorithm. Used mostly for
* testing.
* @return {goog.events.PasteHandler.State} The current state of the class.
*/
goog.events.PasteHandler.prototype.getState = function() {
return this.state_;
};
/**
* Returns the event handler.
* @return {goog.events.EventHandler} The event handler.
* @protected
*/
goog.events.PasteHandler.prototype.getEventHandler = function() {
return this.eventHandler_;
};
/**
* Checks whether the element.value property was updated, and if so, dispatches
* the event that let clients know that the text is available.
* @return {boolean} Whether the polling should stop or not, based on whether
* we found a text change or not.
* @private
*/
goog.events.PasteHandler.prototype.checkUpdatedText_ = function() {
if (this.oldValue_ == this.element_.value) {
return false;
}
this.logger_.info('detected textchange after paste');
this.dispatchEvent(goog.events.PasteHandler.EventType.AFTER_PASTE);
return true;
};
/**
* Dispatches the paste event.
* @param {goog.events.BrowserEvent} e The underlying browser event.
* @private
*/
goog.events.PasteHandler.prototype.dispatch_ = function(e) {
var event = new goog.events.BrowserEvent(e.getBrowserEvent());
event.type = goog.events.PasteHandler.EventType.PASTE;
this.dispatchEvent(event);
// Starts polling for updates in the element.value property so we can tell
// when do dispatch the AFTER_PASTE event. (We do an initial check after an
// async delay of 0 msec since some browsers update the text right away and
// our poller will always wait one period before checking).
goog.Timer.callOnce(function() {
if (!this.checkUpdatedText_()) {
this.delay_.start(
goog.events.PasteHandler.PASTE_POLLING_PERIOD_MS_,
goog.events.PasteHandler.PASTE_POLLING_TIMEOUT_MS_);
}
}, 0, this);
};
/**
* The main event handler which implements a state machine.
*
* To handle FF2, we enumerate and cover all the known ways a user can paste:
*
* 1) ctrl+v, shift+insert, cmd+v
* 2) right click -> paste
* 3) edit menu -> paste
* 4) drag and drop
* 5) middle click
*
* (1) is easy and can be detected by listening for key events and finding out
* which keys are pressed. (2), (3), (4) and (5) do not generate a key event,
* so we need to listen for more than that. (2-5) all generate 'input' events,
* but so does key events. So we need to have some sort of 'how did the input
* event was generated' history algorithm.
*
* (2) is an interesting case in Opera on a Mac: since Macs does not have two
* buttons, right clicking involves pressing the CTRL key. Even more interesting
* is the fact that opera does NOT set the e.ctrlKey bit. Instead, it sets
* e.keyCode = 0.
* {@link http://www.quirksmode.org/js/keys.html}
*
* (1) is also an interesting case in Opera on a Mac: Opera is the only browser
* covered by this class that can detect the cmd key (FF2 can't apparently). And
* it fires e.keyCode = 17, which is the CTRL key code.
* {@link http://www.quirksmode.org/js/keys.html}
*
* NOTE(user, pbarry): There is an interesting thing about (5): on Linux, (5)
* pastes the last thing that you highlighted, not the last thing that you
* ctrl+c'ed. This code will still generate a {@code PASTE} event though.
*
* We enumerate all the possible steps a user can take to paste text and we
* implemented the transition between the steps in a state machine. The
* following is the design of the state machine:
*
* matching paths:
*
* (1) happens on INIT -> FOCUSED -> TYPING -> [e.ctrlKey & e.keyCode = 'v']
* (2-3) happens on INIT -> FOCUSED -> [input event happened]
* (4) happens on INIT -> [mouseover && text changed]
*
* non matching paths:
*
* user is typing normally
* INIT -> FOCUS -> TYPING -> INPUT -> INIT
*
* @param {goog.events.BrowserEvent} e The underlying browser event.
* @private
*/
goog.events.PasteHandler.prototype.handleEvent_ = function(e) {
// transition between states happen at each browser event, and depend on the
// current state, the event that led to this state, and the event input.
switch (this.state_) {
case goog.events.PasteHandler.State.INIT: {
this.handleUnderInit_(e);
break;
}
case goog.events.PasteHandler.State.FOCUSED: {
this.handleUnderFocused_(e);
break;
}
case goog.events.PasteHandler.State.TYPING: {
this.handleUnderTyping_(e);
break;
}
default: {
this.logger_.severe('invalid ' + this.state_ + ' state');
}
}
this.lastTime_ = goog.now();
this.oldValue_ = this.element_.value;
this.logger_.info(e.type + ' -> ' + this.state_);
this.previousEvent_ = e.type;
};
/**
* {@code goog.events.PasteHandler.EventType.INIT} is the first initial state
* the textarea is found. You can only leave this state by setting focus on the
* textarea, which is how users will input text. You can also paste things using
* drag and drop, which will not generate a {@code goog.events.EventType.FOCUS}
* event, but will generate a {@code goog.events.EventType.MOUSEOVER}.
*
* For browsers that support the 'paste' event, we match it and stay on the same
* state.
*
* @param {goog.events.BrowserEvent} e The underlying browser event.
* @private
*/
goog.events.PasteHandler.prototype.handleUnderInit_ = function(e) {
switch (e.type) {
case goog.events.EventType.BLUR: {
this.state_ = goog.events.PasteHandler.State.INIT;
break;
}
case goog.events.EventType.FOCUS: {
this.state_ = goog.events.PasteHandler.State.FOCUSED;
break;
}
case goog.events.EventType.MOUSEOVER: {
this.state_ = goog.events.PasteHandler.State.INIT;
if (this.element_.value != this.oldValue_) {
this.logger_.info('paste by dragdrop while on init!');
this.dispatch_(e);
}
break;
}
default: {
this.logger_.severe('unexpected event ' + e.type + 'during init');
}
}
};
/**
* {@code goog.events.PasteHandler.EventType.FOCUSED} is typically the second
* state the textarea will be, which is followed by the {@code INIT} state. On
* this state, users can paste in three different ways: edit -> paste,
* right click -> paste and drag and drop.
*
* The latter will generate a {@code goog.events.EventType.MOUSEOVER} event,
* which we match by making sure the textarea text changed. The first two will
* generate an 'input', which we match by making sure it was NOT generated by a
* key event (which also generates an 'input' event).
*
* Unfortunately, in Firefox, if you type fast, some KEYDOWN events are
* swallowed but an INPUT event may still happen. That means we need to
* differentiate between two consecutive INPUT events being generated either by
* swallowed key events OR by a valid edit -> paste -> edit -> paste action. We
* do this by checking a minimum time between the two events. This heuristic
* seems to work well, but it is obviously a heuristic :).
*
* @param {goog.events.BrowserEvent} e The underlying browser event.
* @private
*/
goog.events.PasteHandler.prototype.handleUnderFocused_ = function(e) {
switch (e.type) {
case 'input' : {
// there are two different events that happen in practice that involves
// consecutive 'input' events. we use a heuristic to differentiate
// between the one that generates a valid paste action and the one that
// doesn't.
// @see testTypingReallyFastDispatchesTwoInputEventsBeforeTheKEYDOWNEvent
// and
// @see testRightClickRightClickAlsoDispatchesTwoConsecutiveInputEvents
// Notice that an 'input' event may be also triggered by a 'middle click'
// paste event, which is described in
// @see testMiddleClickWithoutFocusTriggersPasteEvent
var minimumMilisecondsBetweenInputEvents = this.lastTime_ +
goog.events.PasteHandler.
MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER;
if (goog.now() > minimumMilisecondsBetweenInputEvents ||
this.previousEvent_ == goog.events.EventType.FOCUS) {
this.logger_.info('paste by textchange while focused!');
this.dispatch_(e);
}
break;
}
case goog.events.EventType.BLUR: {
this.state_ = goog.events.PasteHandler.State.INIT;
break;
}
case goog.events.EventType.KEYDOWN: {
this.logger_.info('key down ... looking for ctrl+v');
// Opera + MAC does not set e.ctrlKey. Instead, it gives me e.keyCode = 0.
// http://www.quirksmode.org/js/keys.html
if (goog.userAgent.MAC && goog.userAgent.OPERA && e.keyCode == 0 ||
goog.userAgent.MAC && goog.userAgent.OPERA && e.keyCode == 17) {
break;
}
this.state_ = goog.events.PasteHandler.State.TYPING;
break;
}
case goog.events.EventType.MOUSEOVER: {
if (this.element_.value != this.oldValue_) {
this.logger_.info('paste by dragdrop while focused!');
this.dispatch_(e);
}
break;
}
default: {
this.logger_.severe('unexpected event ' + e.type + ' during focused');
}
}
};
/**
* {@code goog.events.PasteHandler.EventType.TYPING} is the third state
* this class can be. It exists because each KEYPRESS event will ALSO generate
* an INPUT event (because the textarea value changes), and we need to
* differentiate between an INPUT event generated by a key event and an INPUT
* event generated by edit -> paste actions.
*
* This is the state that we match the ctrl+v pattern.
*
* @param {goog.events.BrowserEvent} e The underlying browser event.
* @private
*/
goog.events.PasteHandler.prototype.handleUnderTyping_ = function(e) {
switch (e.type) {
case 'input' : {
this.state_ = goog.events.PasteHandler.State.FOCUSED;
break;
}
case goog.events.EventType.BLUR: {
this.state_ = goog.events.PasteHandler.State.INIT;
break;
}
case goog.events.EventType.KEYDOWN: {
if (e.ctrlKey && e.keyCode == goog.events.KeyCodes.V ||
e.shiftKey && e.keyCode == goog.events.KeyCodes.INSERT ||
e.metaKey && e.keyCode == goog.events.KeyCodes.V) {
this.logger_.info('paste by ctrl+v while keypressed!');
this.dispatch_(e);
}
break;
}
case goog.events.EventType.MOUSEOVER: {
if (this.element_.value != this.oldValue_) {
this.logger_.info('paste by dragdrop while keypressed!');
this.dispatch_(e);
}
break;
}
default: {
this.logger_.severe('unexpected event ' + e.type + ' during keypressed');
}
}
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Action event wrapper implementation.
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.events.actionEventWrapper');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.events.EventWrapper');
goog.require('goog.events.KeyCodes');
/**
* Event wrapper for action handling. Fires when an element is activated either
* by clicking it or by focusing it and pressing Enter.
*
* @constructor
* @implements {goog.events.EventWrapper}
* @private
*/
goog.events.ActionEventWrapper_ = function() {
};
/**
* Singleton instance of ActionEventWrapper_.
* @type {goog.events.ActionEventWrapper_}
*/
goog.events.actionEventWrapper = new goog.events.ActionEventWrapper_();
/**
* Event types used by the wrapper.
*
* @type {Array.<goog.events.EventType>}
* @private
*/
goog.events.ActionEventWrapper_.EVENT_TYPES_ = [
goog.events.EventType.CLICK,
goog.userAgent.GECKO ?
goog.events.EventType.KEYPRESS :
goog.events.EventType.KEYDOWN
];
/**
* Adds an event listener using the wrapper on a DOM Node or an object that has
* implemented {@link goog.events.EventTarget}. A listener can only be added
* once to an object.
*
* @param {EventTarget|goog.events.EventTarget} target The node to listen to
* events on.
* @param {Function|Object} listener Callback method, or an object with a
* handleEvent function.
* @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
* false).
* @param {Object=} opt_scope Element in whose scope to call the listener.
* @param {goog.events.EventHandler=} opt_eventHandler Event handler to add
* listener to.
* @override
*/
goog.events.ActionEventWrapper_.prototype.listen = function(target, listener,
opt_capt, opt_scope, opt_eventHandler) {
var callback = function(e) {
if (e.type == goog.events.EventType.CLICK && e.isMouseActionButton()) {
listener.call(opt_scope, e);
} else if (e.keyCode == goog.events.KeyCodes.ENTER ||
e.keyCode == goog.events.KeyCodes.MAC_ENTER) {
// convert keydown to keypress for backward compatibility.
e.type = goog.events.EventType.KEYPRESS;
listener.call(opt_scope, e);
}
};
callback.listener_ = listener;
callback.scope_ = opt_scope;
if (opt_eventHandler) {
opt_eventHandler.listen(target,
goog.events.ActionEventWrapper_.EVENT_TYPES_,
callback, opt_capt);
} else {
goog.events.listen(target,
goog.events.ActionEventWrapper_.EVENT_TYPES_,
callback, opt_capt);
}
};
/**
* Removes an event listener added using goog.events.EventWrapper.listen.
*
* @param {EventTarget|goog.events.EventTarget} target The node to remove
* listener from.
* @param {Function|Object} listener Callback method, or an object with a
* handleEvent function.
* @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
* false).
* @param {Object=} opt_scope Element in whose scope to call the listener.
* @param {goog.events.EventHandler=} opt_eventHandler Event handler to remove
* listener from.
* @override
*/
goog.events.ActionEventWrapper_.prototype.unlisten = function(target, listener,
opt_capt, opt_scope, opt_eventHandler) {
for (var type, j = 0; type = goog.events.ActionEventWrapper_.EVENT_TYPES_[j];
j++) {
var listeners = goog.events.getListeners(target, type, !!opt_capt);
for (var obj, i = 0; obj = listeners[i]; i++) {
if (obj.listener.listener_ == listener &&
obj.listener.scope_ == opt_scope) {
if (opt_eventHandler) {
opt_eventHandler.unlisten(target, type, obj.listener, opt_capt,
opt_scope);
} else {
goog.events.unlisten(target, type, obj.listener, opt_capt, opt_scope);
}
break;
}
}
}
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Constant declarations for common key codes.
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.events.KeyNames');
/**
* Key names for common characters.
*
* This list is not localized and therefore some of the key codes are not
* correct for non-US keyboard layouts.
*
* @see goog.events.KeyCodes
* @enum {string}
*/
goog.events.KeyNames = {
8: 'backspace',
9: 'tab',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
19: 'pause',
20: 'caps-lock',
27: 'esc',
32: 'space',
33: 'pg-up',
34: 'pg-down',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'insert',
46: 'delete',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
59: 'semicolon',
61: 'equals',
65: 'a',
66: 'b',
67: 'c',
68: 'd',
69: 'e',
70: 'f',
71: 'g',
72: 'h',
73: 'i',
74: 'j',
75: 'k',
76: 'l',
77: 'm',
78: 'n',
79: 'o',
80: 'p',
81: 'q',
82: 'r',
83: 's',
84: 't',
85: 'u',
86: 'v',
87: 'w',
88: 'x',
89: 'y',
90: 'z',
93: 'context',
96: 'num-0',
97: 'num-1',
98: 'num-2',
99: 'num-3',
100: 'num-4',
101: 'num-5',
102: 'num-6',
103: 'num-7',
104: 'num-8',
105: 'num-9',
106: 'num-multiply',
107: 'num-plus',
109: 'num-minus',
110: 'num-period',
111: 'num-division',
112: 'f1',
113: 'f2',
114: 'f3',
115: 'f4',
116: 'f5',
117: 'f6',
118: 'f7',
119: 'f8',
120: 'f9',
121: 'f10',
122: 'f11',
123: 'f12',
186: 'semicolon',
187: 'equals',
189: 'dash',
188: ',',
190: '.',
191: '/',
192: '~',
219: 'open-square-bracket',
220: '\\',
221: 'close-square-bracket',
222: 'single-quote',
224: 'win'
};
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.