diff options
author | twellington <twellington@chromium.org> | 2015-05-11 17:32:33 -0700 |
---|---|---|
committer | Commit bot <commit-bot@chromium.org> | 2015-05-12 00:32:38 +0000 |
commit | 1b13f371bfe3c5d5eba8689cdea916c16dd79f84 (patch) | |
tree | a4db30e7b7f2850f5238348eaf72b9d832019732 /third_party | |
parent | 491fea8c41977b1557a79cf2f53d4b60ecd159d9 (diff) | |
download | chromium_src-1b13f371bfe3c5d5eba8689cdea916c16dd79f84.zip chromium_src-1b13f371bfe3c5d5eba8689cdea916c16dd79f84.tar.gz chromium_src-1b13f371bfe3c5d5eba8689cdea916c16dd79f84.tar.bz2 |
Update third_party/document_image_extractor
Update to newer version (closure dependencies have been removed).
BUG=485567
Review URL: https://codereview.chromium.org/1138123002
Cr-Commit-Position: refs/heads/master@{#329297}
Diffstat (limited to 'third_party')
116 files changed, 604 insertions, 38036 deletions
diff --git a/third_party/document_image_extractor/README.chromium b/third_party/document_image_extractor/README.chromium index adda872..f0173e1 100644 --- a/third_party/document_image_extractor/README.chromium +++ b/third_party/document_image_extractor/README.chromium @@ -1,8 +1,8 @@ Name: Document image extractor scripts and dependencies Short Name: document_image_extractor URL: google3/image/collections/extension/ -Version: 0 -Date: 3/26/2015 +Version: 1 +Date: 4/11/2015 Security Critical: No License: BSD @@ -11,5 +11,4 @@ The document image extractor is used to extract all images from a webpage and assign each one a relevance. Local Modifications: -constant.js: stripped of all unneeded constants. -dom_controller.js: removed unused depedency on GenUtils +None diff --git a/third_party/document_image_extractor/document_image_extractor_files.gypi b/third_party/document_image_extractor/document_image_extractor_files.gypi index 466b898..6d75f0f 100644 --- a/third_party/document_image_extractor/document_image_extractor_files.gypi +++ b/third_party/document_image_extractor/document_image_extractor_files.gypi @@ -7,70 +7,14 @@ # List of dependencies for document_image_extractor.js generated by closurebuilder.py 'document_image_extractor_js_files': [ 'src/ad_element_filter.js', - 'src/constants.js', - 'src/document_feature_extractor.js', 'src/document_feature.js', - 'src/document_image_extractor.js', + 'src/document_feature_extractor.js', 'src/document_image.js', + 'src/document_image_extractor.js', + 'src/dom_utils.js', 'src/element_filter.js', + 'src/size.js', 'src/visible_element_filter.js', - 'third_party/closure-library/closure/goog/array/array.js', - 'third_party/closure-library/closure/goog/asserts/asserts.js', - 'third_party/closure-library/closure/goog/base.js', - 'third_party/closure-library/closure/goog/debug/debug.js', - 'third_party/closure-library/closure/goog/debug/error.js', - 'third_party/closure-library/closure/goog/debug/logbuffer.js', - 'third_party/closure-library/closure/goog/debug/logger.js', - 'third_party/closure-library/closure/goog/debug/logrecord.js', - 'third_party/closure-library/closure/goog/disposable/disposable.js', - 'third_party/closure-library/closure/goog/disposable/idisposable.js', - 'third_party/closure-library/closure/goog/dom/browserfeature.js', - 'third_party/closure-library/closure/goog/dom/classlist.js', - 'third_party/closure-library/closure/goog/dom/dom.js', - 'third_party/closure-library/closure/goog/dom/nodetype.js', - 'third_party/closure-library/closure/goog/dom/safe.js', - 'third_party/closure-library/closure/goog/dom/tagname.js', - 'third_party/closure-library/closure/goog/dom/tags.js', - 'third_party/closure-library/closure/goog/dom/vendor.js', - 'third_party/closure-library/closure/goog/events/browserevent.js', - 'third_party/closure-library/closure/goog/events/browserfeature.js', - 'third_party/closure-library/closure/goog/events/event.js', - 'third_party/closure-library/closure/goog/events/eventid.js', - 'third_party/closure-library/closure/goog/events/eventtype.js', - 'third_party/closure-library/closure/goog/fs/url.js', - 'third_party/closure-library/closure/goog/functions/functions.js', - 'third_party/closure-library/closure/goog/html/safehtml.js', - 'third_party/closure-library/closure/goog/html/safescript.js', - 'third_party/closure-library/closure/goog/html/safestyle.js', - 'third_party/closure-library/closure/goog/html/safestylesheet.js', - 'third_party/closure-library/closure/goog/html/safeurl.js', - 'third_party/closure-library/closure/goog/html/trustedresourceurl.js', - 'third_party/closure-library/closure/goog/html/uncheckedconversions.js', - 'third_party/closure-library/closure/goog/i18n/bidi.js', - 'third_party/closure-library/closure/goog/iter/iter.js', - 'third_party/closure-library/closure/goog/labs/useragent/browser.js', - 'third_party/closure-library/closure/goog/labs/useragent/engine.js', - 'third_party/closure-library/closure/goog/labs/useragent/platform.js', - 'third_party/closure-library/closure/goog/labs/useragent/util.js', - 'third_party/closure-library/closure/goog/log/log.js', - 'third_party/closure-library/closure/goog/math/box.js', - 'third_party/closure-library/closure/goog/math/coordinate.js', - 'third_party/closure-library/closure/goog/math/math.js', - 'third_party/closure-library/closure/goog/math/rect.js', - 'third_party/closure-library/closure/goog/math/size.js', - 'third_party/closure-library/closure/goog/object/object.js', - 'third_party/closure-library/closure/goog/reflect/reflect.js', - 'third_party/closure-library/closure/goog/string/const.js', - 'third_party/closure-library/closure/goog/string/string.js', - 'third_party/closure-library/closure/goog/string/typedstring.js', - 'third_party/closure-library/closure/goog/structs/collection.js', - 'third_party/closure-library/closure/goog/structs/map.js', - 'third_party/closure-library/closure/goog/structs/set.js', - 'third_party/closure-library/closure/goog/structs/structs.js', - 'third_party/closure-library/closure/goog/style/style.js', - 'third_party/closure-library/closure/goog/uri/uri.js', - 'third_party/closure-library/closure/goog/uri/utils.js', - 'third_party/closure-library/closure/goog/useragent/useragent.js', ], }, } diff --git a/third_party/document_image_extractor/dom_controller_files.gypi b/third_party/document_image_extractor/dom_controller_files.gypi index 42b788b..b13caf1 100644 --- a/third_party/document_image_extractor/dom_controller_files.gypi +++ b/third_party/document_image_extractor/dom_controller_files.gypi @@ -6,83 +6,12 @@ 'variables': { # List of dependencies for dom_controller.js generated by closurebuilder.py 'dom_controller_js_files': [ - 'src/constants.js', - 'src/controller.js', 'src/document_feature.js', 'src/document_image.js', 'src/document_video.js', 'src/dom_controller.js', - 'src/dom_event.js', - 'third_party/closure-library/closure/goog/array/array.js', - 'third_party/closure-library/closure/goog/asserts/asserts.js', - 'third_party/closure-library/closure/goog/async/freelist.js', - 'third_party/closure-library/closure/goog/async/nexttick.js', - 'third_party/closure-library/closure/goog/async/run.js', - 'third_party/closure-library/closure/goog/async/workqueue.js', - 'third_party/closure-library/closure/goog/base.js', - 'third_party/closure-library/closure/goog/debug/debug.js', - 'third_party/closure-library/closure/goog/debug/entrypointregistry.js', - 'third_party/closure-library/closure/goog/debug/error.js', - 'third_party/closure-library/closure/goog/debug/errorhandler.js', - 'third_party/closure-library/closure/goog/debug/logbuffer.js', - 'third_party/closure-library/closure/goog/debug/logger.js', - 'third_party/closure-library/closure/goog/debug/logrecord.js', - 'third_party/closure-library/closure/goog/debug/tracer.js', - 'third_party/closure-library/closure/goog/disposable/disposable.js', - 'third_party/closure-library/closure/goog/disposable/idisposable.js', - 'third_party/closure-library/closure/goog/dom/browserfeature.js', - 'third_party/closure-library/closure/goog/dom/dom.js', - 'third_party/closure-library/closure/goog/dom/nodetype.js', - 'third_party/closure-library/closure/goog/dom/safe.js', - 'third_party/closure-library/closure/goog/dom/tagname.js', - 'third_party/closure-library/closure/goog/dom/tags.js', - 'third_party/closure-library/closure/goog/events/browserevent.js', - 'third_party/closure-library/closure/goog/events/browserfeature.js', - 'third_party/closure-library/closure/goog/events/event.js', - 'third_party/closure-library/closure/goog/events/eventhandler.js', - 'third_party/closure-library/closure/goog/events/eventid.js', - 'third_party/closure-library/closure/goog/events/events.js', - 'third_party/closure-library/closure/goog/events/eventtarget.js', - 'third_party/closure-library/closure/goog/events/eventtype.js', - 'third_party/closure-library/closure/goog/events/eventwrapper.js', - 'third_party/closure-library/closure/goog/events/listenable.js', - 'third_party/closure-library/closure/goog/events/listener.js', - 'third_party/closure-library/closure/goog/events/listenermap.js', - 'third_party/closure-library/closure/goog/fs/url.js', - 'third_party/closure-library/closure/goog/functions/functions.js', - 'third_party/closure-library/closure/goog/html/safehtml.js', - 'third_party/closure-library/closure/goog/html/safescript.js', - 'third_party/closure-library/closure/goog/html/safestyle.js', - 'third_party/closure-library/closure/goog/html/safestylesheet.js', - 'third_party/closure-library/closure/goog/html/safeurl.js', - 'third_party/closure-library/closure/goog/html/trustedresourceurl.js', - 'third_party/closure-library/closure/goog/html/uncheckedconversions.js', - 'third_party/closure-library/closure/goog/i18n/bidi.js', - 'third_party/closure-library/closure/goog/iter/iter.js', - 'third_party/closure-library/closure/goog/labs/useragent/browser.js', - 'third_party/closure-library/closure/goog/labs/useragent/engine.js', - 'third_party/closure-library/closure/goog/labs/useragent/platform.js', - 'third_party/closure-library/closure/goog/labs/useragent/util.js', - 'third_party/closure-library/closure/goog/log/log.js', - 'third_party/closure-library/closure/goog/math/coordinate.js', - 'third_party/closure-library/closure/goog/math/math.js', - 'third_party/closure-library/closure/goog/math/size.js', - 'third_party/closure-library/closure/goog/object/object.js', - 'third_party/closure-library/closure/goog/promise/promise.js', - 'third_party/closure-library/closure/goog/promise/resolver.js', - 'third_party/closure-library/closure/goog/promise/thenable.js', - 'third_party/closure-library/closure/goog/reflect/reflect.js', - 'third_party/closure-library/closure/goog/string/const.js', - 'third_party/closure-library/closure/goog/string/string.js', - 'third_party/closure-library/closure/goog/string/typedstring.js', - 'third_party/closure-library/closure/goog/structs/collection.js', - 'third_party/closure-library/closure/goog/structs/map.js', - 'third_party/closure-library/closure/goog/structs/set.js', - 'third_party/closure-library/closure/goog/structs/simplepool.js', - 'third_party/closure-library/closure/goog/structs/structs.js', - 'third_party/closure-library/closure/goog/testing/watchers.js', - 'third_party/closure-library/closure/goog/timer/timer.js', - 'third_party/closure-library/closure/goog/useragent/useragent.js', + 'src/dom_utils.js', + 'src/size.js', ], }, } diff --git a/third_party/document_image_extractor/src/ad_element_filter.js b/third_party/document_image_extractor/src/ad_element_filter.js index 8ef06a0..b302ed4 100644 --- a/third_party/document_image_extractor/src/ad_element_filter.js +++ b/third_party/document_image_extractor/src/ad_element_filter.js @@ -2,44 +2,42 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.AdElementFilter'); +goog.provide('image.collections.extension.domextractor.AdElementFilter'); -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.dom.classlist'); -goog.require('image.collections.extension.ElementFilter'); +goog.require('image.collections.extension.domextractor.DomUtils'); +goog.require('image.collections.extension.domextractor.ElementFilter'); goog.scope(function() { -var ElementFilter = image.collections.extension.ElementFilter; +var DomUtils = image.collections.extension.domextractor.DomUtils; /** * Filters out potential ad elements. * @constructor - * @implements {ElementFilter} + * @implements {image.collections.extension.domextractor.ElementFilter} */ -image.collections.extension.AdElementFilter = function() { +image.collections.extension.domextractor.AdElementFilter = function() { /** @private {!Array.<string>} */ this.adWords_ = ['ad', 'advertisement', 'ads', 'sponsor', 'sponsored']; }; -var AdElementFilter = image.collections.extension.AdElementFilter; +var AdElementFilter = image.collections.extension.domextractor.AdElementFilter; /** @override */ AdElementFilter.prototype.filter = function(element) { var ancestorElement = element; while (ancestorElement) { - var classNames = goog.dom.classlist.get(ancestorElement); + var classNames = ancestorElement.classList; for (var i = 0; i < classNames.length; ++i) { var tokens = classNames[i].split(/\W+/); for (var j = 0; j < tokens.length; ++j) { - if (goog.array.contains(this.adWords_, tokens[j].toLowerCase())) { + if (this.adWords_.indexOf(tokens[j].toLowerCase()) >= 0) { return false; } } } - ancestorElement = goog.dom.getParentElement(ancestorElement); + ancestorElement = DomUtils.getParentElement(ancestorElement); } return true; }; diff --git a/third_party/document_image_extractor/src/constants.js b/third_party/document_image_extractor/src/constants.js deleted file mode 100644 index 77a856a..0000000 --- a/third_party/document_image_extractor/src/constants.js +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Collections constants. - * @author busaryev@google.com (Oleksiy Busaryev) - */ -goog.provide('gws.collections.common.Constants'); - -goog.scope(function() { - -var Constants = gws.collections.common.Constants; - -/** @type {number} The minimum width of extracted images. */ -Constants.EXTRACT_MIN_WIDTH = 100; - - -/** @type {number} The minimum height of extracted images. */ -Constants.EXTRACT_MIN_HEIGHT = 100; - -}); // goog.scope diff --git a/third_party/document_image_extractor/src/controller.js b/third_party/document_image_extractor/src/controller.js deleted file mode 100644 index e8acb95..0000000 --- a/third_party/document_image_extractor/src/controller.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -goog.provide('image.collections.extension.Controller'); - -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventTarget'); - -goog.scope(function() { - - - -/** - * A base class for all controller classes. Controllers connect UI of the - * 'Google Stars' Chrome extension (see go/stars for details) to backends - * (such as GWS, Chrome Sync etc.) Should not be instantiated by itself. - * Each derived controller should handle certain types of UI events - * (e.g. search requests, clustering requests etc.) - * - * @extends {goog.events.EventTarget} - * @constructor - */ -image.collections.extension.Controller = function() { - Controller.base(this, 'constructor'); - - /** @protected {!goog.events.EventHandler} */ - this.eventHandler = new goog.events.EventHandler(this); - this.registerDisposable(this.eventHandler); -}; -goog.inherits(image.collections.extension.Controller, goog.events.EventTarget); -var Controller = image.collections.extension.Controller; - - -/** - * Initializes the controller. By default, sets the parent event target - * (controllers communicate with UI by handling and dispatching events - * on this event target). - * @param {!goog.events.EventTarget} parentEventTarget - */ -Controller.prototype.initialize = function(parentEventTarget) { - this.setParentEventTarget(parentEventTarget); -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/src/document_feature.js b/third_party/document_image_extractor/src/document_feature.js index 31e4e49..7c0b6fb 100644 --- a/third_party/document_image_extractor/src/document_feature.js +++ b/third_party/document_image_extractor/src/document_feature.js @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.DocumentFeature'); +goog.provide('image.collections.extension.domextractor.DocumentFeature'); goog.scope(function() { @@ -13,11 +13,11 @@ goog.scope(function() { * @param {number} relevance Relevance of this feature to the document. * @constructor */ -image.collections.extension.DocumentFeature = function(relevance) { +image.collections.extension.domextractor.DocumentFeature = function(relevance) { /** @private {number} */ this.relevance_ = relevance; }; -var DocumentFeature = image.collections.extension.DocumentFeature; +var DocumentFeature = image.collections.extension.domextractor.DocumentFeature; /** diff --git a/third_party/document_image_extractor/src/document_feature_extractor.js b/third_party/document_image_extractor/src/document_feature_extractor.js index 515727d..f9c6ba6 100644 --- a/third_party/document_image_extractor/src/document_feature_extractor.js +++ b/third_party/document_image_extractor/src/document_feature_extractor.js @@ -2,15 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.DocumentFeatureExtractor'); +goog.provide('image.collections.extension.domextractor.DocumentFeatureExtractor'); -goog.require('goog.asserts'); -goog.require('image.collections.extension.DocumentFeature'); -goog.require('image.collections.extension.ElementFilter'); +goog.require('image.collections.extension.domextractor.DocumentFeature'); +goog.require('image.collections.extension.domextractor.ElementFilter'); goog.scope(function() { -var DocumentFeature = image.collections.extension.DocumentFeature; -var ElementFilter = image.collections.extension.ElementFilter; +var DocumentFeature = image.collections.extension.domextractor.DocumentFeature; +var ElementFilter = image.collections.extension.domextractor.ElementFilter; @@ -18,12 +17,12 @@ var ElementFilter = image.collections.extension.ElementFilter; * A base class for document feature (title, snippet, image) extractors. * @constructor */ -image.collections.extension.DocumentFeatureExtractor = function() { - /** @protected {!Array.<!ElementFilter>} */ +image.collections.extension.domextractor.DocumentFeatureExtractor = function() { + /** @private {!Array.<!ElementFilter>} */ this.filters_ = []; }; var DocumentFeatureExtractor = - image.collections.extension.DocumentFeatureExtractor; + image.collections.extension.domextractor.DocumentFeatureExtractor; /** @@ -93,7 +92,6 @@ DocumentFeatureExtractor.prototype.extractAllFromDocument = function(doc) { */ DocumentFeatureExtractor.prototype.extractFromNodeList = function( nodeList, opt_context) { - goog.asserts.assert(goog.isArrayLike(nodeList)); var result = []; var nodeListLength = nodeList.length; for (var j = 0; j < nodeListLength; ++j) { diff --git a/third_party/document_image_extractor/src/document_image.js b/third_party/document_image_extractor/src/document_image.js index fe1dea8..147d37f 100644 --- a/third_party/document_image_extractor/src/document_image.js +++ b/third_party/document_image_extractor/src/document_image.js @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.DocumentImage'); +goog.provide('image.collections.extension.domextractor.DocumentImage'); -goog.require('goog.asserts'); -goog.require('image.collections.extension.DocumentFeature'); +goog.require('image.collections.extension.domextractor.DocumentFeature'); +goog.require('image.collections.extension.domextractor.DomUtils'); goog.scope(function() { -var DocumentFeature = image.collections.extension.DocumentFeature; +var DocumentFeature = image.collections.extension.domextractor.DocumentFeature; @@ -16,32 +16,38 @@ var DocumentFeature = image.collections.extension.DocumentFeature; * A class representing a salient image in an HTML document. * @param {number} relevance * @param {string} url - * @param {!goog.math.Size=} opt_size Natural size of image or null if image - * size is not available in the DOM tree. - * @param {!goog.math.Size=} opt_displaySize Size at which the image is being - * shown. One of opt_size or opt_displaySize MUST be specified. + * @param {!image.collections.extension.domextractor.Size=} opt_size Natural + * size of image or undefined if image size is not available in the DOM + * tree. + * @param {!image.collections.extension.domextractor.Size=} opt_displaySize Size + * at which the image is being shown. One of opt_size or opt_displaySize + * MUST be specified. * @extends {DocumentFeature} * @constructor + * @suppress {undefinedNames} */ -image.collections.extension.DocumentImage = function( +image.collections.extension.domextractor.DocumentImage = function( relevance, url, opt_size, opt_displaySize) { DocumentImage.base(this, 'constructor', relevance); /** @private {string} Absolute image url. */ this.url_ = url; - /** @private {!goog.math.Size|undefined} Image resolution in pixels. */ + /** + * @private {!image.collections.extension.domextractor.Size|undefined} Image + * resolution in pixels. + */ this.size_ = opt_size; - /** @private {!goog.math.Size|undefined} Displayed image resolution - * in pixels. + /** + * @private {!image.collections.extension.domextractor.Size|undefined} + * Displayed image resolution in pixels. */ this.displaySize_ = opt_displaySize; - - goog.asserts.assert(goog.isDef(opt_size) || goog.isDef(opt_displaySize)); }; -goog.inherits(image.collections.extension.DocumentImage, DocumentFeature); -var DocumentImage = image.collections.extension.DocumentImage; +image.collections.extension.domextractor.DomUtils.inherits( + image.collections.extension.domextractor.DocumentImage, DocumentFeature); +var DocumentImage = image.collections.extension.domextractor.DocumentImage; /** @@ -67,7 +73,7 @@ DocumentImage.prototype.getUrl = function() { /** * Returns the image resolution in pixels. - * @return {!goog.math.Size|undefined} + * @return {!image.collections.extension.domextractor.Size|undefined} */ DocumentImage.prototype.getSize = function() { return this.size_; @@ -76,7 +82,7 @@ DocumentImage.prototype.getSize = function() { /** * Returns the shown image resolution in pixels. - * @return {!goog.math.Size|undefined} + * @return {!image.collections.extension.domextractor.Size|undefined} */ DocumentImage.prototype.getDisplaySize = function() { return this.displaySize_; diff --git a/third_party/document_image_extractor/src/document_image_extractor.js b/third_party/document_image_extractor/src/document_image_extractor.js index 38c59bb..a9ee672 100644 --- a/third_party/document_image_extractor/src/document_image_extractor.js +++ b/third_party/document_image_extractor/src/document_image_extractor.js @@ -2,56 +2,58 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.DocumentImageExtractor'); - -goog.require('goog.Uri'); -goog.require('goog.asserts'); -goog.require('goog.dom'); -goog.require('goog.log'); -goog.require('goog.math.Size'); -goog.require('goog.object'); -goog.require('goog.string'); -goog.require('goog.style'); -goog.require('goog.uri.utils'); -goog.require('gws.collections.common.Constants'); -goog.require('image.collections.extension.AdElementFilter'); -goog.require('image.collections.extension.DocumentFeature'); -goog.require('image.collections.extension.DocumentFeatureExtractor'); -goog.require('image.collections.extension.DocumentImage'); -goog.require('image.collections.extension.VisibleElementFilter'); +goog.provide('image.collections.extension.domextractor.DocumentImageExtractor'); + +goog.require('image.collections.extension.domextractor.AdElementFilter'); +goog.require('image.collections.extension.domextractor.DocumentFeature'); +goog.require('image.collections.extension.domextractor.DocumentFeatureExtractor'); +goog.require('image.collections.extension.domextractor.DocumentImage'); +goog.require('image.collections.extension.domextractor.DomUtils'); +goog.require('image.collections.extension.domextractor.Size'); +goog.require('image.collections.extension.domextractor.VisibleElementFilter'); goog.scope(function() { -var AdElementFilter = image.collections.extension.AdElementFilter; -var Constants = gws.collections.common.Constants; -var DocumentFeature = image.collections.extension.DocumentFeature; +var AdElementFilter = image.collections.extension.domextractor.AdElementFilter; +var DocumentFeature = image.collections.extension.domextractor.DocumentFeature; var DocumentFeatureExtractor = - image.collections.extension.DocumentFeatureExtractor; -var DocumentImage = image.collections.extension.DocumentImage; + image.collections.extension.domextractor.DocumentFeatureExtractor; +var DocumentImage = image.collections.extension.domextractor.DocumentImage; var CustomAttribute = DocumentImage.CustomAttribute; -var VisibleElementFilter = image.collections.extension.VisibleElementFilter; +var DomUtils = image.collections.extension.domextractor.DomUtils; +var Size = image.collections.extension.domextractor.Size; +var VisibleElementFilter = + image.collections.extension.domextractor.VisibleElementFilter; + + +/** @const {number} The minimum width of extracted images. */ +var EXTRACT_MIN_WIDTH = 100; + + +/** @const {number} The minimum height of extracted images. */ +var EXTRACT_MIN_HEIGHT = 100; /** * This class is used for extracting a salient image from an HTML document. * @extends {DocumentFeatureExtractor} * @constructor + * @suppress {undefinedNames} */ -image.collections.extension.DocumentImageExtractor = function() { +image.collections.extension.domextractor.DocumentImageExtractor = function() { DocumentImageExtractor.base(this, 'constructor'); this.addFilter(new AdElementFilter()); this.addFilter(new VisibleElementFilter()); + + /** @private {!Element} Helper element for resolving URLs. */ + this.helperAnchor_ = document.createElement('a'); }; -goog.inherits(image.collections.extension.DocumentImageExtractor, +DomUtils.inherits( + image.collections.extension.domextractor.DocumentImageExtractor, DocumentFeatureExtractor); -var DocumentImageExtractor = image.collections.extension.DocumentImageExtractor; -goog.addSingletonGetter(DocumentImageExtractor); - - -/** @private {goog.log.Logger} Extractor logger. */ -DocumentImageExtractor.logger_ = goog.log.getLogger( - 'image.collections.extension.DocumentImageExtractor'); +var DocumentImageExtractor = + image.collections.extension.domextractor.DocumentImageExtractor; /** @enum {number} */ @@ -77,8 +79,7 @@ var Parameters = DocumentImageExtractor.Parameters; * Map of image type to relevance multiplier. * @private {!Object.<string, number>} */ -DocumentImageExtractor.IMAGE_TYPE_RELEVANCE_MULTIPLIER_ = - goog.object.create('.gif', 0.5); +DocumentImageExtractor.IMAGE_TYPE_RELEVANCE_MULTIPLIER_ = {'.gif': 0.5}; @@ -147,11 +148,10 @@ DocumentImageExtractor.prototype.extractFromElement = function( } var size = image.getDisplaySize() || image.getSize(); - goog.asserts.assert(!goog.isNull(size)); if (image.getUrl() != document.location.href) { // Ignore images that are too small. - if (size.width < Constants.EXTRACT_MIN_WIDTH || - size.height < Constants.EXTRACT_MIN_HEIGHT) { + if (size.width < EXTRACT_MIN_WIDTH || + size.height < EXTRACT_MIN_HEIGHT) { return null; } } @@ -159,7 +159,7 @@ DocumentImageExtractor.prototype.extractFromElement = function( var relevance = image.getRelevance(); relevance /= (1 + Math.exp(Parameters.AREA_MULTIPLIER * size.area())); // Demote images with bad aspect ratio. - var aspectRatio = size.aspectRatio(); + var aspectRatio = size.width / size.height; if (aspectRatio < 1) { aspectRatio = 1 / aspectRatio; } @@ -173,17 +173,11 @@ DocumentImageExtractor.prototype.extractFromElement = function( // - position (demote images on the border of the page). var url = image.getUrl(); - try { - // Make sure that image url is absolute. - var documentUrl = goog.dom.getOwnerDocument(element).documentURI; - url = goog.Uri.resolve(documentUrl, url).toString(); - } catch (e) { - goog.log.info(DocumentImageExtractor.logger_, - 'Cannot resolve url: ' + url); - return null; - } + // Make sure that image url is absolute. + this.helperAnchor_.href = url; + url = this.helperAnchor_.href; - var imagePath = goog.string.makeSafe(goog.uri.utils.getPath(url)); + var imagePath = decodeURIComponent(this.helperAnchor_.pathname || ''); var lastDot = imagePath.lastIndexOf('.'); if (lastDot > 0) { var imageType = imagePath.slice(lastDot); @@ -267,31 +261,28 @@ DocumentImageExtractor.prototype.extractImageSrcImage_ = function(element) { * @param {string} urlAttributeName * @return {DocumentImage} * @private + * @suppress {missingProperties} */ DocumentImageExtractor.prototype.extractCanonicalImage_ = function( element, relevance, attributeName, attribute, urlAttributeName) { - goog.asserts.assert(goog.isNumber(relevance)); - goog.asserts.assert(goog.isString(attributeName)); - goog.asserts.assert(goog.isString(attribute)); - - if (goog.string.caseInsensitiveEquals( - goog.string.makeSafe(element.getAttribute(attributeName)), attribute)) { + if (element.hasAttribute(attributeName) && + element.getAttribute(attributeName).toLowerCase() == + attribute.toLowerCase()) { var url = element.getAttribute(urlAttributeName); - if (!url || goog.string.startsWith(url, 'data:')) { + if (!url || url.startsWith('data:')) { return null; } - var width = goog.string.parseInt( - element.getAttribute(CustomAttribute.WIDTH)); - var height = goog.string.parseInt( - element.getAttribute(CustomAttribute.HEIGHT)); + var width = parseInt(element.getAttribute(CustomAttribute.WIDTH), 10); + var height = parseInt(element.getAttribute(CustomAttribute.HEIGHT), 10); if (width && height) { // For non-toplevel urls, demote the image if it is not in the document. - var ownerDocument = goog.dom.getOwnerDocument(element); - if (goog.uri.utils.getPath(ownerDocument.documentURI) != '/' && - ownerDocument.body.innerHTML.indexOf(url) == -1) { + var ownerDocument = DomUtils.getOwnerDocument(element); + this.helperAnchor_.href = ownerDocument.documentURI; + var path = this.helperAnchor_.pathname; + if (path != '/' && ownerDocument.body.innerHTML.indexOf(url) == -1) { relevance *= Parameters.NON_TOPLEVEL_DEMOTION_FACTOR; } - var size = new goog.math.Size(width, height); + var size = new Size(width, height); return new DocumentImage(relevance, url, size); } } @@ -303,20 +294,19 @@ DocumentImageExtractor.prototype.extractCanonicalImage_ = function( * @param {!Element} element * @return {DocumentImage} * @private + * @suppress {missingProperties} */ DocumentImageExtractor.prototype.extractMicrodataImage_ = function(element) { var itemProp = element.getAttribute('itemprop'); if (itemProp && itemProp.toLowerCase() == 'thumbnailurl') { var url = element.getAttribute('href') || element.getAttribute('content'); - if (!url || goog.string.startsWith(url, 'data:')) { + if (!url || url.startsWith('data:')) { return null; } - var width = goog.string.parseInt( - element.getAttribute(CustomAttribute.WIDTH)); - var height = goog.string.parseInt( - element.getAttribute(CustomAttribute.HEIGHT)); + var width = parseInt(element.getAttribute(CustomAttribute.WIDTH), 10); + var height = parseInt(element.getAttribute(CustomAttribute.HEIGHT), 10); if (width && height) { - var size = new goog.math.Size(width, height); + var size = new Size(width, height); return new DocumentImage(Parameters.WEIGHT_MICRODATA, url, size); } } @@ -330,7 +320,7 @@ DocumentImageExtractor.prototype.extractMicrodataImage_ = function(element) { * @private */ DocumentImageExtractor.prototype.getElementRelevance_ = function(element) { - var offset = goog.style.getPageOffsetTop(element); + var offset = DomUtils.getPageOffsetTop(element); if (offset > Parameters.MAX_OFFSET) { return 0; } @@ -345,13 +335,11 @@ DocumentImageExtractor.prototype.getElementRelevance_ = function(element) { * @private */ DocumentImageExtractor.prototype.extractImage_ = function(element) { - goog.asserts.assert(element.tagName.toLowerCase() == 'img'); var url = element.src; // We cannot handle data URIs. - if (url && !goog.string.startsWith(url, 'data:')) { - var naturalSize = new goog.math.Size( - element.naturalWidth, element.naturalHeight); - var displaySize = goog.style.getSize(element); + if (url && !url.startsWith('data:')) { + var naturalSize = new Size(element.naturalWidth, element.naturalHeight); + var displaySize = DomUtils.getSize(element); var size = naturalSize.area() < displaySize.area() ? naturalSize : displaySize; if (size.width && size.height) { @@ -368,28 +356,29 @@ DocumentImageExtractor.prototype.extractImage_ = function(element) { * @param {!Element} element * @return {DocumentImage} * @private + * @suppress {missingProperties} */ DocumentImageExtractor.prototype.extractBackgroundImage_ = function(element) { - var backgroundImage = goog.style.getComputedStyle( + var backgroundImage = DomUtils.getComputedStyle( element, 'background-image'); - var backgroundRepeat = goog.style.getComputedStyle( + var backgroundRepeat = DomUtils.getComputedStyle( element, 'background-repeat'); - var backgroundSize = goog.style.getComputedStyle( + var backgroundSize = DomUtils.getComputedStyle( element, 'background-size'); if (backgroundImage && (backgroundRepeat == 'no-repeat' || backgroundSize == 'cover') && - goog.string.startsWith(backgroundImage, 'url(') && - goog.string.endsWith(backgroundImage, ')')) { + backgroundImage.startsWith('url(') && + backgroundImage.endsWith(')')) { var url = backgroundImage.substr(4, backgroundImage.length - 5); - if (url && !goog.string.startsWith(url, 'data:')) { - var size = goog.style.getSize(element); + if (url && !url.startsWith('data:')) { + var size = DomUtils.getSize(element); if (size.width && size.height) { var relevance = this.getElementRelevance_(element); - var children = goog.dom.getChildren(element); + var children = element.children; for (var i = 0; i < children.length; ++i) { var child = children[i]; - if (goog.style.getComputedStyle(child, 'display') != 'none' && - goog.style.getSize(child).area() > 0.1 * size.area()) { + if (DomUtils.getComputedStyle(child, 'display') != 'none' && + DomUtils.getSize(child).area() > 0.1 * size.area()) { relevance *= 0.1; break; } diff --git a/third_party/document_image_extractor/src/document_video.js b/third_party/document_image_extractor/src/document_video.js index 747f4dc..ded38c8 100644 --- a/third_party/document_image_extractor/src/document_video.js +++ b/third_party/document_image_extractor/src/document_video.js @@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.DocumentVideo'); +goog.provide('image.collections.extension.domextractor.DocumentVideo'); -goog.require('image.collections.extension.DocumentFeature'); +goog.require('image.collections.extension.domextractor.DocumentFeature'); +goog.require('image.collections.extension.domextractor.DomUtils'); goog.scope(function() { -var DocumentFeature = image.collections.extension.DocumentFeature; +var DocumentFeature = image.collections.extension.domextractor.DocumentFeature; @@ -15,21 +16,27 @@ var DocumentFeature = image.collections.extension.DocumentFeature; * A class representing a salient video in an HTML document. * @param {number} relevance * @param {string} url - * @param {!goog.math.Size} size + * @param {!image.collections.extension.domextractor.Size} size * @extends {DocumentFeature} * @constructor + * @suppress {undefinedNames} */ -image.collections.extension.DocumentVideo = function(relevance, url, size) { +image.collections.extension.domextractor.DocumentVideo = + function(relevance, url, size) { DocumentVideo.base(this, 'constructor', relevance); /** @private {string} Absolute video url. */ this.url_ = url; - /** @private {!goog.math.Size} Video resolution in pixels */ + /** + * @private {!image.collections.extension.domextractor.Size} Video resolution + * in pixels + */ this.size_ = size; }; -goog.inherits(image.collections.extension.DocumentVideo, DocumentFeature); -var DocumentVideo = image.collections.extension.DocumentVideo; +image.collections.extension.domextractor.DomUtils.inherits( + image.collections.extension.domextractor.DocumentVideo, DocumentFeature); +var DocumentVideo = image.collections.extension.domextractor.DocumentVideo; /** @enum {string} */ @@ -50,7 +57,7 @@ DocumentVideo.prototype.getUrl = function() { /** * Returns the video resolution in pixels. - * @return {!goog.math.Size} + * @return {!image.collections.extension.domextractor.Size} */ DocumentVideo.prototype.getSize = function() { return this.size_; diff --git a/third_party/document_image_extractor/src/dom_controller.js b/third_party/document_image_extractor/src/dom_controller.js index 962c4fd..eeb3e66 100644 --- a/third_party/document_image_extractor/src/dom_controller.js +++ b/third_party/document_image_extractor/src/dom_controller.js @@ -2,50 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.DomController'); +goog.provide('image.collections.extension.domextractor.DomController'); -goog.require('goog.Timer'); -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.events.EventType'); -goog.require('goog.log'); -goog.require('gws.collections.common.Constants'); -goog.require('image.collections.extension.Controller'); -goog.require('image.collections.extension.DocumentImage'); -goog.require('image.collections.extension.DocumentVideo'); -goog.require('image.collections.extension.DomEvent'); +goog.require('image.collections.extension.domextractor.DocumentImage'); +goog.require('image.collections.extension.domextractor.DocumentVideo'); +goog.require('image.collections.extension.domextractor.DomUtils'); goog.scope(function() { -var Constants = gws.collections.common.Constants; -var DocumentImage = image.collections.extension.DocumentImage; -var DocumentVideo = image.collections.extension.DocumentVideo; -var DomEvent = image.collections.extension.DomEvent; +var DocumentImage = image.collections.extension.domextractor.DocumentImage; +var DocumentVideo = image.collections.extension.domextractor.DocumentVideo; +var DomUtils = image.collections.extension.domextractor.DomUtils; + /** * This class handles page DOM events and implements DOM manipulation. * It should be instantiated by a content script. * TODO(busaryev): preloading may not be the best choice for mobile clients. - * @extends {image.collections.extension.Controller} * @constructor */ -image.collections.extension.DomController = function() { - DomController.base(this, 'constructor'); - +image.collections.extension.domextractor.DomController = function() { /** @private {number} Number of DOM elements left. */ this.numElementsToProcess_ = 0; - /** @private {number} The timeout id for goog.Timer.callOnce. */ - this.timeoutId_ = -1; -}; -goog.inherits(image.collections.extension.DomController, - image.collections.extension.Controller); -var DomController = image.collections.extension.DomController; - + /** + * Promise returned by initialize() call. Resolves when all elements have been + * processed, or alternatively when a timeout has been reached. + * @private {!Promise} + */ + this.initializedPromise_ = Promise.resolve(); -/** @private {goog.log.Logger} */ -DomController.logger_ = goog.log.getLogger( - 'image.collections.extension.DomController'); + /** @private {?function()} Resolve function for the initialized promise. */ + this.initializedPromiseResolve_ = null; +}; +var DomController = image.collections.extension.domextractor.DomController; /** @@ -56,37 +46,38 @@ DomController.logger_ = goog.log.getLogger( DomController.LOAD_TIMEOUT_MS_ = 5000; -/** @override */ -DomController.prototype.initialize = function(parentEventTarget) { - DomController.base(this, 'initialize', parentEventTarget); - - this.eventHandler. - listen(parentEventTarget, DomEvent.Type.INITIALIZE_DOM, - this.handleInitializeDom_); -}; - - /** - * @param {DomEvent} e - * @private + * Initializes the DomController. + * @return {!Promise} A promise that resolves when all elements have been + * processed, or alternatively after a timeout has expired. */ -DomController.prototype.handleInitializeDom_ = function(e) { +DomController.prototype.initialize = function() { if (this.numElementsToProcess_ == 0) { // Find <meta> and <link> tags that specify canonical page images, compute // image sizes with preloading and store them in element attributes. - var doc = goog.dom.getDocument(); - var metaElements = doc.getElementsByTagName('meta'); - var linkElements = doc.getElementsByTagName('link'); + var metaElements = document.getElementsByTagName('meta'); + var linkElements = document.getElementsByTagName('link'); this.numElementsToProcess_ = metaElements.length + linkElements.length; if (this.numElementsToProcess_ > 0) { - goog.array.forEach(metaElements, this.processMetaElement_, this); - goog.array.forEach(linkElements, this.processLinkElement_, this); - this.timeoutId_ = goog.Timer.callOnce( - goog.bind(this.dispatchEvent, this, DomEvent.Type.DOM_INITIALIZED), + this.initializedPromise_ = + new Promise(function(resolve, reject) { + this.initializedPromiseResolve_ = resolve; + }.bind(this)); + for (var i = 0; i < metaElements.length; i++) { + this.processMetaElement_(metaElements[i]); + } + for (var i = 0; i < linkElements.length; i++) { + this.processLinkElement_(linkElements[i]); + } + setTimeout(this.initializedPromiseResolve_, DomController.LOAD_TIMEOUT_MS_); + return this.initializedPromise_; } else { - this.dispatchEvent(DomEvent.Type.DOM_INITIALIZED); + this.initializedPromise_ = Promise.resolve(); + return this.initializedPromise_; } + } else { + return this.initializedPromise_; } }; @@ -94,17 +85,15 @@ DomController.prototype.handleInitializeDom_ = function(e) { /** * Tries to compute the size of the image specified in a <meta> element. * @param {Element} element The element to process. - * @param {number} index Index of the element in the array. - * @param {goog.array.ArrayLike} array The array. * @private */ -DomController.prototype.processMetaElement_ = function(element, index, array) { +DomController.prototype.processMetaElement_ = function(element) { var url = ''; if (element.hasAttribute('property')) { switch (element.getAttribute('property').toLowerCase()) { case 'og:image': url = element.getAttribute('content'); - var siblings = goog.dom.getChildren(goog.dom.getParentElement(element)); + var siblings = DomUtils.getParentElement(element).children; var width = this.getPropertyContent_(siblings, 'og:image:width'); var height = this.getPropertyContent_(siblings, 'og:image:height'); if (width > 0 && height > 0) { @@ -113,7 +102,7 @@ DomController.prototype.processMetaElement_ = function(element, index, array) { } break; case 'og:video': - var children = goog.dom.getChildren(goog.dom.getParentElement(element)); + var children = DomUtils.getParentElement(element).children; var width = this.getPropertyContent_(children, 'og:video:width'); var height = this.getPropertyContent_(children, 'og:video:height'); if (width > 0 && height > 0) { @@ -141,11 +130,9 @@ DomController.prototype.processMetaElement_ = function(element, index, array) { /** * Tries to compute the size of the image specified in a <link> element. * @param {Element} element The element to process. - * @param {number} index Index of the element in the array. - * @param {goog.array.ArrayLike} array The array. * @private */ -DomController.prototype.processLinkElement_ = function(element, index, array) { +DomController.prototype.processLinkElement_ = function(element) { var url = ''; if (element.hasAttribute('rel')) { switch (element.getAttribute('rel').toLowerCase()) { @@ -197,9 +184,9 @@ DomController.prototype.maybeComputeAndStoreImageSize_ = function( var CustomAttribute = DocumentImage.CustomAttribute; if (url && (!element.hasAttribute(CustomAttribute.WIDTH) || !element.hasAttribute(CustomAttribute.HEIGHT))) { - this.computeImageSize_(url, goog.bind(this.storeImageSize_, this, element)); + this.computeImageSize_(url, this.storeImageSize_.bind(this, element)); } else { - this.maybeDispatchDomInitialized_(); + this.maybeResolveInitializedPromise_(); } }; @@ -212,42 +199,30 @@ DomController.prototype.maybeComputeAndStoreImageSize_ = function( */ DomController.prototype.computeImageSize_ = function(url, callback) { var image = new Image(); - this.eventHandler.listenOnce(image, - [goog.events.EventType.LOAD, goog.events.EventType.ERROR], - goog.bind(this.handleImageLoadOrError_, this, callback)); - image.src = url; -}; + var that = this; + var handleImageLoadOrError = function(e) { + if (e.type == 'load') { + callback(image.naturalWidth, image.naturalHeight); + } + that.maybeResolveInitializedPromise_(); + image.removeEventListener('load', handleImageLoadOrError); + image.removeEventListener('error', handleImageLoadOrError); + }; -/** - * Handles image LOAD and ERROR events. - * @param {!function(number, number)} callback A callback. - * @param {goog.events.Event} e Image event. - * @private - */ -DomController.prototype.handleImageLoadOrError_ = function(callback, e) { - var image = /** @type {!Image} */ (e.target); - if (e.type == goog.events.EventType.LOAD) { - callback(image.naturalWidth, image.naturalHeight); - } else { - goog.log.warning(DomController.logger_, - 'Failed to load image ' + image.src); - } - this.maybeDispatchDomInitialized_(); + image.addEventListener('load', handleImageLoadOrError); + image.addEventListener('error', handleImageLoadOrError); + image.src = url; }; /** - * Dispatches the DOM_INITIALIZED event if all elements have been processed. + * Resolves the initialized promise if all elements have been processed. * @private */ -DomController.prototype.maybeDispatchDomInitialized_ = function() { +DomController.prototype.maybeResolveInitializedPromise_ = function() { if (--this.numElementsToProcess_ == 0) { - if (this.timeoutId_ != -1) { - goog.Timer.clear(this.timeoutId_); - this.timeoutId_ = -1; - } - this.dispatchEvent(DomEvent.Type.DOM_INITIALIZED); + this.initializedPromiseResolve_(); } }; diff --git a/third_party/document_image_extractor/src/dom_event.js b/third_party/document_image_extractor/src/dom_event.js deleted file mode 100644 index 3880d56..0000000 --- a/third_party/document_image_extractor/src/dom_event.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview This file provides the DomEvent class. - */ - -goog.provide('image.collections.extension.DomEvent'); - -goog.require('goog.events.Event'); - -goog.scope(function() { - - - -/** - * Represents the content script DOM event. - * @param {!DomEvent.Type} type The type of this event. - * @extends {goog.events.Event} - * @constructor - */ -image.collections.extension.DomEvent = function(type) { - DomEvent.base(this, 'constructor', type); -}; -goog.inherits(image.collections.extension.DomEvent, goog.events.Event); -var DomEvent = image.collections.extension.DomEvent; - - -/** @enum {string} */ -DomEvent.Type = { - DOM_INITIALIZED: 'dom_initialized', - INITIALIZE_DOM: 'initialize_dom' -}; - -}); // goog.scope diff --git a/third_party/document_image_extractor/src/dom_utils.js b/third_party/document_image_extractor/src/dom_utils.js new file mode 100644 index 0000000..e8127b4 --- /dev/null +++ b/third_party/document_image_extractor/src/dom_utils.js @@ -0,0 +1,349 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Provides copied versions of Closure library functions. The + * functions in this file are modified to remove non-Chrome compatibility + * code. + */ +goog.provide('image.collections.extension.domextractor.DomUtils'); + +goog.require('image.collections.extension.domextractor.Size'); + + +goog.scope(function() { +var DomUtils = image.collections.extension.domextractor.DomUtils; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * Usage: + * <pre> + * function ParentClass(a, b) { } + * ParentClass.prototype.foo = function(a) { }; + * + * function ChildClass(a, b, c) { + * ChildClass.base(this, 'constructor', a, b); + * } + * DomUtils.inherits(ChildClass, ParentClass); + * + * var child = new ChildClass('a', 'b', 'see'); + * child.foo(); // This works. + * </pre> + * + * @param {Function} childCtor Child class. + * @param {Function} parentCtor Parent class. + */ +image.collections.extension.domextractor.DomUtils.inherits = + function(childCtor, parentCtor) { + /** @constructor */ + function tempCtor() {}; + tempCtor.prototype = parentCtor.prototype; + childCtor.prototype = new tempCtor(); + /** @override */ + childCtor.prototype.constructor = childCtor; + + /** + * Calls superclass constructor/method. + * + * @param {!Object} me Should always be "this". + * @param {string} methodName The method name to call. Calling + * superclass constructor can be done with the special string + * 'constructor'. + * @param {...*} var_args The arguments to pass to superclass + * method/constructor. + * @return {*} The return value of the superclass method/constructor. + */ + childCtor.base = function(me, methodName, var_args) { + // Copying using loop to avoid deop due to passing arguments object to + // function. This is faster in many JS engines as of late 2014. + var args = new Array(arguments.length - 2); + for (var i = 2; i < arguments.length; i++) { + args[i - 2] = arguments[i]; + } + return parentCtor.prototype[methodName].apply(me, args); + }; +}; + + +/** + * Map of tags whose content to ignore when calculating text length. + * @const {!Object<string, number>} + */ +var TAGS_TO_IGNORE = { + 'SCRIPT': 1, + 'STYLE': 1, + 'HEAD': 1, + 'IFRAME': 1, + 'OBJECT': 1 +}; + +/** + * Map of tags which have predefined values with regard to whitespace. + * @const {!Object<string, string>} + */ +var PREDEFINED_TAG_VALUES = {'IMG': ' ', 'BR': '\n'}; + +/** @const {number} */ +var ELEMENT_NODE_TYPE = 1; + +/** @const {number} */ +var TEXT_NODE_TYPE = 3; + +/** @const {number} */ +var DOCUMENT_NODE_TYPE = 9; + +/** + * Regular expression that matches an HTML entity. + * See also HTML5: Tokenization / Tokenizing character references. + * @type {!RegExp} + */ +var HTML_ENTITY_PATTERN = /&([^;\s<&]+);?/g; + + + +/** + * Retrieves a computed style value of a node. It returns empty string if the + * value cannot be computed (which will be the case in Internet Explorer) or + * "none" if the property requested is an SVG one and it has not been + * explicitly set (firefox and webkit). + * + * @param {!Element} element Element to get style of. + * @param {string} property Property to get (camel-case). + * @return {string} Style value. + */ +image.collections.extension.domextractor.DomUtils.getComputedStyle = + function(element, property) { + var doc = DomUtils.getOwnerDocument(element); + if (doc.defaultView && doc.defaultView.getComputedStyle) { + var styles = doc.defaultView.getComputedStyle(element, null); + if (styles) { + // element.style[..] is undefined for browser specific styles + // as 'filter'. + return styles[property] || styles.getPropertyValue(property) || ''; + } + } + + return ''; +}; + + +/** + * Gets the height and width of an element, even if its display is none. + * + * Specifically, this returns the height and width of the border box, + * irrespective of the box model in effect. + * + * Note that this function does not take CSS transforms into account. + * @param {!Element} element Element to get size of. + * @return {!image.collections.extension.domextractor.Size} Object with + * width/height properties. + */ +image.collections.extension.domextractor.DomUtils.getSize = function(element) { + if (DomUtils.getComputedStyle(element, 'display') != 'none') { + return DomUtils.getSizeWithDisplay_(element); + } + + var style = element.style; + var originalDisplay = style.display; + var originalVisibility = style.visibility; + var originalPosition = style.position; + + style.visibility = 'hidden'; + style.position = 'absolute'; + style.display = 'inline'; + + var retVal = DomUtils.getSizeWithDisplay_(element); + + style.display = originalDisplay; + style.position = originalPosition; + style.visibility = originalVisibility; + + return retVal; +}; + + +/** + * Gets the height and width of an element when the display is not none. + * @param {!Element} element Element to get size of. + * @return {!image.collections.extension.domextractor.Size} Object with + * width/height properties. + * @private + */ +image.collections.extension.domextractor.DomUtils.getSizeWithDisplay_ = + function(element) { + var offsetWidth = element.offsetWidth; + var offsetHeight = element.offsetHeight; + var offsetsZero = !offsetWidth && !offsetHeight; + if ((offsetWidth === undefined) || offsetsZero) { + // Fall back to calling getBoundingClientRect when offsetWidth or + // offsetHeight are not defined, or when they are zero. + // This makes sure that we return for the correct size for SVG elements. + var clientRect = element.getBoundingClientRect(); + return new image.collections.extension.domextractor.Size( + clientRect.right - clientRect.left, clientRect.bottom - clientRect.top); + } + return new image.collections.extension.domextractor.Size( + offsetWidth, offsetHeight); +}; + + +/** + * Returns the owner document for a node. + * @param {!Node|!Window} node The node to get the document for. + * @return {!Document} The document owning the node. + */ +image.collections.extension.domextractor.DomUtils.getOwnerDocument = + function(node) { + return /** @type {!Document} */ (node.nodeType == DOCUMENT_NODE_TYPE ? + node : node.ownerDocument || node.document); +}; + + +/** + * Returns an element's parent, if it's an Element. + * @param {Element} element The DOM element. + * @return {Element} The parent, or null if not an Element. + */ +image.collections.extension.domextractor.DomUtils.getParentElement = + function(element) { + if (element.parentElement) { + return element.parentElement; + } + var parent = element.parentNode; + if (typeof parent == 'object' && parent.nodeType == ELEMENT_NODE_TYPE) { + return /** @type {!Element} */ (parent); + } + return null; +}; + + +/** + * Returns the top coordinate of an element relative to the HTML document + * @param {!Element} el Elements. + * @return {number} The top coordinate. + */ +image.collections.extension.domextractor.DomUtils.getPageOffsetTop = + function(el) { + var doc = DomUtils.getOwnerDocument(el); + if (el == doc.documentElement) { + // viewport is always at 0,0 as that defined the coordinate system for this + // function - this avoids special case checks in the code below + return 0; + } + + // Must add the scroll coordinates in to get the absolute page offset + // of element since getBoundingClientRect returns relative coordinates to + // the viewport. + var documentScrollElement = doc.body || doc.documentElement; + var win = doc.defaultView; + var scrollOffset = win.pageYOffset || documentScrollElement.scrollTop; + + return el.getBoundingClientRect().top + scrollOffset; +}; + + +/** + * Returns the text content of the current node, without markup and invisible + * symbols. New lines are stripped and whitespace is collapsed, + * such that each character would be visible. + * + * @param {Node} node The node from which we are getting content. + * @return {string} The text content. + */ +DomUtils.getTextContent = function(node) { + var textContent; + var buf = []; + DomUtils.getTextContent_(node, buf); + textContent = buf.join(''); + + textContent = textContent.replace(/ +/g, ' '); + if (textContent != ' ') { + textContent = textContent.replace(/^\s*/, ''); + } + + return textContent; +}; + +/** + * Recursive support function for text content retrieval. + * + * @param {Node} node The node from which we are getting content. + * @param {Array<string>} buf string buffer. + * @private + */ +image.collections.extension.domextractor.DomUtils.getTextContent_ = + function(node, buf) { + if (node.nodeName in TAGS_TO_IGNORE) { + // ignore certain tags + } else if (node.nodeType == TEXT_NODE_TYPE) { + // Text node + buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, '')); + } else if (node.nodeName in PREDEFINED_TAG_VALUES) { + buf.push(PREDEFINED_TAG_VALUES[node.nodeName]); + } else { + var child = node.firstChild; + while (child) { + DomUtils.getTextContent_(child, buf); + child = child.nextSibling; + } + } +}; + + +/** + * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric + * entities. This function is XSS-safe and whitespace-preserving. + * @param {string} str The string to unescape. + * @param {Document=} opt_document An optional document to use for creating + * elements. If this is not specified then the default window.document + * will be used. + * @return {string} The unescaped {@code str} string. + */ +image.collections.extension.domextractor.DomUtils.unescapeEntitiesUsingDom = + function(str, opt_document) { + if (str.indexOf('&') == -1) { + return str; + } + /** @type {!Object<string, string>} */ + var seen = {'&': '&', '<': '<', '>': '>', '"': '"'}; + var div; + if (opt_document) { + div = opt_document.createElement('div'); + } else { + div = document.createElement('div'); + } + // Match as many valid entity characters as possible. If the actual entity + // happens to be shorter, it will still work as innerHTML will return the + // trailing characters unchanged. Since the entity characters do not include + // open angle bracket, there is no chance of XSS from the innerHTML use. + // Since no whitespace is passed to innerHTML, whitespace is preserved. + return str.replace(HTML_ENTITY_PATTERN, function(s, entity) { + // Check for cached entity. + var value = seen[s]; + if (value) { + return value; + } + // Check for numeric entity. + if (entity.charAt(0) == '#') { + // Prefix with 0 so that hex entities (e.g. ) parse as hex numbers. + var n = Number('0' + entity.substr(1)); + if (!isNaN(n)) { + value = String.fromCharCode(n); + } + } + // Fall back to innerHTML otherwise. + if (!value) { + // Append a non-entity character to avoid a bug in Webkit that parses + // an invalid entity at the end of innerHTML text as the empty string. + div.innerHTML = s + ' '; + // Then remove the trailing character from the result. + value = div.firstChild.nodeValue.slice(0, -1); + } + // Cache and return. + return seen[s] = value; + }); +}; +}); // goog.scope diff --git a/third_party/document_image_extractor/src/element_filter.js b/third_party/document_image_extractor/src/element_filter.js index e1c8125..c5002bb 100644 --- a/third_party/document_image_extractor/src/element_filter.js +++ b/third_party/document_image_extractor/src/element_filter.js @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.ElementFilter'); +goog.provide('image.collections.extension.domextractor.ElementFilter'); goog.scope(function() { @@ -12,8 +12,8 @@ goog.scope(function() { * An element filter interface. * @interface */ -image.collections.extension.ElementFilter = function() {}; -var ElementFilter = image.collections.extension.ElementFilter; +image.collections.extension.domextractor.ElementFilter = function() {}; +var ElementFilter = image.collections.extension.domextractor.ElementFilter; /** diff --git a/third_party/document_image_extractor/src/size.js b/third_party/document_image_extractor/src/size.js new file mode 100644 index 0000000..a773259 --- /dev/null +++ b/third_party/document_image_extractor/src/size.js @@ -0,0 +1,32 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +goog.provide('image.collections.extension.domextractor.Size'); + + +goog.scope(function() { + + + +/** + * @param {number} width + * @param {number} height + * @constructor + */ +image.collections.extension.domextractor.Size = function(width, height) { + /** @type {number} */ + this.width = width; + + /** @type {number} */ + this.height = height; +}; + + +/** + * @return {number} The area of the size (width * height). + */ +image.collections.extension.domextractor.Size.prototype.area = function() { + return this.width * this.height; +}; +}); diff --git a/third_party/document_image_extractor/src/visible_element_filter.js b/third_party/document_image_extractor/src/visible_element_filter.js index e337b1b..3c9aaf7 100644 --- a/third_party/document_image_extractor/src/visible_element_filter.js +++ b/third_party/document_image_extractor/src/visible_element_filter.js @@ -2,45 +2,44 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -goog.provide('image.collections.extension.VisibleElementFilter'); +goog.provide('image.collections.extension.domextractor.VisibleElementFilter'); -goog.require('goog.dom'); -goog.require('goog.style'); -goog.require('image.collections.extension.ElementFilter'); +goog.require('image.collections.extension.domextractor.DomUtils'); +goog.require('image.collections.extension.domextractor.ElementFilter'); goog.scope(function() { -var ElementFilter = image.collections.extension.ElementFilter; +var DomUtils = image.collections.extension.domextractor.DomUtils; /** * Filters elements by visibility. - * @implements {ElementFilter} + * @implements {image.collections.extension.domextractor.ElementFilter} * @constructor */ -image.collections.extension.VisibleElementFilter = function() {}; -var VisibleElementFilter = image.collections.extension.VisibleElementFilter; +image.collections.extension.domextractor.VisibleElementFilter = function() {}; +var VisibleElementFilter = + image.collections.extension.domextractor.VisibleElementFilter; /** @override */ VisibleElementFilter.prototype.filter = function(element) { - // TODO(busaryev): handle the overflow: hidden case. var ancestorElement = element; while (ancestorElement) { - if (goog.style.getComputedStyle(ancestorElement, 'display') == 'none') { + if (DomUtils.getComputedStyle(ancestorElement, 'display') == 'none') { return false; } - var size = goog.style.getSize(ancestorElement); - var overflow = goog.style.getComputedStyle(ancestorElement, 'overflow'); - if ((overflow == 'hidden') && size.isEmpty()) { + var size = DomUtils.getSize(ancestorElement); + var overflow = DomUtils.getComputedStyle(ancestorElement, 'overflow'); + if ((overflow == 'hidden') && size.area() == 0) { return false; } - if (goog.style.getComputedStyle(ancestorElement, 'visibility') == + if (DomUtils.getComputedStyle(ancestorElement, 'visibility') == 'hidden') { return false; } - ancestorElement = goog.dom.getParentElement(ancestorElement); + ancestorElement = DomUtils.getParentElement(ancestorElement); } return true; }; diff --git a/third_party/document_image_extractor/third_party/LICENSE b/third_party/document_image_extractor/third_party/LICENSE deleted file mode 100644 index a32e00c..0000000 --- a/third_party/document_image_extractor/third_party/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/document_image_extractor/third_party/OWNERS b/third_party/document_image_extractor/third_party/OWNERS deleted file mode 100644 index 150374c..0000000 --- a/third_party/document_image_extractor/third_party/OWNERS +++ /dev/null @@ -1,3 +0,0 @@ -kkimlabs@chromium.org -rfevang@chromium.org -noyau@chromium.org
\ No newline at end of file diff --git a/third_party/document_image_extractor/third_party/README.chromium b/third_party/document_image_extractor/third_party/README.chromium deleted file mode 100644 index adda872..0000000 --- a/third_party/document_image_extractor/third_party/README.chromium +++ /dev/null @@ -1,15 +0,0 @@ -Name: Document image extractor scripts and dependencies -Short Name: document_image_extractor -URL: google3/image/collections/extension/ -Version: 0 -Date: 3/26/2015 -Security Critical: No -License: BSD - -Description: -The document image extractor is used to extract all images from a webpage and -assign each one a relevance. - -Local Modifications: -constant.js: stripped of all unneeded constants. -dom_controller.js: removed unused depedency on GenUtils diff --git a/third_party/document_image_extractor/third_party/closure-library/AUTHORS b/third_party/document_image_extractor/third_party/closure-library/AUTHORS deleted file mode 100644 index d5fa71f8..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/AUTHORS +++ /dev/null @@ -1,19 +0,0 @@ -# This is a list of contributors to the Closure Library. - -# Names should be added to this file like so: -# Name or Organization <email address> - -Google Inc. -Stellar Science Ltd. -Mohamed Mansour <hello@mohamedmansour.com> -Bjorn Tipling <bjorn.tipling@gmail.com> -SameGoal LLC <help@samegoal.com> -Guido Tapia <guido.tapia@gmail.com> -Andrew Mattie <amattie@gmail.com> -Ilia Mirkin <ibmirkin@gmail.com> -Ivan Kozik <ivan.kozik@gmail.com> -Rich Dougherty <rich@rd.gen.nz> -Chad Killingsworth <chadkillingsworth@missouristate.edu> -Dan Pupius <dan.pupius@gmail.com> -Mike Dunn <dunn74@gmail.com> -Kengo Toda <skypencil@gmail.com> diff --git a/third_party/document_image_extractor/third_party/closure-library/LICENSE b/third_party/document_image_extractor/third_party/closure-library/LICENSE deleted file mode 100644 index d9a10c0..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/third_party/document_image_extractor/third_party/closure-library/README.chromium b/third_party/document_image_extractor/third_party/closure-library/README.chromium deleted file mode 100644 index 402ab3b..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/README.chromium +++ /dev/null @@ -1,18 +0,0 @@ -Name: Closure Library -URL: https://github.com/google/closure-library -Version: 848686a4791374beaa99478cdf37d95deb2752e1 -InfoURL: http://developers.google.com/closure/library -Security Critical: No -License: Apache 2.0 - -Description: -Closure Library is a powerful, low level JavaScript library designed -for building complex and scalable web applications. - -Local Modifications: -Only the files actually used by the scripts in document_image_extractor/src are kept. -This includes a number of JavaScript source files and a few python modules to scan -sources for closure dependencies. - -A few cosmetic changes were made to a few closure-library classes so that compilation -would pass with our third_party/closure_compiler/checker.py. See chrome-changes.diff diff --git a/third_party/document_image_extractor/third_party/closure-library/chrome-changes.diff b/third_party/document_image_extractor/third_party/closure-library/chrome-changes.diff deleted file mode 100644 index 174aad9..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/chrome-changes.diff +++ /dev/null @@ -1,105 +0,0 @@ -diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/dom.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/dom.js -index 9b9ec9e..2d0cdd0 100644 ---- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/dom.js -+++ b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/dom.js -@@ -249,7 +249,7 @@ goog.dom.getElementByClass = function(className, opt_el) { - * @param {string} className the name of the class to look for. - * @param {!Element|!Document=} opt_root Optional element or document to look - * in. -- * @return {!Element} The first item with the class name provided. -+ * @return {!Element|null} The first item with the class name provided. - * @throws {goog.asserts.AssertionError} Thrown if no element is found. - */ - goog.dom.getRequiredElementByClass = function(className, opt_root) { -@@ -2340,7 +2340,7 @@ goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) { - * @param {string} className the name of the class to look for. - * @param {(!Element|!Document)=} opt_root Optional element or document to look - * in. -- * @return {!Element} The first item found with the class name provided. -+ * @return {!Element|null} The first item found with the class name provided. - * @throws {goog.asserts.AssertionError} Thrown if no element is found. - */ - goog.dom.DomHelper.prototype.getRequiredElementByClass = function(className, -diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/style/style.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/style/style.js -index c9179b2f..9ed0efa 100644 ---- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/style/style.js -+++ b/third_party/document_image_extractor/third_party/closure-library/closure/goog/style/style.js -@@ -38,8 +38,8 @@ goog.require('goog.object'); - goog.require('goog.string'); - goog.require('goog.userAgent'); - --goog.forwardDeclare('goog.events.BrowserEvent'); --goog.forwardDeclare('goog.events.Event'); -+goog.require('goog.events.BrowserEvent'); -+goog.require('goog.events.Event'); - - - /** -@@ -438,7 +438,7 @@ goog.style.getViewportPageOffset = function(doc) { - * If the element is not in the DOM, the result is undefined, and an error may - * be thrown depending on user agent. - * -- * @param {!Element} el The element whose bounding rectangle is being queried. -+ * @param {!Element|null} el The element whose bounding rectangle is being queried. - * @return {Object} A native bounding rectangle with numerical left, top, - * right, and bottom. Reported by Firefox to be of object type ClientRect. - * @private -@@ -819,7 +819,7 @@ goog.style.getRelativePosition = function(a, b) { - /** - * Returns the position of the event or the element's border box relative to - * the client viewport. -- * @param {!Element} el Element whose position to get. -+ * @param {!Element|null} el Element whose position to get. - * @return {!goog.math.Coordinate} The position. - * @private - */ -diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventhandler.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventhandler.js -index 16b1ad0..3551d10 100644 ---- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventhandler.js -+++ b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventhandler.js -@@ -61,7 +61,7 @@ goog.require('goog.Disposable'); - goog.require('goog.events'); - goog.require('goog.object'); - --goog.forwardDeclare('goog.events.EventWrapper'); -+goog.require('goog.events.EventWrapper'); - - - -diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/events.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/events.js -index 39cc405..7687b5c 100644 ---- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/events.js -+++ b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/events.js -@@ -63,8 +63,8 @@ goog.require('goog.events.BrowserFeature'); - goog.require('goog.events.Listenable'); - goog.require('goog.events.ListenerMap'); - --goog.forwardDeclare('goog.debug.ErrorHandler'); --goog.forwardDeclare('goog.events.EventWrapper'); -+goog.require('goog.debug.ErrorHandler'); -+goog.require('goog.events.EventWrapper'); - - - /** -diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/ui/component.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/ui/component.js -index b8806fd..0ee9b9f 100644 ---- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/ui/component.js -+++ b/third_party/document_image_extractor/third_party/closure-library/closure/goog/ui/component.js -@@ -474,7 +474,7 @@ goog.ui.Component.prototype.getElement = function() { - * it assumes that the element exists (i.e. the component has been - * rendered/decorated) and will cause an assertion error otherwise (if - * assertion is enabled). -- * @return {!Element} The element for the component. -+ * @return {!Element|null} The element for the component. - */ - goog.ui.Component.prototype.getElementStrict = function() { - var el = this.element_; -@@ -530,7 +530,7 @@ goog.ui.Component.prototype.getElementByClass = function(className) { - * element to be present in the dom thus returning a required value. Otherwise, - * will assert. - * @param {string} className The name of the class to look for. -- * @return {!Element} The first item with the class name provided. -+ * @return {!Element|null} The first item with the class name provided. - */ - goog.ui.Component.prototype.getRequiredElementByClass = function(className) { - var el = this.getElementByClass(className); diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/bin/build/closurebuilder.py b/third_party/document_image_extractor/third_party/closure-library/closure/bin/build/closurebuilder.py deleted file mode 100755 index 9e4e2eb..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/bin/build/closurebuilder.py +++ /dev/null @@ -1,287 +0,0 @@ -#!/usr/bin/env python -# -# 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. - -"""Utility for Closure Library dependency calculation. - -ClosureBuilder scans source files to build dependency info. From the -dependencies, the script can produce a manifest in dependency order, -a concatenated script, or compiled output from the Closure Compiler. - -Paths to files can be expressed as individual arguments to the tool (intended -for use with find and xargs). As a convenience, --root can be used to specify -all JS files below a directory. - -usage: %prog [options] [file1.js file2.js ...] -""" - -__author__ = 'nnaze@google.com (Nathan Naze)' - - -import logging -import optparse -import os -import sys - -import depstree -import jscompiler -import source -import treescan - - -def _GetOptionsParser(): - """Get the options parser.""" - - parser = optparse.OptionParser(__doc__) - parser.add_option('-i', - '--input', - dest='inputs', - action='append', - default=[], - help='One or more input files to calculate dependencies ' - 'for. The namespaces in this file will be combined with ' - 'those given with the -n flag to form the set of ' - 'namespaces to find dependencies for.') - parser.add_option('-n', - '--namespace', - dest='namespaces', - action='append', - default=[], - help='One or more namespaces to calculate dependencies ' - 'for. These namespaces will be combined with those given ' - 'with the -i flag to form the set of namespaces to find ' - 'dependencies for. A Closure namespace is a ' - 'dot-delimited path expression declared with a call to ' - 'goog.provide() (e.g. "goog.array" or "foo.bar").') - parser.add_option('--root', - dest='roots', - action='append', - default=[], - help='The paths that should be traversed to build the ' - 'dependencies.') - parser.add_option('-o', - '--output_mode', - dest='output_mode', - type='choice', - action='store', - choices=['list', 'script', 'compiled'], - default='list', - help='The type of output to generate from this script. ' - 'Options are "list" for a list of filenames, "script" ' - 'for a single script containing the contents of all the ' - 'files, or "compiled" to produce compiled output with ' - 'the Closure Compiler. Default is "list".') - parser.add_option('-c', - '--compiler_jar', - dest='compiler_jar', - action='store', - help='The location of the Closure compiler .jar file.') - parser.add_option('-f', - '--compiler_flags', - dest='compiler_flags', - default=[], - action='append', - help='Additional flags to pass to the Closure compiler. ' - 'To pass multiple flags, --compiler_flags has to be ' - 'specified multiple times.') - parser.add_option('-j', - '--jvm_flags', - dest='jvm_flags', - default=[], - action='append', - help='Additional flags to pass to the JVM compiler. ' - 'To pass multiple flags, --jvm_flags has to be ' - 'specified multiple times.') - parser.add_option('--output_file', - dest='output_file', - action='store', - help=('If specified, write output to this path instead of ' - 'writing to standard output.')) - - return parser - - -def _GetInputByPath(path, sources): - """Get the source identified by a path. - - Args: - path: str, A path to a file that identifies a source. - sources: An iterable collection of source objects. - - Returns: - The source from sources identified by path, if found. Converts to - real paths for comparison. - """ - for js_source in sources: - # Convert both to real paths for comparison. - if os.path.realpath(path) == os.path.realpath(js_source.GetPath()): - return js_source - - -def _GetClosureBaseFile(sources): - """Given a set of sources, returns the one base.js file. - - Note that if zero or two or more base.js files are found, an error message - will be written and the program will be exited. - - Args: - sources: An iterable of _PathSource objects. - - Returns: - The _PathSource representing the base Closure file. - """ - base_files = [ - js_source for js_source in sources if _IsClosureBaseFile(js_source)] - - if not base_files: - logging.error('No Closure base.js file found.') - sys.exit(1) - if len(base_files) > 1: - logging.error('More than one Closure base.js files found at these paths:') - for base_file in base_files: - logging.error(base_file.GetPath()) - sys.exit(1) - return base_files[0] - - -def _IsClosureBaseFile(js_source): - """Returns true if the given _PathSource is the Closure base.js source.""" - return (os.path.basename(js_source.GetPath()) == 'base.js' and - js_source.provides == set(['goog'])) - - -class _PathSource(source.Source): - """Source file subclass that remembers its file path.""" - - def __init__(self, path): - """Initialize a source. - - Args: - path: str, Path to a JavaScript file. The source string will be read - from this file. - """ - super(_PathSource, self).__init__(source.GetFileContents(path)) - - self._path = path - - def __str__(self): - return 'PathSource %s' % self._path - - def GetPath(self): - """Returns the path.""" - return self._path - - -def _WrapGoogModuleSource(src): - return ('goog.loadModule(function(exports) {{' - '"use strict";' - '{0}' - '\n' # terminate any trailing single line comment. - ';return exports' - '}});\n').format(src) - - -def main(): - logging.basicConfig(format=(sys.argv[0] + ': %(message)s'), - level=logging.INFO) - options, args = _GetOptionsParser().parse_args() - - # Make our output pipe. - if options.output_file: - out = open(options.output_file, 'w') - else: - out = sys.stdout - - sources = set() - - logging.info('Scanning paths...') - for path in options.roots: - for js_path in treescan.ScanTreeForJsFiles(path): - sources.add(_PathSource(js_path)) - - # Add scripts specified on the command line. - for js_path in args: - sources.add(_PathSource(js_path)) - - logging.info('%s sources scanned.', len(sources)) - - # Though deps output doesn't need to query the tree, we still build it - # to validate dependencies. - logging.info('Building dependency tree..') - tree = depstree.DepsTree(sources) - - input_namespaces = set() - inputs = options.inputs or [] - for input_path in inputs: - js_input = _GetInputByPath(input_path, sources) - if not js_input: - logging.error('No source matched input %s', input_path) - sys.exit(1) - input_namespaces.update(js_input.provides) - - input_namespaces.update(options.namespaces) - - if not input_namespaces: - logging.error('No namespaces found. At least one namespace must be ' - 'specified with the --namespace or --input flags.') - sys.exit(2) - - # The Closure Library base file must go first. - base = _GetClosureBaseFile(sources) - deps = [base] + tree.GetDependencies(input_namespaces) - - output_mode = options.output_mode - if output_mode == 'list': - out.writelines([js_source.GetPath() + '\n' for js_source in deps]) - elif output_mode == 'script': - for js_source in deps: - src = js_source.GetSource() - if js_source.is_goog_module: - src = _WrapGoogModuleSource(src) - out.write(src + '\n') - elif output_mode == 'compiled': - logging.warning("""\ -Closure Compiler now natively understands and orders Closure dependencies and -is prefererred over using this script for performing JavaScript compilation. - -Please migrate your codebase. - -See: -https://github.com/google/closure-compiler/wiki/Manage-Closure-Dependencies -""") - - # Make sure a .jar is specified. - if not options.compiler_jar: - logging.error('--compiler_jar flag must be specified if --output is ' - '"compiled"') - sys.exit(2) - - # Will throw an error if the compilation fails. - compiled_source = jscompiler.Compile( - options.compiler_jar, - [js_source.GetPath() for js_source in deps], - jvm_flags=options.jvm_flags, - compiler_flags=options.compiler_flags) - - logging.info('JavaScript compilation succeeded.') - out.write(compiled_source) - - else: - logging.error('Invalid value for --output flag.') - sys.exit(2) - - -if __name__ == '__main__': - main() diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/bin/calcdeps.py b/third_party/document_image_extractor/third_party/closure-library/closure/bin/calcdeps.py deleted file mode 100755 index 9cb1a6d..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/bin/calcdeps.py +++ /dev/null @@ -1,590 +0,0 @@ -#!/usr/bin/env python -# -# 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. - - -"""Calculates JavaScript dependencies without requiring Google's build system. - -This tool is deprecated and is provided for legacy users. -See build/closurebuilder.py and build/depswriter.py for the current tools. - -It iterates over a number of search paths and builds a dependency tree. With -the inputs provided, it walks the dependency tree and outputs all the files -required for compilation. -""" - - - - - -try: - import distutils.version -except ImportError: - # distutils is not available in all environments - distutils = None - -import logging -import optparse -import os -import re -import subprocess -import sys - - -_BASE_REGEX_STRING = '^\s*goog\.%s\(\s*[\'"](.+)[\'"]\s*\)' -req_regex = re.compile(_BASE_REGEX_STRING % 'require') -prov_regex = re.compile(_BASE_REGEX_STRING % 'provide') -ns_regex = re.compile('^ns:((\w+\.)*(\w+))$') -version_regex = re.compile('[\.0-9]+') - - -def IsValidFile(ref): - """Returns true if the provided reference is a file and exists.""" - return os.path.isfile(ref) - - -def IsJsFile(ref): - """Returns true if the provided reference is a Javascript file.""" - return ref.endswith('.js') - - -def IsNamespace(ref): - """Returns true if the provided reference is a namespace.""" - return re.match(ns_regex, ref) is not None - - -def IsDirectory(ref): - """Returns true if the provided reference is a directory.""" - return os.path.isdir(ref) - - -def ExpandDirectories(refs): - """Expands any directory references into inputs. - - Description: - Looks for any directories in the provided references. Found directories - are recursively searched for .js files, which are then added to the result - list. - - Args: - refs: a list of references such as files, directories, and namespaces - - Returns: - A list of references with directories removed and replaced by any - .js files that are found in them. Also, the paths will be normalized. - """ - result = [] - for ref in refs: - if IsDirectory(ref): - # Disable 'Unused variable' for subdirs - # pylint: disable=unused-variable - for (directory, subdirs, filenames) in os.walk(ref): - for filename in filenames: - if IsJsFile(filename): - result.append(os.path.join(directory, filename)) - else: - result.append(ref) - return map(os.path.normpath, result) - - -class DependencyInfo(object): - """Represents a dependency that is used to build and walk a tree.""" - - def __init__(self, filename): - self.filename = filename - self.provides = [] - self.requires = [] - - def __str__(self): - return '%s Provides: %s Requires: %s' % (self.filename, - repr(self.provides), - repr(self.requires)) - - -def BuildDependenciesFromFiles(files): - """Build a list of dependencies from a list of files. - - Description: - Takes a list of files, extracts their provides and requires, and builds - out a list of dependency objects. - - Args: - files: a list of files to be parsed for goog.provides and goog.requires. - - Returns: - A list of dependency objects, one for each file in the files argument. - """ - result = [] - filenames = set() - for filename in files: - if filename in filenames: - continue - - # Python 3 requires the file encoding to be specified - if (sys.version_info[0] < 3): - file_handle = open(filename, 'r') - else: - file_handle = open(filename, 'r', encoding='utf8') - - try: - dep = CreateDependencyInfo(filename, file_handle) - result.append(dep) - finally: - file_handle.close() - - filenames.add(filename) - - return result - - -def CreateDependencyInfo(filename, source): - """Create dependency info. - - Args: - filename: Filename for source. - source: File-like object containing source. - - Returns: - A DependencyInfo object with provides and requires filled. - """ - dep = DependencyInfo(filename) - for line in source: - if re.match(req_regex, line): - dep.requires.append(re.search(req_regex, line).group(1)) - if re.match(prov_regex, line): - dep.provides.append(re.search(prov_regex, line).group(1)) - return dep - - -def BuildDependencyHashFromDependencies(deps): - """Builds a hash for searching dependencies by the namespaces they provide. - - Description: - Dependency objects can provide multiple namespaces. This method enumerates - the provides of each dependency and adds them to a hash that can be used - to easily resolve a given dependency by a namespace it provides. - - Args: - deps: a list of dependency objects used to build the hash. - - Raises: - Exception: If a multiple files try to provide the same namepace. - - Returns: - A hash table { namespace: dependency } that can be used to resolve a - dependency by a namespace it provides. - """ - dep_hash = {} - for dep in deps: - for provide in dep.provides: - if provide in dep_hash: - raise Exception('Duplicate provide (%s) in (%s, %s)' % ( - provide, - dep_hash[provide].filename, - dep.filename)) - dep_hash[provide] = dep - return dep_hash - - -def CalculateDependencies(paths, inputs): - """Calculates the dependencies for given inputs. - - Description: - This method takes a list of paths (files, directories) and builds a - searchable data structure based on the namespaces that each .js file - provides. It then parses through each input, resolving dependencies - against this data structure. The final output is a list of files, - including the inputs, that represent all of the code that is needed to - compile the given inputs. - - Args: - paths: the references (files, directories) that are used to build the - dependency hash. - inputs: the inputs (files, directories, namespaces) that have dependencies - that need to be calculated. - - Raises: - Exception: if a provided input is invalid. - - Returns: - A list of all files, including inputs, that are needed to compile the given - inputs. - """ - deps = BuildDependenciesFromFiles(paths + inputs) - search_hash = BuildDependencyHashFromDependencies(deps) - result_list = [] - seen_list = [] - for input_file in inputs: - if IsNamespace(input_file): - namespace = re.search(ns_regex, input_file).group(1) - if namespace not in search_hash: - raise Exception('Invalid namespace (%s)' % namespace) - input_file = search_hash[namespace].filename - if not IsValidFile(input_file) or not IsJsFile(input_file): - raise Exception('Invalid file (%s)' % input_file) - seen_list.append(input_file) - file_handle = open(input_file, 'r') - try: - for line in file_handle: - if re.match(req_regex, line): - require = re.search(req_regex, line).group(1) - ResolveDependencies(require, search_hash, result_list, seen_list) - finally: - file_handle.close() - result_list.append(input_file) - - # All files depend on base.js, so put it first. - base_js_path = FindClosureBasePath(paths) - if base_js_path: - result_list.insert(0, base_js_path) - else: - logging.warning('Closure Library base.js not found.') - - return result_list - - -def FindClosureBasePath(paths): - """Given a list of file paths, return Closure base.js path, if any. - - Args: - paths: A list of paths. - - Returns: - The path to Closure's base.js file including filename, if found. - """ - - for path in paths: - pathname, filename = os.path.split(path) - - if filename == 'base.js': - f = open(path) - - is_base = False - - # Sanity check that this is the Closure base file. Check that this - # is where goog is defined. This is determined by the @provideGoog - # flag. - for line in f: - if '@provideGoog' in line: - is_base = True - break - - f.close() - - if is_base: - return path - -def ResolveDependencies(require, search_hash, result_list, seen_list): - """Takes a given requirement and resolves all of the dependencies for it. - - Description: - A given requirement may require other dependencies. This method - recursively resolves all dependencies for the given requirement. - - Raises: - Exception: when require does not exist in the search_hash. - - Args: - require: the namespace to resolve dependencies for. - search_hash: the data structure used for resolving dependencies. - result_list: a list of filenames that have been calculated as dependencies. - This variable is the output for this function. - seen_list: a list of filenames that have been 'seen'. This is required - for the dependency->dependant ordering. - """ - if require not in search_hash: - raise Exception('Missing provider for (%s)' % require) - - dep = search_hash[require] - if not dep.filename in seen_list: - seen_list.append(dep.filename) - for sub_require in dep.requires: - ResolveDependencies(sub_require, search_hash, result_list, seen_list) - result_list.append(dep.filename) - - -def GetDepsLine(dep, base_path): - """Returns a JS string for a dependency statement in the deps.js file. - - Args: - dep: The dependency that we're printing. - base_path: The path to Closure's base.js including filename. - """ - return 'goog.addDependency("%s", %s, %s);' % ( - GetRelpath(dep.filename, base_path), dep.provides, dep.requires) - - -def GetRelpath(path, start): - """Return a relative path to |path| from |start|.""" - # NOTE: Python 2.6 provides os.path.relpath, which has almost the same - # functionality as this function. Since we want to support 2.4, we have - # to implement it manually. :( - path_list = os.path.abspath(os.path.normpath(path)).split(os.sep) - start_list = os.path.abspath( - os.path.normpath(os.path.dirname(start))).split(os.sep) - - common_prefix_count = 0 - for i in range(0, min(len(path_list), len(start_list))): - if path_list[i] != start_list[i]: - break - common_prefix_count += 1 - - # Always use forward slashes, because this will get expanded to a url, - # not a file path. - return '/'.join(['..'] * (len(start_list) - common_prefix_count) + - path_list[common_prefix_count:]) - - -def PrintLine(msg, out): - out.write(msg) - out.write('\n') - - -def PrintDeps(source_paths, deps, out): - """Print out a deps.js file from a list of source paths. - - Args: - source_paths: Paths that we should generate dependency info for. - deps: Paths that provide dependency info. Their dependency info should - not appear in the deps file. - out: The output file. - - Returns: - True on success, false if it was unable to find the base path - to generate deps relative to. - """ - base_path = FindClosureBasePath(source_paths + deps) - if not base_path: - return False - - PrintLine('// This file was autogenerated by calcdeps.py', out) - excludesSet = set(deps) - - for dep in BuildDependenciesFromFiles(source_paths + deps): - if not dep.filename in excludesSet: - PrintLine(GetDepsLine(dep, base_path), out) - - return True - - -def PrintScript(source_paths, out): - for index, dep in enumerate(source_paths): - PrintLine('// Input %d' % index, out) - f = open(dep, 'r') - PrintLine(f.read(), out) - f.close() - - -def GetJavaVersion(): - """Returns the string for the current version of Java installed.""" - proc = subprocess.Popen(['java', '-version'], stderr=subprocess.PIPE) - proc.wait() - version_line = proc.stderr.read().splitlines()[0] - return version_regex.search(version_line).group() - - -def FilterByExcludes(options, files): - """Filters the given files by the exlusions specified at the command line. - - Args: - options: The flags to calcdeps. - files: The files to filter. - Returns: - A list of files. - """ - excludes = [] - if options.excludes: - excludes = ExpandDirectories(options.excludes) - - excludesSet = set(excludes) - return [i for i in files if not i in excludesSet] - - -def GetPathsFromOptions(options): - """Generates the path files from flag options. - - Args: - options: The flags to calcdeps. - Returns: - A list of files in the specified paths. (strings). - """ - - search_paths = options.paths - if not search_paths: - search_paths = ['.'] # Add default folder if no path is specified. - - search_paths = ExpandDirectories(search_paths) - return FilterByExcludes(options, search_paths) - - -def GetInputsFromOptions(options): - """Generates the inputs from flag options. - - Args: - options: The flags to calcdeps. - Returns: - A list of inputs (strings). - """ - inputs = options.inputs - if not inputs: # Parse stdin - logging.info('No inputs specified. Reading from stdin...') - inputs = filter(None, [line.strip('\n') for line in sys.stdin.readlines()]) - - logging.info('Scanning files...') - inputs = ExpandDirectories(inputs) - - return FilterByExcludes(options, inputs) - - -def Compile(compiler_jar_path, source_paths, out, flags=None): - """Prepares command-line call to Closure compiler. - - Args: - compiler_jar_path: Path to the Closure compiler .jar file. - source_paths: Source paths to build, in order. - flags: A list of additional flags to pass on to Closure compiler. - """ - args = ['java', '-jar', compiler_jar_path] - for path in source_paths: - args += ['--js', path] - - if flags: - args += flags - - logging.info('Compiling with the following command: %s', ' '.join(args)) - proc = subprocess.Popen(args, stdout=subprocess.PIPE) - (stdoutdata, stderrdata) = proc.communicate() - if proc.returncode != 0: - logging.error('JavaScript compilation failed.') - sys.exit(1) - else: - out.write(stdoutdata) - - -def main(): - """The entrypoint for this script.""" - - logging.basicConfig(format='calcdeps.py: %(message)s', level=logging.INFO) - - usage = 'usage: %prog [options] arg' - parser = optparse.OptionParser(usage) - parser.add_option('-i', - '--input', - dest='inputs', - action='append', - help='The inputs to calculate dependencies for. Valid ' - 'values can be files, directories, or namespaces ' - '(ns:goog.net.XhrIo). Only relevant to "list" and ' - '"script" output.') - parser.add_option('-p', - '--path', - dest='paths', - action='append', - help='The paths that should be traversed to build the ' - 'dependencies.') - parser.add_option('-d', - '--dep', - dest='deps', - action='append', - help='Directories or files that should be traversed to ' - 'find required dependencies for the deps file. ' - 'Does not generate dependency information for names ' - 'provided by these files. Only useful in "deps" mode.') - parser.add_option('-e', - '--exclude', - dest='excludes', - action='append', - help='Files or directories to exclude from the --path ' - 'and --input flags') - parser.add_option('-o', - '--output_mode', - dest='output_mode', - action='store', - default='list', - help='The type of output to generate from this script. ' - 'Options are "list" for a list of filenames, "script" ' - 'for a single script containing the contents of all the ' - 'file, "deps" to generate a deps.js file for all ' - 'paths, or "compiled" to produce compiled output with ' - 'the Closure compiler.') - parser.add_option('-c', - '--compiler_jar', - dest='compiler_jar', - action='store', - help='The location of the Closure compiler .jar file.') - parser.add_option('-f', - '--compiler_flag', - '--compiler_flags', # for backwards compatability - dest='compiler_flags', - action='append', - help='Additional flag to pass to the Closure compiler. ' - 'May be specified multiple times to pass multiple flags.') - parser.add_option('--output_file', - dest='output_file', - action='store', - help=('If specified, write output to this path instead of ' - 'writing to standard output.')) - - (options, args) = parser.parse_args() - - search_paths = GetPathsFromOptions(options) - - if options.output_file: - out = open(options.output_file, 'w') - else: - out = sys.stdout - - if options.output_mode == 'deps': - result = PrintDeps(search_paths, ExpandDirectories(options.deps or []), out) - if not result: - logging.error('Could not find Closure Library in the specified paths') - sys.exit(1) - - return - - inputs = GetInputsFromOptions(options) - - logging.info('Finding Closure dependencies...') - deps = CalculateDependencies(search_paths, inputs) - output_mode = options.output_mode - - if output_mode == 'script': - PrintScript(deps, out) - elif output_mode == 'list': - # Just print out a dep per line - for dep in deps: - PrintLine(dep, out) - elif output_mode == 'compiled': - # Make sure a .jar is specified. - if not options.compiler_jar: - logging.error('--compiler_jar flag must be specified if --output is ' - '"compiled"') - sys.exit(1) - - # User friendly version check. - if distutils and not (distutils.version.LooseVersion(GetJavaVersion()) > - distutils.version.LooseVersion('1.6')): - logging.error('Closure Compiler requires Java 1.6 or higher.') - logging.error('Please visit http://www.java.com/getjava') - sys.exit(1) - - Compile(options.compiler_jar, deps, out, options.compiler_flags) - - else: - logging.error('Invalid value for --output flag.') - sys.exit(1) - -if __name__ == '__main__': - main() diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/bin/scopify.py b/third_party/document_image_extractor/third_party/closure-library/closure/bin/scopify.py deleted file mode 100755 index d8057ef..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/bin/scopify.py +++ /dev/null @@ -1,221 +0,0 @@ -#!/usr/bin/python -# -# 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. - - -"""Automatically converts codebases over to goog.scope. - -Usage: -cd path/to/my/dir; -../../../../javascript/closure/bin/scopify.py - -Scans every file in this directory, recursively. Looks for existing -goog.scope calls, and goog.require'd symbols. If it makes sense to -generate a goog.scope call for the file, then we will do so, and -try to auto-generate some aliases based on the goog.require'd symbols. - -Known Issues: - - When a file is goog.scope'd, the file contents will be indented +2. - This may put some lines over 80 chars. These will need to be fixed manually. - - We will only try to create aliases for capitalized names. We do not check - to see if those names will conflict with any existing locals. - - This creates merge conflicts for every line of every outstanding change. - If you intend to run this on your codebase, make sure your team members - know. Better yet, send them this script so that they can scopify their - outstanding changes and "accept theirs". - - When an alias is "captured", it can no longer be stubbed out for testing. - Run your tests. - -""" - -__author__ = 'nicksantos@google.com (Nick Santos)' - -import os.path -import re -import sys - -REQUIRES_RE = re.compile(r"goog.require\('([^']*)'\)") - -# Edit this manually if you want something to "always" be aliased. -# TODO(nicksantos): Add a flag for this. -DEFAULT_ALIASES = {} - -def Transform(lines): - """Converts the contents of a file into javascript that uses goog.scope. - - Arguments: - lines: A list of strings, corresponding to each line of the file. - Returns: - A new list of strings, or None if the file was not modified. - """ - requires = [] - - # Do an initial scan to be sure that this file can be processed. - for line in lines: - # Skip this file if it has already been scopified. - if line.find('goog.scope') != -1: - return None - - # If there are any global vars or functions, then we also have - # to skip the whole file. We might be able to deal with this - # more elegantly. - if line.find('var ') == 0 or line.find('function ') == 0: - return None - - for match in REQUIRES_RE.finditer(line): - requires.append(match.group(1)) - - if len(requires) == 0: - return None - - # Backwards-sort the requires, so that when one is a substring of another, - # we match the longer one first. - for val in DEFAULT_ALIASES.values(): - if requires.count(val) == 0: - requires.append(val) - - requires.sort() - requires.reverse() - - # Generate a map of requires to their aliases - aliases_to_globals = DEFAULT_ALIASES.copy() - for req in requires: - index = req.rfind('.') - if index == -1: - alias = req - else: - alias = req[(index + 1):] - - # Don't scopify lowercase namespaces, because they may conflict with - # local variables. - if alias[0].isupper(): - aliases_to_globals[alias] = req - - aliases_to_matchers = {} - globals_to_aliases = {} - for alias, symbol in aliases_to_globals.items(): - globals_to_aliases[symbol] = alias - aliases_to_matchers[alias] = re.compile('\\b%s\\b' % symbol) - - # Insert a goog.scope that aliases all required symbols. - result = [] - - START = 0 - SEEN_REQUIRES = 1 - IN_SCOPE = 2 - - mode = START - aliases_used = set() - insertion_index = None - num_blank_lines = 0 - for line in lines: - if mode == START: - result.append(line) - - if re.search(REQUIRES_RE, line): - mode = SEEN_REQUIRES - - elif mode == SEEN_REQUIRES: - if (line and - not re.search(REQUIRES_RE, line) and - not line.isspace()): - # There should be two blank lines before goog.scope - result += ['\n'] * 2 - result.append('goog.scope(function() {\n') - insertion_index = len(result) - result += ['\n'] * num_blank_lines - mode = IN_SCOPE - elif line.isspace(): - # Keep track of the number of blank lines before each block of code so - # that we can move them after the goog.scope line if necessary. - num_blank_lines += 1 - else: - # Print the blank lines we saw before this code block - result += ['\n'] * num_blank_lines - num_blank_lines = 0 - result.append(line) - - if mode == IN_SCOPE: - for symbol in requires: - if not symbol in globals_to_aliases: - continue - - alias = globals_to_aliases[symbol] - matcher = aliases_to_matchers[alias] - for match in matcher.finditer(line): - # Check to make sure we're not in a string. - # We do this by being as conservative as possible: - # if there are any quote or double quote characters - # before the symbol on this line, then bail out. - before_symbol = line[:match.start(0)] - if before_symbol.count('"') > 0 or before_symbol.count("'") > 0: - continue - - line = line.replace(match.group(0), alias) - aliases_used.add(alias) - - if line.isspace(): - # Truncate all-whitespace lines - result.append('\n') - else: - result.append(line) - - if len(aliases_used): - aliases_used = [alias for alias in aliases_used] - aliases_used.sort() - aliases_used.reverse() - for alias in aliases_used: - symbol = aliases_to_globals[alias] - result.insert(insertion_index, - 'var %s = %s;\n' % (alias, symbol)) - result.append('}); // goog.scope\n') - return result - else: - return None - -def TransformFileAt(path): - """Converts a file into javascript that uses goog.scope. - - Arguments: - path: A path to a file. - """ - f = open(path) - lines = Transform(f.readlines()) - if lines: - f = open(path, 'w') - for l in lines: - f.write(l) - f.close() - -if __name__ == '__main__': - args = sys.argv[1:] - if not len(args): - args = '.' - - for file_name in args: - if os.path.isdir(file_name): - for root, dirs, files in os.walk(file_name): - for name in files: - if name.endswith('.js') and \ - not os.path.islink(os.path.join(root, name)): - TransformFileAt(os.path.join(root, name)) - else: - if file_name.endswith('.js') and \ - not os.path.islink(file_name): - TransformFileAt(file_name) diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/array/array.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/array/array.js deleted file mode 100644 index bd99626..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/array/array.js +++ /dev/null @@ -1,1655 +0,0 @@ -// 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 for manipulating arrays. - * - * @author arv@google.com (Erik Arvidsson) - */ - - -goog.provide('goog.array'); -goog.provide('goog.array.ArrayLike'); - -goog.require('goog.asserts'); - - -/** - * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should - * rely on Array.prototype functions, if available. - * - * The Array.prototype functions can be defined by external libraries like - * Prototype and setting this flag to false forces closure to use its own - * goog.array implementation. - * - * If your javascript can be loaded by a third party site and you are wary about - * relying on the prototype functions, specify - * "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler. - * - * Setting goog.TRUSTED_SITE to false will automatically set - * NATIVE_ARRAY_PROTOTYPES to false. - */ -goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE); - - -/** - * @define {boolean} If true, JSCompiler will use the native implementation of - * array functions where appropriate (e.g., {@code Array#filter}) and remove the - * unused pure JS implementation. - */ -goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false); - - -/** - * @typedef {Array|NodeList|Arguments|{length: number}} - */ -goog.array.ArrayLike; - - -/** - * Returns the last element in an array without removing it. - * Same as goog.array.last. - * @param {Array<T>|goog.array.ArrayLike} array The array. - * @return {T} Last item in array. - * @template T - */ -goog.array.peek = function(array) { - return array[array.length - 1]; -}; - - -/** - * Returns the last element in an array without removing it. - * Same as goog.array.peek. - * @param {Array<T>|goog.array.ArrayLike} array The array. - * @return {T} Last item in array. - * @template T - */ -goog.array.last = goog.array.peek; - - -/** - * Reference to the original {@code Array.prototype}. - * @private - */ -goog.array.ARRAY_PROTOTYPE_ = Array.prototype; - - -// NOTE(arv): Since most of the array functions are generic it allows you to -// pass an array-like object. Strings have a length and are considered array- -// like. However, the 'in' operator does not work on strings so we cannot just -// use the array path even if the browser supports indexing into strings. We -// therefore end up splitting the string. - - -/** - * Returns the index of the first element of an array with a specified value, or - * -1 if the element is not present in the array. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof} - * - * @param {Array<T>|goog.array.ArrayLike} arr The array to be searched. - * @param {T} obj The object for which we are searching. - * @param {number=} opt_fromIndex The index at which to start the search. If - * omitted the search starts at index 0. - * @return {number} The index of the first matching array element. - * @template T - */ -goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.indexOf) ? - function(arr, obj, opt_fromIndex) { - goog.asserts.assert(arr.length != null); - - return goog.array.ARRAY_PROTOTYPE_.indexOf.call(arr, obj, opt_fromIndex); - } : - function(arr, obj, opt_fromIndex) { - var fromIndex = opt_fromIndex == null ? - 0 : (opt_fromIndex < 0 ? - Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex); - - if (goog.isString(arr)) { - // Array.prototype.indexOf uses === so only strings should be found. - if (!goog.isString(obj) || obj.length != 1) { - return -1; - } - return arr.indexOf(obj, fromIndex); - } - - for (var i = fromIndex; i < arr.length; i++) { - if (i in arr && arr[i] === obj) - return i; - } - return -1; - }; - - -/** - * Returns the index of the last element of an array with a specified value, or - * -1 if the element is not present in the array. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof} - * - * @param {!Array<T>|!goog.array.ArrayLike} arr The array to be searched. - * @param {T} obj The object for which we are searching. - * @param {?number=} opt_fromIndex The index at which to start the search. If - * omitted the search starts at the end of the array. - * @return {number} The index of the last matching array element. - * @template T - */ -goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.lastIndexOf) ? - function(arr, obj, opt_fromIndex) { - goog.asserts.assert(arr.length != null); - - // Firefox treats undefined and null as 0 in the fromIndex argument which - // leads it to always return -1 - var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex; - return goog.array.ARRAY_PROTOTYPE_.lastIndexOf.call(arr, obj, fromIndex); - } : - function(arr, obj, opt_fromIndex) { - var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex; - - if (fromIndex < 0) { - fromIndex = Math.max(0, arr.length + fromIndex); - } - - if (goog.isString(arr)) { - // Array.prototype.lastIndexOf uses === so only strings should be found. - if (!goog.isString(obj) || obj.length != 1) { - return -1; - } - return arr.lastIndexOf(obj, fromIndex); - } - - for (var i = fromIndex; i >= 0; i--) { - if (i in arr && arr[i] === obj) - return i; - } - return -1; - }; - - -/** - * Calls a function for each element in an array. Skips holes in the array. - * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach} - * - * @param {Array<T>|goog.array.ArrayLike} arr Array or array like object over - * which to iterate. - * @param {?function(this: S, T, number, ?): ?} f The function to call for every - * element. This function takes 3 arguments (the element, the index and the - * array). The return value is ignored. - * @param {S=} opt_obj The object to be used as the value of 'this' within f. - * @template T,S - */ -goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.forEach) ? - function(arr, f, opt_obj) { - goog.asserts.assert(arr.length != null); - - goog.array.ARRAY_PROTOTYPE_.forEach.call(arr, f, opt_obj); - } : - function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = 0; i < l; i++) { - if (i in arr2) { - f.call(opt_obj, arr2[i], i, arr); - } - } - }; - - -/** - * Calls a function for each element in an array, starting from the last - * element rather than the first. - * - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this: S, T, number, ?): ?} f The function to call for every - * element. This function - * takes 3 arguments (the element, the index and the array). The return - * value is ignored. - * @param {S=} opt_obj The object to be used as the value of 'this' - * within f. - * @template T,S - */ -goog.array.forEachRight = function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = l - 1; i >= 0; --i) { - if (i in arr2) { - f.call(opt_obj, arr2[i], i, arr); - } - } -}; - - -/** - * Calls a function for each element in an array, and if the function returns - * true adds the element to a new array. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-filter} - * - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?):boolean} f The function to call for - * every element. This function - * takes 3 arguments (the element, the index and the array) and must - * return a Boolean. If the return value is true the element is added to the - * result array. If it is false the element is not included. - * @param {S=} opt_obj The object to be used as the value of 'this' - * within f. - * @return {!Array<T>} a new array in which only elements that passed the test - * are present. - * @template T,S - */ -goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.filter) ? - function(arr, f, opt_obj) { - goog.asserts.assert(arr.length != null); - - return goog.array.ARRAY_PROTOTYPE_.filter.call(arr, f, opt_obj); - } : - function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var res = []; - var resLength = 0; - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = 0; i < l; i++) { - if (i in arr2) { - var val = arr2[i]; // in case f mutates arr2 - if (f.call(opt_obj, val, i, arr)) { - res[resLength++] = val; - } - } - } - return res; - }; - - -/** - * Calls a function for each element in an array and inserts the result into a - * new array. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-map} - * - * @param {Array<VALUE>|goog.array.ArrayLike} arr Array or array like object - * over which to iterate. - * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call - * for every element. This function takes 3 arguments (the element, - * the index and the array) and should return something. The result will be - * inserted into a new array. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within f. - * @return {!Array<RESULT>} a new array with the results from f. - * @template THIS, VALUE, RESULT - */ -goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.map) ? - function(arr, f, opt_obj) { - goog.asserts.assert(arr.length != null); - - return goog.array.ARRAY_PROTOTYPE_.map.call(arr, f, opt_obj); - } : - function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var res = new Array(l); - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = 0; i < l; i++) { - if (i in arr2) { - res[i] = f.call(opt_obj, arr2[i], i, arr); - } - } - return res; - }; - - -/** - * Passes every element of an array into a function and accumulates the result. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce} - * - * For example: - * var a = [1, 2, 3, 4]; - * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0); - * returns 10 - * - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {function(this:S, R, T, number, ?) : R} f The function to call for - * every element. This function - * takes 4 arguments (the function's previous result or the initial value, - * the value of the current array element, the current array index, and the - * array itself) - * function(previousValue, currentValue, index, array). - * @param {?} val The initial value to pass into the function on the first call. - * @param {S=} opt_obj The object to be used as the value of 'this' - * within f. - * @return {R} Result of evaluating f repeatedly across the values of the array. - * @template T,S,R - */ -goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.reduce) ? - function(arr, f, val, opt_obj) { - goog.asserts.assert(arr.length != null); - if (opt_obj) { - f = goog.bind(f, opt_obj); - } - return goog.array.ARRAY_PROTOTYPE_.reduce.call(arr, f, val); - } : - function(arr, f, val, opt_obj) { - var rval = val; - goog.array.forEach(arr, function(val, index) { - rval = f.call(opt_obj, rval, val, index, arr); - }); - return rval; - }; - - -/** - * Passes every element of an array into a function and accumulates the result, - * starting from the last element and working towards the first. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright} - * - * For example: - * var a = ['a', 'b', 'c']; - * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, ''); - * returns 'cba' - * - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, R, T, number, ?) : R} f The function to call for - * every element. This function - * takes 4 arguments (the function's previous result or the initial value, - * the value of the current array element, the current array index, and the - * array itself) - * function(previousValue, currentValue, index, array). - * @param {?} val The initial value to pass into the function on the first call. - * @param {S=} opt_obj The object to be used as the value of 'this' - * within f. - * @return {R} Object returned as a result of evaluating f repeatedly across the - * values of the array. - * @template T,S,R - */ -goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.reduceRight) ? - function(arr, f, val, opt_obj) { - goog.asserts.assert(arr.length != null); - if (opt_obj) { - f = goog.bind(f, opt_obj); - } - return goog.array.ARRAY_PROTOTYPE_.reduceRight.call(arr, f, val); - } : - function(arr, f, val, opt_obj) { - var rval = val; - goog.array.forEachRight(arr, function(val, index) { - rval = f.call(opt_obj, rval, val, index, arr); - }); - return rval; - }; - - -/** - * Calls f for each element of an array. If any call returns true, some() - * returns true (without checking the remaining elements). If all calls - * return false, some() returns false. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-some} - * - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call for - * for every element. This function takes 3 arguments (the element, the - * index and the array) and should return a boolean. - * @param {S=} opt_obj The object to be used as the value of 'this' - * within f. - * @return {boolean} true if any element passes the test. - * @template T,S - */ -goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.some) ? - function(arr, f, opt_obj) { - goog.asserts.assert(arr.length != null); - - return goog.array.ARRAY_PROTOTYPE_.some.call(arr, f, opt_obj); - } : - function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = 0; i < l; i++) { - if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) { - return true; - } - } - return false; - }; - - -/** - * Call f for each element of an array. If all calls return true, every() - * returns true. If any call returns false, every() returns false and - * does not continue to check the remaining elements. - * - * See {@link http://tinyurl.com/developer-mozilla-org-array-every} - * - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call for - * for every element. This function takes 3 arguments (the element, the - * index and the array) and should return a boolean. - * @param {S=} opt_obj The object to be used as the value of 'this' - * within f. - * @return {boolean} false if any element fails the test. - * @template T,S - */ -goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES && - (goog.array.ASSUME_NATIVE_FUNCTIONS || - goog.array.ARRAY_PROTOTYPE_.every) ? - function(arr, f, opt_obj) { - goog.asserts.assert(arr.length != null); - - return goog.array.ARRAY_PROTOTYPE_.every.call(arr, f, opt_obj); - } : - function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = 0; i < l; i++) { - if (i in arr2 && !f.call(opt_obj, arr2[i], i, arr)) { - return false; - } - } - return true; - }; - - -/** - * Counts the array elements that fulfill the predicate, i.e. for which the - * callback function returns true. Skips holes in the array. - * - * @param {!(Array<T>|goog.array.ArrayLike)} arr Array or array like object - * over which to iterate. - * @param {function(this: S, T, number, ?): boolean} f The function to call for - * every element. Takes 3 arguments (the element, the index and the array). - * @param {S=} opt_obj The object to be used as the value of 'this' within f. - * @return {number} The number of the matching elements. - * @template T,S - */ -goog.array.count = function(arr, f, opt_obj) { - var count = 0; - goog.array.forEach(arr, function(element, index, arr) { - if (f.call(opt_obj, element, index, arr)) { - ++count; - } - }, opt_obj); - return count; -}; - - -/** - * Search an array for the first element that satisfies a given condition and - * return that element. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call - * for every element. This function takes 3 arguments (the element, the - * index and the array) and should return a boolean. - * @param {S=} opt_obj An optional "this" context for the function. - * @return {T|null} The first array element that passes the test, or null if no - * element is found. - * @template T,S - */ -goog.array.find = function(arr, f, opt_obj) { - var i = goog.array.findIndex(arr, f, opt_obj); - return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i]; -}; - - -/** - * Search an array for the first element that satisfies a given condition and - * return its index. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call for - * every element. This function - * takes 3 arguments (the element, the index and the array) and should - * return a boolean. - * @param {S=} opt_obj An optional "this" context for the function. - * @return {number} The index of the first array element that passes the test, - * or -1 if no element is found. - * @template T,S - */ -goog.array.findIndex = function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = 0; i < l; i++) { - if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) { - return i; - } - } - return -1; -}; - - -/** - * Search an array (in reverse order) for the last element that satisfies a - * given condition and return that element. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call - * for every element. This function - * takes 3 arguments (the element, the index and the array) and should - * return a boolean. - * @param {S=} opt_obj An optional "this" context for the function. - * @return {T|null} The last array element that passes the test, or null if no - * element is found. - * @template T,S - */ -goog.array.findRight = function(arr, f, opt_obj) { - var i = goog.array.findIndexRight(arr, f, opt_obj); - return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i]; -}; - - -/** - * Search an array (in reverse order) for the last element that satisfies a - * given condition and return its index. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call - * for every element. This function - * takes 3 arguments (the element, the index and the array) and should - * return a boolean. - * @param {S=} opt_obj An optional "this" context for the function. - * @return {number} The index of the last array element that passes the test, - * or -1 if no element is found. - * @template T,S - */ -goog.array.findIndexRight = function(arr, f, opt_obj) { - var l = arr.length; // must be fixed during loop... see docs - var arr2 = goog.isString(arr) ? arr.split('') : arr; - for (var i = l - 1; i >= 0; i--) { - if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) { - return i; - } - } - return -1; -}; - - -/** - * Whether the array contains the given object. - * @param {goog.array.ArrayLike} arr The array to test for the presence of the - * element. - * @param {*} obj The object for which to test. - * @return {boolean} true if obj is present. - */ -goog.array.contains = function(arr, obj) { - return goog.array.indexOf(arr, obj) >= 0; -}; - - -/** - * Whether the array is empty. - * @param {goog.array.ArrayLike} arr The array to test. - * @return {boolean} true if empty. - */ -goog.array.isEmpty = function(arr) { - return arr.length == 0; -}; - - -/** - * Clears the array. - * @param {goog.array.ArrayLike} arr Array or array like object to clear. - */ -goog.array.clear = function(arr) { - // For non real arrays we don't have the magic length so we delete the - // indices. - if (!goog.isArray(arr)) { - for (var i = arr.length - 1; i >= 0; i--) { - delete arr[i]; - } - } - arr.length = 0; -}; - - -/** - * Pushes an item into an array, if it's not already in the array. - * @param {Array<T>} arr Array into which to insert the item. - * @param {T} obj Value to add. - * @template T - */ -goog.array.insert = function(arr, obj) { - if (!goog.array.contains(arr, obj)) { - arr.push(obj); - } -}; - - -/** - * Inserts an object at the given index of the array. - * @param {goog.array.ArrayLike} arr The array to modify. - * @param {*} obj The object to insert. - * @param {number=} opt_i The index at which to insert the object. If omitted, - * treated as 0. A negative index is counted from the end of the array. - */ -goog.array.insertAt = function(arr, obj, opt_i) { - goog.array.splice(arr, opt_i, 0, obj); -}; - - -/** - * Inserts at the given index of the array, all elements of another array. - * @param {goog.array.ArrayLike} arr The array to modify. - * @param {goog.array.ArrayLike} elementsToAdd The array of elements to add. - * @param {number=} opt_i The index at which to insert the object. If omitted, - * treated as 0. A negative index is counted from the end of the array. - */ -goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) { - goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd); -}; - - -/** - * Inserts an object into an array before a specified object. - * @param {Array<T>} arr The array to modify. - * @param {T} obj The object to insert. - * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2 - * is omitted or not found, obj is inserted at the end of the array. - * @template T - */ -goog.array.insertBefore = function(arr, obj, opt_obj2) { - var i; - if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) { - arr.push(obj); - } else { - goog.array.insertAt(arr, obj, i); - } -}; - - -/** - * Removes the first occurrence of a particular value from an array. - * @param {Array<T>|goog.array.ArrayLike} arr Array from which to remove - * value. - * @param {T} obj Object to remove. - * @return {boolean} True if an element was removed. - * @template T - */ -goog.array.remove = function(arr, obj) { - var i = goog.array.indexOf(arr, obj); - var rv; - if ((rv = i >= 0)) { - goog.array.removeAt(arr, i); - } - return rv; -}; - - -/** - * Removes from an array the element at index i - * @param {goog.array.ArrayLike} arr Array or array like object from which to - * remove value. - * @param {number} i The index to remove. - * @return {boolean} True if an element was removed. - */ -goog.array.removeAt = function(arr, i) { - goog.asserts.assert(arr.length != null); - - // use generic form of splice - // splice returns the removed items and if successful the length of that - // will be 1 - return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1; -}; - - -/** - * Removes the first value that satisfies the given condition. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call - * for every element. This function - * takes 3 arguments (the element, the index and the array) and should - * return a boolean. - * @param {S=} opt_obj An optional "this" context for the function. - * @return {boolean} True if an element was removed. - * @template T,S - */ -goog.array.removeIf = function(arr, f, opt_obj) { - var i = goog.array.findIndex(arr, f, opt_obj); - if (i >= 0) { - goog.array.removeAt(arr, i); - return true; - } - return false; -}; - - -/** - * Removes all values that satisfy the given condition. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array - * like object over which to iterate. - * @param {?function(this:S, T, number, ?) : boolean} f The function to call - * for every element. This function - * takes 3 arguments (the element, the index and the array) and should - * return a boolean. - * @param {S=} opt_obj An optional "this" context for the function. - * @return {number} The number of items removed - * @template T,S - */ -goog.array.removeAllIf = function(arr, f, opt_obj) { - var removedCount = 0; - goog.array.forEachRight(arr, function(val, index) { - if (f.call(opt_obj, val, index, arr)) { - if (goog.array.removeAt(arr, index)) { - removedCount++; - } - } - }); - return removedCount; -}; - - -/** - * Returns a new array that is the result of joining the arguments. If arrays - * are passed then their items are added, however, if non-arrays are passed they - * will be added to the return array as is. - * - * Note that ArrayLike objects will be added as is, rather than having their - * items added. - * - * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4] - * goog.array.concat(0, [1, 2]) -> [0, 1, 2] - * goog.array.concat([1, 2], null) -> [1, 2, null] - * - * There is bug in all current versions of IE (6, 7 and 8) where arrays created - * in an iframe become corrupted soon (not immediately) after the iframe is - * destroyed. This is common if loading data via goog.net.IframeIo, for example. - * This corruption only affects the concat method which will start throwing - * Catastrophic Errors (#-2147418113). - * - * See http://endoflow.com/scratch/corrupted-arrays.html for a test case. - * - * Internally goog.array should use this, so that all methods will continue to - * work on these broken array objects. - * - * @param {...*} var_args Items to concatenate. Arrays will have each item - * added, while primitives and objects will be added as is. - * @return {!Array<?>} The new resultant array. - */ -goog.array.concat = function(var_args) { - return goog.array.ARRAY_PROTOTYPE_.concat.apply( - goog.array.ARRAY_PROTOTYPE_, arguments); -}; - - -/** - * Returns a new array that contains the contents of all the arrays passed. - * @param {...!Array<T>} var_args - * @return {!Array<T>} - * @template T - */ -goog.array.join = function(var_args) { - return goog.array.ARRAY_PROTOTYPE_.concat.apply( - goog.array.ARRAY_PROTOTYPE_, arguments); -}; - - -/** - * Converts an object to an array. - * @param {Array<T>|goog.array.ArrayLike} object The object to convert to an - * array. - * @return {!Array<T>} The object converted into an array. If object has a - * length property, every property indexed with a non-negative number - * less than length will be included in the result. If object does not - * have a length property, an empty array will be returned. - * @template T - */ -goog.array.toArray = function(object) { - var length = object.length; - - // If length is not a number the following it false. This case is kept for - // backwards compatibility since there are callers that pass objects that are - // not array like. - if (length > 0) { - var rv = new Array(length); - for (var i = 0; i < length; i++) { - rv[i] = object[i]; - } - return rv; - } - return []; -}; - - -/** - * Does a shallow copy of an array. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array-like object to - * clone. - * @return {!Array<T>} Clone of the input array. - * @template T - */ -goog.array.clone = goog.array.toArray; - - -/** - * Extends an array with another array, element, or "array like" object. - * This function operates 'in-place', it does not create a new Array. - * - * Example: - * var a = []; - * goog.array.extend(a, [0, 1]); - * a; // [0, 1] - * goog.array.extend(a, 2); - * a; // [0, 1, 2] - * - * @param {Array<VALUE>} arr1 The array to modify. - * @param {...(Array<VALUE>|VALUE)} var_args The elements or arrays of elements - * to add to arr1. - * @template VALUE - */ -goog.array.extend = function(arr1, var_args) { - for (var i = 1; i < arguments.length; i++) { - var arr2 = arguments[i]; - if (goog.isArrayLike(arr2)) { - var len1 = arr1.length || 0; - var len2 = arr2.length || 0; - arr1.length = len1 + len2; - for (var j = 0; j < len2; j++) { - arr1[len1 + j] = arr2[j]; - } - } else { - arr1.push(arr2); - } - } -}; - - -/** - * Adds or removes elements from an array. This is a generic version of Array - * splice. This means that it might work on other objects similar to arrays, - * such as the arguments object. - * - * @param {Array<T>|goog.array.ArrayLike} arr The array to modify. - * @param {number|undefined} index The index at which to start changing the - * array. If not defined, treated as 0. - * @param {number} howMany How many elements to remove (0 means no removal. A - * value below 0 is treated as zero and so is any other non number. Numbers - * are floored). - * @param {...T} var_args Optional, additional elements to insert into the - * array. - * @return {!Array<T>} the removed elements. - * @template T - */ -goog.array.splice = function(arr, index, howMany, var_args) { - goog.asserts.assert(arr.length != null); - - return goog.array.ARRAY_PROTOTYPE_.splice.apply( - arr, goog.array.slice(arguments, 1)); -}; - - -/** - * Returns a new array from a segment of an array. This is a generic version of - * Array slice. This means that it might work on other objects similar to - * arrays, such as the arguments object. - * - * @param {Array<T>|goog.array.ArrayLike} arr The array from - * which to copy a segment. - * @param {number} start The index of the first element to copy. - * @param {number=} opt_end The index after the last element to copy. - * @return {!Array<T>} A new array containing the specified segment of the - * original array. - * @template T - */ -goog.array.slice = function(arr, start, opt_end) { - goog.asserts.assert(arr.length != null); - - // passing 1 arg to slice is not the same as passing 2 where the second is - // null or undefined (in that case the second argument is treated as 0). - // we could use slice on the arguments object and then use apply instead of - // testing the length - if (arguments.length <= 2) { - return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start); - } else { - return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end); - } -}; - - -/** - * Removes all duplicates from an array (retaining only the first - * occurrence of each array element). This function modifies the - * array in place and doesn't change the order of the non-duplicate items. - * - * For objects, duplicates are identified as having the same unique ID as - * defined by {@link goog.getUid}. - * - * Alternatively you can specify a custom hash function that returns a unique - * value for each item in the array it should consider unique. - * - * Runtime: N, - * Worstcase space: 2N (no dupes) - * - * @param {Array<T>|goog.array.ArrayLike} arr The array from which to remove - * duplicates. - * @param {Array=} opt_rv An optional array in which to return the results, - * instead of performing the removal inplace. If specified, the original - * array will remain unchanged. - * @param {function(T):string=} opt_hashFn An optional function to use to - * apply to every item in the array. This function should return a unique - * value for each item in the array it should consider unique. - * @template T - */ -goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) { - var returnArray = opt_rv || arr; - var defaultHashFn = function(item) { - // Prefix each type with a single character representing the type to - // prevent conflicting keys (e.g. true and 'true'). - return goog.isObject(current) ? 'o' + goog.getUid(current) : - (typeof current).charAt(0) + current; - }; - var hashFn = opt_hashFn || defaultHashFn; - - var seen = {}, cursorInsert = 0, cursorRead = 0; - while (cursorRead < arr.length) { - var current = arr[cursorRead++]; - var key = hashFn(current); - if (!Object.prototype.hasOwnProperty.call(seen, key)) { - seen[key] = true; - returnArray[cursorInsert++] = current; - } - } - returnArray.length = cursorInsert; -}; - - -/** - * Searches the specified array for the specified target using the binary - * search algorithm. If no opt_compareFn is specified, elements are compared - * using <code>goog.array.defaultCompare</code>, which compares the elements - * using the built in < and > operators. This will produce the expected - * behavior for homogeneous arrays of String(s) and Number(s). The array - * specified <b>must</b> be sorted in ascending order (as defined by the - * comparison function). If the array is not sorted, results are undefined. - * If the array contains multiple instances of the specified target value, any - * of these instances may be found. - * - * Runtime: O(log n) - * - * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched. - * @param {TARGET} target The sought value. - * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison - * function by which the array is ordered. Should take 2 arguments to - * compare, and return a negative number, zero, or a positive number - * depending on whether the first argument is less than, equal to, or - * greater than the second. - * @return {number} Lowest index of the target value if found, otherwise - * (-(insertion point) - 1). The insertion point is where the value should - * be inserted into arr to preserve the sorted property. Return value >= 0 - * iff target is found. - * @template TARGET, VALUE - */ -goog.array.binarySearch = function(arr, target, opt_compareFn) { - return goog.array.binarySearch_(arr, - opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */, - target); -}; - - -/** - * Selects an index in the specified array using the binary search algorithm. - * The evaluator receives an element and determines whether the desired index - * is before, at, or after it. The evaluator must be consistent (formally, - * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign) - * must be monotonically non-increasing). - * - * Runtime: O(log n) - * - * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched. - * @param {function(this:THIS, VALUE, number, ?): number} evaluator - * Evaluator function that receives 3 arguments (the element, the index and - * the array). Should return a negative number, zero, or a positive number - * depending on whether the desired index is before, at, or after the - * element passed to it. - * @param {THIS=} opt_obj The object to be used as the value of 'this' - * within evaluator. - * @return {number} Index of the leftmost element matched by the evaluator, if - * such exists; otherwise (-(insertion point) - 1). The insertion point is - * the index of the first element for which the evaluator returns negative, - * or arr.length if no such element exists. The return value is non-negative - * iff a match is found. - * @template THIS, VALUE - */ -goog.array.binarySelect = function(arr, evaluator, opt_obj) { - return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */, - undefined /* opt_target */, opt_obj); -}; - - -/** - * Implementation of a binary search algorithm which knows how to use both - * comparison functions and evaluators. If an evaluator is provided, will call - * the evaluator with the given optional data object, conforming to the - * interface defined in binarySelect. Otherwise, if a comparison function is - * provided, will call the comparison function against the given data object. - * - * This implementation purposefully does not use goog.bind or goog.partial for - * performance reasons. - * - * Runtime: O(log n) - * - * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched. - * @param {function(TARGET, VALUE): number| - * function(this:THIS, VALUE, number, ?): number} compareFn Either an - * evaluator or a comparison function, as defined by binarySearch - * and binarySelect above. - * @param {boolean} isEvaluator Whether the function is an evaluator or a - * comparison function. - * @param {TARGET=} opt_target If the function is a comparison function, then - * this is the target to binary search for. - * @param {THIS=} opt_selfObj If the function is an evaluator, this is an - * optional this object for the evaluator. - * @return {number} Lowest index of the target value if found, otherwise - * (-(insertion point) - 1). The insertion point is where the value should - * be inserted into arr to preserve the sorted property. Return value >= 0 - * iff target is found. - * @template THIS, VALUE, TARGET - * @private - */ -goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target, - opt_selfObj) { - var left = 0; // inclusive - var right = arr.length; // exclusive - var found; - while (left < right) { - var middle = (left + right) >> 1; - var compareResult; - if (isEvaluator) { - compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr); - } else { - compareResult = compareFn(opt_target, arr[middle]); - } - if (compareResult > 0) { - left = middle + 1; - } else { - right = middle; - // We are looking for the lowest index so we can't return immediately. - found = !compareResult; - } - } - // left is the index if found, or the insertion point otherwise. - // ~left is a shorthand for -left - 1. - return found ? left : ~left; -}; - - -/** - * Sorts the specified array into ascending order. If no opt_compareFn is - * specified, elements are compared using - * <code>goog.array.defaultCompare</code>, which compares the elements using - * the built in < and > operators. This will produce the expected behavior - * for homogeneous arrays of String(s) and Number(s), unlike the native sort, - * but will give unpredictable results for heterogenous lists of strings and - * numbers with different numbers of digits. - * - * This sort is not guaranteed to be stable. - * - * Runtime: Same as <code>Array.prototype.sort</code> - * - * @param {Array<T>} arr The array to be sorted. - * @param {?function(T,T):number=} opt_compareFn Optional comparison - * function by which the - * array is to be ordered. Should take 2 arguments to compare, and return a - * negative number, zero, or a positive number depending on whether the - * first argument is less than, equal to, or greater than the second. - * @template T - */ -goog.array.sort = function(arr, opt_compareFn) { - // TODO(arv): Update type annotation since null is not accepted. - arr.sort(opt_compareFn || goog.array.defaultCompare); -}; - - -/** - * Sorts the specified array into ascending order in a stable way. If no - * opt_compareFn is specified, elements are compared using - * <code>goog.array.defaultCompare</code>, which compares the elements using - * the built in < and > operators. This will produce the expected behavior - * for homogeneous arrays of String(s) and Number(s). - * - * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional - * O(n) overhead of copying the array twice. - * - * @param {Array<T>} arr The array to be sorted. - * @param {?function(T, T): number=} opt_compareFn Optional comparison function - * by which the array is to be ordered. Should take 2 arguments to compare, - * and return a negative number, zero, or a positive number depending on - * whether the first argument is less than, equal to, or greater than the - * second. - * @template T - */ -goog.array.stableSort = function(arr, opt_compareFn) { - for (var i = 0; i < arr.length; i++) { - arr[i] = {index: i, value: arr[i]}; - } - var valueCompareFn = opt_compareFn || goog.array.defaultCompare; - function stableCompareFn(obj1, obj2) { - return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index; - }; - goog.array.sort(arr, stableCompareFn); - for (var i = 0; i < arr.length; i++) { - arr[i] = arr[i].value; - } -}; - - -/** - * Sort the specified array into ascending order based on item keys - * returned by the specified key function. - * If no opt_compareFn is specified, the keys are compared in ascending order - * using <code>goog.array.defaultCompare</code>. - * - * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code> - * and f(n) is runtime of the key function. - * - * @param {Array<T>} arr The array to be sorted. - * @param {function(T): K} keyFn Function taking array element and returning - * a key used for sorting this element. - * @param {?function(K, K): number=} opt_compareFn Optional comparison function - * by which the keys are to be ordered. Should take 2 arguments to compare, - * and return a negative number, zero, or a positive number depending on - * whether the first argument is less than, equal to, or greater than the - * second. - * @template T - * @template K - */ -goog.array.sortByKey = function(arr, keyFn, opt_compareFn) { - var keyCompareFn = opt_compareFn || goog.array.defaultCompare; - goog.array.sort(arr, function(a, b) { - return keyCompareFn(keyFn(a), keyFn(b)); - }); -}; - - -/** - * Sorts an array of objects by the specified object key and compare - * function. If no compare function is provided, the key values are - * compared in ascending order using <code>goog.array.defaultCompare</code>. - * This won't work for keys that get renamed by the compiler. So use - * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}. - * @param {Array<Object>} arr An array of objects to sort. - * @param {string} key The object key to sort by. - * @param {Function=} opt_compareFn The function to use to compare key - * values. - */ -goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) { - goog.array.sortByKey(arr, - function(obj) { return obj[key]; }, - opt_compareFn); -}; - - -/** - * Tells if the array is sorted. - * @param {!Array<T>} arr The array. - * @param {?function(T,T):number=} opt_compareFn Function to compare the - * array elements. - * Should take 2 arguments to compare, and return a negative number, zero, - * or a positive number depending on whether the first argument is less - * than, equal to, or greater than the second. - * @param {boolean=} opt_strict If true no equal elements are allowed. - * @return {boolean} Whether the array is sorted. - * @template T - */ -goog.array.isSorted = function(arr, opt_compareFn, opt_strict) { - var compare = opt_compareFn || goog.array.defaultCompare; - for (var i = 1; i < arr.length; i++) { - var compareResult = compare(arr[i - 1], arr[i]); - if (compareResult > 0 || compareResult == 0 && opt_strict) { - return false; - } - } - return true; -}; - - -/** - * Compares two arrays for equality. Two arrays are considered equal if they - * have the same length and their corresponding elements are equal according to - * the comparison function. - * - * @param {goog.array.ArrayLike} arr1 The first array to compare. - * @param {goog.array.ArrayLike} arr2 The second array to compare. - * @param {Function=} opt_equalsFn Optional comparison function. - * Should take 2 arguments to compare, and return true if the arguments - * are equal. Defaults to {@link goog.array.defaultCompareEquality} which - * compares the elements using the built-in '===' operator. - * @return {boolean} Whether the two arrays are equal. - */ -goog.array.equals = function(arr1, arr2, opt_equalsFn) { - if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) || - arr1.length != arr2.length) { - return false; - } - var l = arr1.length; - var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality; - for (var i = 0; i < l; i++) { - if (!equalsFn(arr1[i], arr2[i])) { - return false; - } - } - return true; -}; - - -/** - * 3-way array compare function. - * @param {!Array<VALUE>|!goog.array.ArrayLike} arr1 The first array to - * compare. - * @param {!Array<VALUE>|!goog.array.ArrayLike} arr2 The second array to - * compare. - * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison - * function by which the array is to be ordered. Should take 2 arguments to - * compare, and return a negative number, zero, or a positive number - * depending on whether the first argument is less than, equal to, or - * greater than the second. - * @return {number} Negative number, zero, or a positive number depending on - * whether the first argument is less than, equal to, or greater than the - * second. - * @template VALUE - */ -goog.array.compare3 = function(arr1, arr2, opt_compareFn) { - var compare = opt_compareFn || goog.array.defaultCompare; - var l = Math.min(arr1.length, arr2.length); - for (var i = 0; i < l; i++) { - var result = compare(arr1[i], arr2[i]); - if (result != 0) { - return result; - } - } - return goog.array.defaultCompare(arr1.length, arr2.length); -}; - - -/** - * Compares its two arguments for order, using the built in < and > - * operators. - * @param {VALUE} a The first object to be compared. - * @param {VALUE} b The second object to be compared. - * @return {number} A negative number, zero, or a positive number as the first - * argument is less than, equal to, or greater than the second, - * respectively. - * @template VALUE - */ -goog.array.defaultCompare = function(a, b) { - return a > b ? 1 : a < b ? -1 : 0; -}; - - -/** - * Compares its two arguments for inverse order, using the built in < and > - * operators. - * @param {VALUE} a The first object to be compared. - * @param {VALUE} b The second object to be compared. - * @return {number} A negative number, zero, or a positive number as the first - * argument is greater than, equal to, or less than the second, - * respectively. - * @template VALUE - */ -goog.array.inverseDefaultCompare = function(a, b) { - return -goog.array.defaultCompare(a, b); -}; - - -/** - * Compares its two arguments for equality, using the built in === operator. - * @param {*} a The first object to compare. - * @param {*} b The second object to compare. - * @return {boolean} True if the two arguments are equal, false otherwise. - */ -goog.array.defaultCompareEquality = function(a, b) { - return a === b; -}; - - -/** - * Inserts a value into a sorted array. The array is not modified if the - * value is already present. - * @param {Array<VALUE>|goog.array.ArrayLike} array The array to modify. - * @param {VALUE} value The object to insert. - * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison - * function by which the array is ordered. Should take 2 arguments to - * compare, and return a negative number, zero, or a positive number - * depending on whether the first argument is less than, equal to, or - * greater than the second. - * @return {boolean} True if an element was inserted. - * @template VALUE - */ -goog.array.binaryInsert = function(array, value, opt_compareFn) { - var index = goog.array.binarySearch(array, value, opt_compareFn); - if (index < 0) { - goog.array.insertAt(array, value, -(index + 1)); - return true; - } - return false; -}; - - -/** - * Removes a value from a sorted array. - * @param {!Array<VALUE>|!goog.array.ArrayLike} array The array to modify. - * @param {VALUE} value The object to remove. - * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison - * function by which the array is ordered. Should take 2 arguments to - * compare, and return a negative number, zero, or a positive number - * depending on whether the first argument is less than, equal to, or - * greater than the second. - * @return {boolean} True if an element was removed. - * @template VALUE - */ -goog.array.binaryRemove = function(array, value, opt_compareFn) { - var index = goog.array.binarySearch(array, value, opt_compareFn); - return (index >= 0) ? goog.array.removeAt(array, index) : false; -}; - - -/** - * Splits an array into disjoint buckets according to a splitting function. - * @param {Array<T>} array The array. - * @param {function(this:S, T,number,Array<T>):?} sorter Function to call for - * every element. This takes 3 arguments (the element, the index and the - * array) and must return a valid object key (a string, number, etc), or - * undefined, if that object should not be placed in a bucket. - * @param {S=} opt_obj The object to be used as the value of 'this' within - * sorter. - * @return {!Object} An object, with keys being all of the unique return values - * of sorter, and values being arrays containing the items for - * which the splitter returned that key. - * @template T,S - */ -goog.array.bucket = function(array, sorter, opt_obj) { - var buckets = {}; - - for (var i = 0; i < array.length; i++) { - var value = array[i]; - var key = sorter.call(opt_obj, value, i, array); - if (goog.isDef(key)) { - // Push the value to the right bucket, creating it if necessary. - var bucket = buckets[key] || (buckets[key] = []); - bucket.push(value); - } - } - - return buckets; -}; - - -/** - * Creates a new object built from the provided array and the key-generation - * function. - * @param {Array<T>|goog.array.ArrayLike} arr Array or array like object over - * which to iterate whose elements will be the values in the new object. - * @param {?function(this:S, T, number, ?) : string} keyFunc The function to - * call for every element. This function takes 3 arguments (the element, the - * index and the array) and should return a string that will be used as the - * key for the element in the new object. If the function returns the same - * key for more than one element, the value for that key is - * implementation-defined. - * @param {S=} opt_obj The object to be used as the value of 'this' - * within keyFunc. - * @return {!Object<T>} The new object. - * @template T,S - */ -goog.array.toObject = function(arr, keyFunc, opt_obj) { - var ret = {}; - goog.array.forEach(arr, function(element, index) { - ret[keyFunc.call(opt_obj, element, index, arr)] = element; - }); - return ret; -}; - - -/** - * Creates a range of numbers in an arithmetic progression. - * - * Range takes 1, 2, or 3 arguments: - * <pre> - * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4] - * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4] - * range(-2, -5, -1) produces [-2, -3, -4] - * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5. - * </pre> - * - * @param {number} startOrEnd The starting value of the range if an end argument - * is provided. Otherwise, the start value is 0, and this is the end value. - * @param {number=} opt_end The optional end value of the range. - * @param {number=} opt_step The step size between range values. Defaults to 1 - * if opt_step is undefined or 0. - * @return {!Array<number>} An array of numbers for the requested range. May be - * an empty array if adding the step would not converge toward the end - * value. - */ -goog.array.range = function(startOrEnd, opt_end, opt_step) { - var array = []; - var start = 0; - var end = startOrEnd; - var step = opt_step || 1; - if (opt_end !== undefined) { - start = startOrEnd; - end = opt_end; - } - - if (step * (end - start) < 0) { - // Sign mismatch: start + step will never reach the end value. - return []; - } - - if (step > 0) { - for (var i = start; i < end; i += step) { - array.push(i); - } - } else { - for (var i = start; i > end; i += step) { - array.push(i); - } - } - return array; -}; - - -/** - * Returns an array consisting of the given value repeated N times. - * - * @param {VALUE} value The value to repeat. - * @param {number} n The repeat count. - * @return {!Array<VALUE>} An array with the repeated value. - * @template VALUE - */ -goog.array.repeat = function(value, n) { - var array = []; - for (var i = 0; i < n; i++) { - array[i] = value; - } - return array; -}; - - -/** - * Returns an array consisting of every argument with all arrays - * expanded in-place recursively. - * - * @param {...*} var_args The values to flatten. - * @return {!Array<?>} An array containing the flattened values. - */ -goog.array.flatten = function(var_args) { - var CHUNK_SIZE = 8192; - - var result = []; - for (var i = 0; i < arguments.length; i++) { - var element = arguments[i]; - if (goog.isArray(element)) { - for (var c = 0; c < element.length; c += CHUNK_SIZE) { - var chunk = goog.array.slice(element, c, c + CHUNK_SIZE); - var recurseResult = goog.array.flatten.apply(null, chunk); - for (var r = 0; r < recurseResult.length; r++) { - result.push(recurseResult[r]); - } - } - } else { - result.push(element); - } - } - return result; -}; - - -/** - * Rotates an array in-place. After calling this method, the element at - * index i will be the element previously at index (i - n) % - * array.length, for all values of i between 0 and array.length - 1, - * inclusive. - * - * For example, suppose list comprises [t, a, n, k, s]. After invoking - * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k]. - * - * @param {!Array<T>} array The array to rotate. - * @param {number} n The amount to rotate. - * @return {!Array<T>} The array. - * @template T - */ -goog.array.rotate = function(array, n) { - goog.asserts.assert(array.length != null); - - if (array.length) { - n %= array.length; - if (n > 0) { - goog.array.ARRAY_PROTOTYPE_.unshift.apply(array, array.splice(-n, n)); - } else if (n < 0) { - goog.array.ARRAY_PROTOTYPE_.push.apply(array, array.splice(0, -n)); - } - } - return array; -}; - - -/** - * Moves one item of an array to a new position keeping the order of the rest - * of the items. Example use case: keeping a list of JavaScript objects - * synchronized with the corresponding list of DOM elements after one of the - * elements has been dragged to a new position. - * @param {!(Array|Arguments|{length:number})} arr The array to modify. - * @param {number} fromIndex Index of the item to move between 0 and - * {@code arr.length - 1}. - * @param {number} toIndex Target index between 0 and {@code arr.length - 1}. - */ -goog.array.moveItem = function(arr, fromIndex, toIndex) { - goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length); - goog.asserts.assert(toIndex >= 0 && toIndex < arr.length); - // Remove 1 item at fromIndex. - var removedItems = goog.array.ARRAY_PROTOTYPE_.splice.call(arr, fromIndex, 1); - // Insert the removed item at toIndex. - goog.array.ARRAY_PROTOTYPE_.splice.call(arr, toIndex, 0, removedItems[0]); - // We don't use goog.array.insertAt and goog.array.removeAt, because they're - // significantly slower than splice. -}; - - -/** - * Creates a new array for which the element at position i is an array of the - * ith element of the provided arrays. The returned array will only be as long - * as the shortest array provided; additional values are ignored. For example, - * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]]. - * - * This is similar to the zip() function in Python. See {@link - * http://docs.python.org/library/functions.html#zip} - * - * @param {...!goog.array.ArrayLike} var_args Arrays to be combined. - * @return {!Array<!Array<?>>} A new array of arrays created from - * provided arrays. - */ -goog.array.zip = function(var_args) { - if (!arguments.length) { - return []; - } - var result = []; - for (var i = 0; true; i++) { - var value = []; - for (var j = 0; j < arguments.length; j++) { - var arr = arguments[j]; - // If i is larger than the array length, this is the shortest array. - if (i >= arr.length) { - return result; - } - value.push(arr[i]); - } - result.push(value); - } -}; - - -/** - * Shuffles the values in the specified array using the Fisher-Yates in-place - * shuffle (also known as the Knuth Shuffle). By default, calls Math.random() - * and so resets the state of that random number generator. Similarly, may reset - * the state of the any other specified random number generator. - * - * Runtime: O(n) - * - * @param {!Array<?>} arr The array to be shuffled. - * @param {function():number=} opt_randFn Optional random function to use for - * shuffling. - * Takes no arguments, and returns a random number on the interval [0, 1). - * Defaults to Math.random() using JavaScript's built-in Math library. - */ -goog.array.shuffle = function(arr, opt_randFn) { - var randFn = opt_randFn || Math.random; - - for (var i = arr.length - 1; i > 0; i--) { - // Choose a random array index in [0, i] (inclusive with i). - var j = Math.floor(randFn() * (i + 1)); - - var tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } -}; - - -/** - * Returns a new array of elements from arr, based on the indexes of elements - * provided by index_arr. For example, the result of index copying - * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c']. - * - * @param {!Array<T>} arr The array to get a indexed copy from. - * @param {!Array<number>} index_arr An array of indexes to get from arr. - * @return {!Array<T>} A new array of elements from arr in index_arr order. - * @template T - */ -goog.array.copyByIndex = function(arr, index_arr) { - var result = []; - goog.array.forEach(index_arr, function(index) { - result.push(arr[index]); - }); - return result; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/asserts/asserts.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/asserts/asserts.js deleted file mode 100644 index 95513d1..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/asserts/asserts.js +++ /dev/null @@ -1,365 +0,0 @@ -// 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. - * - * @author agrieve@google.com (Andrew Grieve) - */ - -goog.provide('goog.asserts'); -goog.provide('goog.asserts.AssertionError'); - -goog.require('goog.debug.Error'); -goog.require('goog.dom.NodeType'); -goog.require('goog.string'); - - -/** - * @define {boolean} Whether to strip out asserts or to leave them in. - */ -goog.define('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} - * @final - */ -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'; - - -/** - * The default error handler. - * @param {!goog.asserts.AssertionError} e The exception to be handled. - */ -goog.asserts.DEFAULT_ERROR_HANDLER = function(e) { throw e; }; - - -/** - * The handler responsible for throwing or logging assertion errors. - * @private {function(!goog.asserts.AssertionError)} - */ -goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER; - - -/** - * 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). - var e = new goog.asserts.AssertionError('' + message, args || []); - goog.asserts.errorHandler_(e); -}; - - -/** - * Sets a custom error handler that can be used to customize the behavior of - * assertion failures, for example by turning all assertion failures into log - * messages. - * @param {function(!goog.asserts.AssertionError)} errorHandler - */ -goog.asserts.setErrorHandler = function(errorHandler) { - if (goog.asserts.ENABLE_ASSERTS) { - goog.asserts.errorHandler_ = errorHandler; - } -}; - - -/** - * Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is - * true. - * @template T - * @param {T} 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 {T} 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) { - goog.asserts.errorHandler_(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 a DOM Element 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 {!Element} The value, likely to be a DOM Element when asserts are - * enabled. - * @throws {goog.asserts.AssertionError} When the value is not an Element. - */ -goog.asserts.assertElement = function(value, opt_message, var_args) { - if (goog.asserts.ENABLE_ASSERTS && (!goog.isObject(value) || - value.nodeType != goog.dom.NodeType.ELEMENT)) { - goog.asserts.doAssertFailure_('Expected Element but got %s: %s.', - [goog.typeOf(value), value], opt_message, - Array.prototype.slice.call(arguments, 2)); - } - return /** @type {!Element} */ (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(new: T, ...)} 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 {T} - * @template T - */ -goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) { - if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) { - goog.asserts.doAssertFailure_('Expected instanceof %s but got %s.', - [goog.asserts.getType_(type), goog.asserts.getType_(value)], - opt_message, Array.prototype.slice.call(arguments, 3)); - } - return value; -}; - - -/** - * Checks that no enumerable keys are present in Object.prototype. Such keys - * would break most code that use {@code for (var ... in ...)} loops. - */ -goog.asserts.assertObjectPrototypeIsIntact = function() { - for (var key in Object.prototype) { - goog.asserts.fail(key + ' should not be enumerable in Object.prototype.'); - } -}; - - -/** - * Returns the type of a value. If a constructor is passed, and a suitable - * string cannot be found, 'unknown type name' will be returned. - * @param {*} value A constructor, object, or primitive. - * @return {string} The best display name for the value, or 'unknown type name'. - * @private - */ -goog.asserts.getType_ = function(value) { - if (value instanceof Function) { - return value.displayName || value.name || 'unknown type name'; - } else if (value instanceof Object) { - return value.constructor.displayName || value.constructor.name || - Object.prototype.toString.call(value); - } else { - return value === null ? 'null' : typeof value; - } -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/freelist.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/freelist.js deleted file mode 100644 index d0331f2..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/freelist.js +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2015 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 Simple freelist. - * - * An anterative to goog.structs.SimplePool, it imposes the requirement that the - * objects in the list contain a "next" property that can be used to maintain - * the pool. - */ - -goog.provide('goog.async.FreeList'); - - -/** - * @template ITEM - */ -goog.async.FreeList = goog.defineClass(null, { - /** - * @param {function():ITEM} create - * @param {function(ITEM):void} reset - * @param {number} limit - */ - constructor: function(create, reset, limit) { - /** @const {number} */ - this.limit_ = limit; - /** @const {function()} */ - this.create_ = create; - /** @const {function(ITEM):void} */ - this.reset_ = reset; - - /** @type {number} */ - this.occupants_ = 0; - /** @type {ITEM} */ - this.head_ = null; - }, - - /** - * @return {ITEM} - */ - get: function() { - var item; - if (this.occupants_ > 0) { - this.occupants_--; - item = this.head_; - this.head_ = item.next; - item.next = null; - } else { - item = this.create_(); - } - return item; - }, - - /** - * @param {ITEM} item An item available for possible future reuse. - */ - put: function(item) { - this.reset_(item); - if (this.occupants_ < this.limit_) { - this.occupants_++; - item.next = this.head_; - this.head_ = item; - } - }, - - /** - * Visible for testing. - * @package - * @return {number} - */ - occupants: function() { - return this.occupants_; - } -}); - - - diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/nexttick.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/nexttick.js deleted file mode 100644 index c5715bc..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/nexttick.js +++ /dev/null @@ -1,240 +0,0 @@ -// 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 Provides a function to schedule running a function as soon - * as possible after the current JS execution stops and yields to the event - * loop. - * - */ - -goog.provide('goog.async.nextTick'); -goog.provide('goog.async.throwException'); - -goog.require('goog.debug.entryPointRegistry'); -goog.require('goog.functions'); -goog.require('goog.labs.userAgent.browser'); -goog.require('goog.labs.userAgent.engine'); - - -/** - * Throw an item without interrupting the current execution context. For - * example, if processing a group of items in a loop, sometimes it is useful - * to report an error while still allowing the rest of the batch to be - * processed. - * @param {*} exception - */ -goog.async.throwException = function(exception) { - // Each throw needs to be in its own context. - goog.global.setTimeout(function() { throw exception; }, 0); -}; - - -/** - * Fires the provided callbacks as soon as possible after the current JS - * execution context. setTimeout(…, 0) takes at least 4ms when called from - * within another setTimeout(…, 0) for legacy reasons. - * - * This will not schedule the callback as a microtask (i.e. a task that can - * preempt user input or networking callbacks). It is meant to emulate what - * setTimeout(_, 0) would do if it were not throttled. If you desire microtask - * behavior, use {@see goog.Promise} instead. - * - * @param {function(this:SCOPE)} callback Callback function to fire as soon as - * possible. - * @param {SCOPE=} opt_context Object in whose scope to call the listener. - * @param {boolean=} opt_useSetImmediate Avoid the IE workaround that - * ensures correctness at the cost of speed. See comments for details. - * @template SCOPE - */ -goog.async.nextTick = function(callback, opt_context, opt_useSetImmediate) { - var cb = callback; - if (opt_context) { - cb = goog.bind(callback, opt_context); - } - cb = goog.async.nextTick.wrapCallback_(cb); - // window.setImmediate was introduced and currently only supported by IE10+, - // but due to a bug in the implementation it is not guaranteed that - // setImmediate is faster than setTimeout nor that setImmediate N is before - // setImmediate N+1. That is why we do not use the native version if - // available. We do, however, call setImmediate if it is a normal function - // because that indicates that it has been replaced by goog.testing.MockClock - // which we do want to support. - // See - // http://connect.microsoft.com/IE/feedback/details/801823/setimmediate-and-messagechannel-are-broken-in-ie10 - // - // Note we do allow callers to also request setImmediate if they are willing - // to accept the possible tradeoffs of incorrectness in exchange for speed. - // The IE fallback of readystate change is much slower. - if (goog.isFunction(goog.global.setImmediate) && - // Opt in. - (opt_useSetImmediate || - // or it isn't a browser or the environment is weird - !goog.global.Window || !goog.global.Window.prototype || - // or something redefined setImmediate in which case we (YOLO) decide - // to use it (This is so that we use the mockClock setImmediate. sigh). - goog.global.Window.prototype.setImmediate != goog.global.setImmediate)) { - goog.global.setImmediate(cb); - return; - } - - // Look for and cache the custom fallback version of setImmediate. - if (!goog.async.nextTick.setImmediate_) { - goog.async.nextTick.setImmediate_ = - goog.async.nextTick.getSetImmediateEmulator_(); - } - goog.async.nextTick.setImmediate_(cb); -}; - - -/** - * Cache for the setImmediate implementation. - * @type {function(function())} - * @private - */ -goog.async.nextTick.setImmediate_; - - -/** - * Determines the best possible implementation to run a function as soon as - * the JS event loop is idle. - * @return {function(function())} The "setImmediate" implementation. - * @private - */ -goog.async.nextTick.getSetImmediateEmulator_ = function() { - // Create a private message channel and use it to postMessage empty messages - // to ourselves. - var Channel = goog.global['MessageChannel']; - // If MessageChannel is not available and we are in a browser, implement - // an iframe based polyfill in browsers that have postMessage and - // document.addEventListener. The latter excludes IE8 because it has a - // synchronous postMessage implementation. - if (typeof Channel === 'undefined' && typeof window !== 'undefined' && - window.postMessage && window.addEventListener && - // Presto (The old pre-blink Opera engine) has problems with iframes - // and contentWindow. - !goog.labs.userAgent.engine.isPresto()) { - /** @constructor */ - Channel = function() { - // Make an empty, invisible iframe. - var iframe = document.createElement('iframe'); - iframe.style.display = 'none'; - iframe.src = ''; - document.documentElement.appendChild(iframe); - var win = iframe.contentWindow; - var doc = win.document; - doc.open(); - doc.write(''); - doc.close(); - // Do not post anything sensitive over this channel, as the workaround for - // pages with file: origin could allow that information to be modified or - // intercepted. - var message = 'callImmediate' + Math.random(); - // The same origin policy rejects attempts to postMessage from file: urls - // unless the origin is '*'. - // TODO(b/16335441): Use '*' origin for data: and other similar protocols. - var origin = win.location.protocol == 'file:' ? - '*' : win.location.protocol + '//' + win.location.host; - var onmessage = goog.bind(function(e) { - // Validate origin and message to make sure that this message was - // intended for us. If the origin is set to '*' (see above) only the - // message needs to match since, for example, '*' != 'file://'. Allowing - // the wildcard is ok, as we are not concerned with security here. - if ((origin != '*' && e.origin != origin) || e.data != message) { - return; - } - this['port1'].onmessage(); - }, this); - win.addEventListener('message', onmessage, false); - this['port1'] = {}; - this['port2'] = { - postMessage: function() { - win.postMessage(message, origin); - } - }; - }; - } - if (typeof Channel !== 'undefined' && - (!goog.labs.userAgent.browser.isIE())) { - // Exclude all of IE due to - // http://codeforhire.com/2013/09/21/setimmediate-and-messagechannel-broken-on-internet-explorer-10/ - // which allows starving postMessage with a busy setTimeout loop. - // This currently affects IE10 and IE11 which would otherwise be able - // to use the postMessage based fallbacks. - var channel = new Channel(); - // Use a fifo linked list to call callbacks in the right order. - var head = {}; - var tail = head; - channel['port1'].onmessage = function() { - if (goog.isDef(head.next)) { - head = head.next; - var cb = head.cb; - head.cb = null; - cb(); - } - }; - return function(cb) { - tail.next = { - cb: cb - }; - tail = tail.next; - channel['port2'].postMessage(0); - }; - } - // Implementation for IE6+: Script elements fire an asynchronous - // onreadystatechange event when inserted into the DOM. - if (typeof document !== 'undefined' && 'onreadystatechange' in - document.createElement('script')) { - return function(cb) { - var script = document.createElement('script'); - script.onreadystatechange = function() { - // Clean up and call the callback. - script.onreadystatechange = null; - script.parentNode.removeChild(script); - script = null; - cb(); - cb = null; - }; - document.documentElement.appendChild(script); - }; - } - // Fall back to setTimeout with 0. In browsers this creates a delay of 5ms - // or more. - return function(cb) { - goog.global.setTimeout(cb, 0); - }; -}; - - -/** - * Helper function that is overrided to protect callbacks with entry point - * monitor if the application monitors entry points. - * @param {function()} callback Callback function to fire as soon as possible. - * @return {function()} The wrapped callback. - * @private - */ -goog.async.nextTick.wrapCallback_ = goog.functions.identity; - - -// Register the callback function as an entry point, so that it can be -// monitored for exception handling, etc. This has to be done in this file -// since it requires special code to handle all browsers. -goog.debug.entryPointRegistry.register( - /** - * @param {function(!Function): !Function} transformer The transforming - * function. - */ - function(transformer) { - goog.async.nextTick.wrapCallback_ = transformer; - }); diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/run.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/run.js deleted file mode 100644 index b621477..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/run.js +++ /dev/null @@ -1,130 +0,0 @@ -// 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. - -goog.provide('goog.async.run'); - -goog.require('goog.async.WorkQueue'); -goog.require('goog.async.nextTick'); -goog.require('goog.async.throwException'); -goog.require('goog.testing.watchers'); - - -/** - * Fires the provided callback just before the current callstack unwinds, or as - * soon as possible after the current JS execution context. - * @param {function(this:THIS)} callback - * @param {THIS=} opt_context Object to use as the "this value" when calling - * the provided function. - * @template THIS - */ -goog.async.run = function(callback, opt_context) { - if (!goog.async.run.schedule_) { - goog.async.run.initializeRunner_(); - } - if (!goog.async.run.workQueueScheduled_) { - // Nothing is currently scheduled, schedule it now. - goog.async.run.schedule_(); - goog.async.run.workQueueScheduled_ = true; - } - - goog.async.run.workQueue_.add(callback, opt_context); -}; - - -/** - * Initializes the function to use to process the work queue. - * @private - */ -goog.async.run.initializeRunner_ = function() { - // If native Promises are available in the browser, just schedule the callback - // on a fulfilled promise, which is specified to be async, but as fast as - // possible. - if (goog.global.Promise && goog.global.Promise.resolve) { - var promise = goog.global.Promise.resolve(); - goog.async.run.schedule_ = function() { - promise.then(goog.async.run.processWorkQueue); - }; - } else { - goog.async.run.schedule_ = function() { - goog.async.nextTick(goog.async.run.processWorkQueue); - }; - } -}; - - -/** - * Forces goog.async.run to use nextTick instead of Promise. - * - * This should only be done in unit tests. It's useful because MockClock - * replaces nextTick, but not the browser Promise implementation, so it allows - * Promise-based code to be tested with MockClock. - */ -goog.async.run.forceNextTick = function() { - goog.async.run.schedule_ = function() { - goog.async.nextTick(goog.async.run.processWorkQueue); - }; -}; - - -/** - * The function used to schedule work asynchronousely. - * @private {function()} - */ -goog.async.run.schedule_; - - -/** @private {boolean} */ -goog.async.run.workQueueScheduled_ = false; - - -/** @private {!goog.async.WorkQueue} */ -goog.async.run.workQueue_ = new goog.async.WorkQueue(); - - -if (goog.DEBUG) { - /** - * Reset the work queue. - * @private - */ - goog.async.run.resetQueue_ = function() { - goog.async.run.workQueueScheduled_ = false; - goog.async.run.workQueue_ = new goog.async.WorkQueue(); - }; - - // If there is a clock implemenation in use for testing - // and it is reset, reset the queue. - goog.testing.watchers.watchClockReset(goog.async.run.resetQueue_); -} - - -/** - * Run any pending goog.async.run work items. This function is not intended - * for general use, but for use by entry point handlers to run items ahead of - * goog.async.nextTick. - */ -goog.async.run.processWorkQueue = function() { - // NOTE: additional work queue items may be added while processing. - var item = null; - while (item = goog.async.run.workQueue_.remove()) { - try { - item.fn.call(item.scope); - } catch (e) { - goog.async.throwException(e); - } - goog.async.run.workQueue_.returnUnused(item); - } - - // There are no more work items, allow processing to be scheduled again. - goog.async.run.workQueueScheduled_ = false; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/workqueue.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/workqueue.js deleted file mode 100644 index 2d86c89..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/async/workqueue.js +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2015 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. - -goog.provide('goog.async.WorkItem'); -goog.provide('goog.async.WorkQueue'); - -goog.require('goog.asserts'); -goog.require('goog.async.FreeList'); - - -// TODO(johnlenz): generalize the WorkQueue if this is used by more -// than goog.async.run. - - - -/** - * A low GC workqueue. The key elements of this design: - * - avoids the need for goog.bind or equivalent by carrying scope - * - avoids the need for array reallocation by using a linked list - * - minimizes work entry objects allocation by recycling objects - * @constructor - * @final - * @struct - */ -goog.async.WorkQueue = function() { - this.workHead_ = null; - this.workTail_ = null; -}; - - -/** @define {number} The maximum number of entries to keep for recycling. */ -goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100); - - -/** @const @private {goog.async.FreeList<goog.async.WorkItem>} */ -goog.async.WorkQueue.freelist_ = new goog.async.FreeList( - function() {return new goog.async.WorkItem(); }, - function(item) {item.reset()}, - goog.async.WorkQueue.DEFAULT_MAX_UNUSED); - - -/** - * @param {function()} fn - * @param {Object|null|undefined} scope - */ -goog.async.WorkQueue.prototype.add = function(fn, scope) { - var item = this.getUnusedItem_(); - item.set(fn, scope); - - if (this.workTail_) { - this.workTail_.next = item; - this.workTail_ = item; - } else { - goog.asserts.assert(!this.workHead_); - this.workHead_ = item; - this.workTail_ = item; - } -}; - - -/** - * @return {goog.async.WorkItem} - */ -goog.async.WorkQueue.prototype.remove = function() { - var item = null; - - if (this.workHead_) { - item = this.workHead_; - this.workHead_ = this.workHead_.next; - if (!this.workHead_) { - this.workTail_ = null; - } - item.next = null; - } - return item; -}; - - -/** - * @param {goog.async.WorkItem} item - */ -goog.async.WorkQueue.prototype.returnUnused = function(item) { - goog.async.WorkQueue.freelist_.put(item); -}; - - -/** - * @return {goog.async.WorkItem} - * @private - */ -goog.async.WorkQueue.prototype.getUnusedItem_ = function() { - return goog.async.WorkQueue.freelist_.get(); -}; - - - -/** - * @constructor - * @final - * @struct - */ -goog.async.WorkItem = function() { - /** @type {?function()} */ - this.fn = null; - /** @type {Object|null|undefined} */ - this.scope = null; - /** @type {?goog.async.WorkItem} */ - this.next = null; -}; - - -/** - * @param {function()} fn - * @param {Object|null|undefined} scope - */ -goog.async.WorkItem.prototype.set = function(fn, scope) { - this.fn = fn; - this.scope = scope; - this.next = null; -}; - - -/** Reset the work item so they don't prevent GC before reuse */ -goog.async.WorkItem.prototype.reset = function() { - this.fn = null; - this.scope = null; - this.next = null; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/base.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/base.js deleted file mode 100644 index 7723717..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/base.js +++ /dev/null @@ -1,2496 +0,0 @@ -// 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 Bootstrap for the Google JS Library (Closure). - * - * In uncompiled mode base.js will write out Closure's deps file, unless the - * global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to - * include their own deps file(s) from different locations. - * - * @author arv@google.com (Erik Arvidsson) - * - * @provideGoog - */ - - -/** - * @define {boolean} Overridden to true by the compiler when --closure_pass - * or --mark_as_compiled is specified. - */ -var COMPILED = false; - - -/** - * Base namespace for the Closure library. Checks to see goog is already - * defined in the current scope before assigning to prevent clobbering if - * base.js is loaded more than once. - * - * @const - */ -var goog = goog || {}; - - -/** - * Reference to the global context. In most cases this will be 'window'. - */ -goog.global = this; - - -/** - * A hook for overriding the define values in uncompiled mode. - * - * In uncompiled mode, {@code CLOSURE_UNCOMPILED_DEFINES} may be defined before - * loading base.js. If a key is defined in {@code CLOSURE_UNCOMPILED_DEFINES}, - * {@code goog.define} will use the value instead of the default value. This - * allows flags to be overwritten without compilation (this is normally - * accomplished with the compiler's "define" flag). - * - * Example: - * <pre> - * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false}; - * </pre> - * - * @type {Object<string, (string|number|boolean)>|undefined} - */ -goog.global.CLOSURE_UNCOMPILED_DEFINES; - - -/** - * A hook for overriding the define values in uncompiled or compiled mode, - * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In - * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence. - * - * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or - * string literals or the compiler will emit an error. - * - * While any @define value may be set, only those set with goog.define will be - * effective for uncompiled code. - * - * Example: - * <pre> - * var CLOSURE_DEFINES = {'goog.DEBUG': false} ; - * </pre> - * - * @type {Object<string, (string|number|boolean)>|undefined} - */ -goog.global.CLOSURE_DEFINES; - - -/** - * Returns true if the specified value is not undefined. - * WARNING: Do not use this to test if an object has a property. Use the in - * operator instead. - * - * @param {?} val Variable to test. - * @return {boolean} Whether variable is defined. - */ -goog.isDef = function(val) { - // void 0 always evaluates to undefined and hence we do not need to depend on - // the definition of the global variable named 'undefined'. - return val !== void 0; -}; - - -/** - * Builds an object structure for the provided namespace path, ensuring that - * names that already exist are not overwritten. For example: - * "a.b.c" -> a = {};a.b={};a.b.c={}; - * Used by goog.provide and goog.exportSymbol. - * @param {string} name name of the object that this file defines. - * @param {*=} opt_object the object to expose at the end of the path. - * @param {Object=} opt_objectToExportTo The object to add the path to; default - * is |goog.global|. - * @private - */ -goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) { - var parts = name.split('.'); - var cur = opt_objectToExportTo || goog.global; - - // Internet Explorer exhibits strange behavior when throwing errors from - // methods externed in this manner. See the testExportSymbolExceptions in - // base_test.html for an example. - if (!(parts[0] in cur) && cur.execScript) { - cur.execScript('var ' + parts[0]); - } - - // Certain browsers cannot parse code in the form for((a in b); c;); - // This pattern is produced by the JSCompiler when it collapses the - // statement above into the conditional loop below. To prevent this from - // happening, use a for-loop and reserve the init logic as below. - - // Parentheses added to eliminate strict JS warning in Firefox. - for (var part; parts.length && (part = parts.shift());) { - if (!parts.length && goog.isDef(opt_object)) { - // last part and we have an object; use it - cur[part] = opt_object; - } else if (cur[part]) { - cur = cur[part]; - } else { - cur = cur[part] = {}; - } - } -}; - - -/** - * Defines a named value. In uncompiled mode, the value is retrieved from - * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and - * has the property specified, and otherwise used the defined defaultValue. - * When compiled the default can be overridden using the compiler - * options or the value set in the CLOSURE_DEFINES object. - * - * @param {string} name The distinguished name to provide. - * @param {string|number|boolean} defaultValue - */ -goog.define = function(name, defaultValue) { - var value = defaultValue; - if (!COMPILED) { - if (goog.global.CLOSURE_UNCOMPILED_DEFINES && - Object.prototype.hasOwnProperty.call( - goog.global.CLOSURE_UNCOMPILED_DEFINES, name)) { - value = goog.global.CLOSURE_UNCOMPILED_DEFINES[name]; - } else if (goog.global.CLOSURE_DEFINES && - Object.prototype.hasOwnProperty.call( - goog.global.CLOSURE_DEFINES, name)) { - value = goog.global.CLOSURE_DEFINES[name]; - } - } - goog.exportPath_(name, value); -}; - - -/** - * @define {boolean} DEBUG is provided as a convenience so that debugging code - * that should not be included in a production js_binary can be easily stripped - * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most - * toString() methods should be declared inside an "if (goog.DEBUG)" conditional - * because they are generally used for debugging purposes and it is difficult - * for the JSCompiler to statically determine whether they are used. - */ -goog.define('goog.DEBUG', true); - - -/** - * @define {string} LOCALE defines the locale being used for compilation. It is - * used to select locale specific data to be compiled in js binary. BUILD rule - * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler - * option. - * - * Take into account that the locale code format is important. You should use - * the canonical Unicode format with hyphen as a delimiter. Language must be - * lowercase, Language Script - Capitalized, Region - UPPERCASE. - * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN. - * - * See more info about locale codes here: - * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers - * - * For language codes you should use values defined by ISO 693-1. See it here - * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from - * this rule: the Hebrew language. For legacy reasons the old code (iw) should - * be used instead of the new code (he), see http://wiki/Main/IIISynonyms. - */ -goog.define('goog.LOCALE', 'en'); // default to en - - -/** - * @define {boolean} Whether this code is running on trusted sites. - * - * On untrusted sites, several native functions can be defined or overridden by - * external libraries like Prototype, Datejs, and JQuery and setting this flag - * to false forces closure to use its own implementations when possible. - * - * If your JavaScript can be loaded by a third party site and you are wary about - * relying on non-standard implementations, specify - * "--define goog.TRUSTED_SITE=false" to the JSCompiler. - */ -goog.define('goog.TRUSTED_SITE', true); - - -/** - * @define {boolean} Whether a project is expected to be running in strict mode. - * - * This define can be used to trigger alternate implementations compatible with - * running in EcmaScript Strict mode or warn about unavailable functionality. - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode - * - */ -goog.define('goog.STRICT_MODE_COMPATIBLE', false); - - -/** - * @define {boolean} Whether code that calls {@link goog.setTestOnly} should - * be disallowed in the compilation unit. - */ -goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG); - - -/** - * Defines a namespace in Closure. - * - * A namespace may only be defined once in a codebase. It may be defined using - * goog.provide() or goog.module(). - * - * The presence of one or more goog.provide() calls in a file indicates - * that the file defines the given objects/namespaces. - * Provided symbols must not be null or undefined. - * - * In addition, goog.provide() creates the object stubs for a namespace - * (for example, goog.provide("goog.foo.bar") will create the object - * goog.foo.bar if it does not already exist). - * - * Build tools also scan for provide/require/module statements - * to discern dependencies, build dependency files (see deps.js), etc. - * - * @see goog.require - * @see goog.module - * @param {string} name Namespace provided by this file in the form - * "goog.package.part". - */ -goog.provide = function(name) { - if (!COMPILED) { - // Ensure that the same namespace isn't provided twice. - // A goog.module/goog.provide maps a goog.require to a specific file - if (goog.isProvided_(name)) { - throw Error('Namespace "' + name + '" already declared.'); - } - } - - goog.constructNamespace_(name); -}; - - -/** - * @param {string} name Namespace provided by this file in the form - * "goog.package.part". - * @param {Object=} opt_obj The object to embed in the namespace. - * @private - */ -goog.constructNamespace_ = function(name, opt_obj) { - if (!COMPILED) { - delete goog.implicitNamespaces_[name]; - - var namespace = name; - while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) { - if (goog.getObjectByName(namespace)) { - break; - } - goog.implicitNamespaces_[namespace] = true; - } - } - - goog.exportPath_(name, opt_obj); -}; - - -/** - * Module identifier validation regexp. - * Note: This is a conservative check, it is very possible to be more lenient, - * the primary exclusion here is "/" and "\" and a leading ".", these - * restrictions are intended to leave the door open for using goog.require - * with relative file paths rather than module identifiers. - * @private - */ -goog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/; - - -/** - * Defines a module in Closure. - * - * Marks that this file must be loaded as a module and claims the namespace. - * - * A namespace may only be defined once in a codebase. It may be defined using - * goog.provide() or goog.module(). - * - * goog.module() has three requirements: - * - goog.module may not be used in the same file as goog.provide. - * - goog.module must be the first statement in the file. - * - only one goog.module is allowed per file. - * - * When a goog.module annotated file is loaded, it is enclosed in - * a strict function closure. This means that: - * - any variables declared in a goog.module file are private to the file - * (not global), though the compiler is expected to inline the module. - * - The code must obey all the rules of "strict" JavaScript. - * - the file will be marked as "use strict" - * - * NOTE: unlike goog.provide, goog.module does not declare any symbols by - * itself. If declared symbols are desired, use - * goog.module.declareLegacyNamespace(). - * - * - * See the public goog.module proposal: http://goo.gl/Va1hin - * - * @param {string} name Namespace provided by this file in the form - * "goog.package.part", is expected but not required. - */ -goog.module = function(name) { - if (!goog.isString(name) || - !name || - name.search(goog.VALID_MODULE_RE_) == -1) { - throw Error('Invalid module identifier'); - } - if (!goog.isInModuleLoader_()) { - throw Error('Module ' + name + ' has been loaded incorrectly.'); - } - if (goog.moduleLoaderState_.moduleName) { - throw Error('goog.module may only be called once per module.'); - } - - // Store the module name for the loader. - goog.moduleLoaderState_.moduleName = name; - if (!COMPILED) { - // Ensure that the same namespace isn't provided twice. - // A goog.module/goog.provide maps a goog.require to a specific file - if (goog.isProvided_(name)) { - throw Error('Namespace "' + name + '" already declared.'); - } - delete goog.implicitNamespaces_[name]; - } -}; - - -/** - * @param {string} name The module identifier. - * @return {?} The module exports for an already loaded module or null. - * - * Note: This is not an alternative to goog.require, it does not - * indicate a hard dependency, instead it is used to indicate - * an optional dependency or to access the exports of a module - * that has already been loaded. - * @suppress {missingProvide} - */ -goog.module.get = function(name) { - return goog.module.getInternal_(name); -}; - - -/** - * @param {string} name The module identifier. - * @return {?} The module exports for an already loaded module or null. - * @private - */ -goog.module.getInternal_ = function(name) { - if (!COMPILED) { - if (goog.isProvided_(name)) { - // goog.require only return a value with-in goog.module files. - return name in goog.loadedModules_ ? - goog.loadedModules_[name] : - goog.getObjectByName(name); - } else { - return null; - } - } -}; - - -/** - * @private {?{ - * moduleName: (string|undefined), - * declareTestMethods: boolean - * }} - */ -goog.moduleLoaderState_ = null; - - -/** - * @private - * @return {boolean} Whether a goog.module is currently being initialized. - */ -goog.isInModuleLoader_ = function() { - return goog.moduleLoaderState_ != null; -}; - - -/** - * Indicate that a module's exports that are known test methods should - * be copied to the global object. This makes the test methods visible to - * test runners that inspect the global object. - * - * TODO(johnlenz): Make the test framework aware of goog.module so - * that this isn't necessary. Alternately combine this with goog.setTestOnly - * to minimize boiler plate. - * @suppress {missingProvide} - */ -goog.module.declareTestMethods = function() { - if (!goog.isInModuleLoader_()) { - throw new Error('goog.module.declareTestMethods must be called from ' + - 'within a goog.module'); - } - goog.moduleLoaderState_.declareTestMethods = true; -}; - - -/** - * Provide the module's exports as a globally accessible object under the - * module's declared name. This is intended to ease migration to goog.module - * for files that have existing usages. - * @suppress {missingProvide} - */ -goog.module.declareLegacyNamespace = function() { - if (!COMPILED && !goog.isInModuleLoader_()) { - throw new Error('goog.module.declareLegacyNamespace must be called from ' + - 'within a goog.module'); - } - if (!COMPILED && !goog.moduleLoaderState_.moduleName) { - throw Error('goog.module must be called prior to ' + - 'goog.module.declareLegacyNamespace.'); - } - goog.moduleLoaderState_.declareLegacyNamespace = true; -}; - - -/** - * Marks that the current file should only be used for testing, and never for - * live code in production. - * - * In the case of unit tests, the message may optionally be an exact namespace - * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra - * provide (if not explicitly defined in the code). - * - * @param {string=} opt_message Optional message to add to the error that's - * raised when used in production code. - */ -goog.setTestOnly = function(opt_message) { - if (goog.DISALLOW_TEST_ONLY_CODE) { - opt_message = opt_message || ''; - throw Error('Importing test-only code into non-debug environment' + - (opt_message ? ': ' + opt_message : '.')); - } -}; - - -/** - * Forward declares a symbol. This is an indication to the compiler that the - * symbol may be used in the source yet is not required and may not be provided - * in compilation. - * - * The most common usage of forward declaration is code that takes a type as a - * function parameter but does not need to require it. By forward declaring - * instead of requiring, no hard dependency is made, and (if not required - * elsewhere) the namespace may never be required and thus, not be pulled - * into the JavaScript binary. If it is required elsewhere, it will be type - * checked as normal. - * - * - * @param {string} name The namespace to forward declare in the form of - * "goog.package.part". - */ -goog.forwardDeclare = function(name) {}; - - -if (!COMPILED) { - - /** - * Check if the given name has been goog.provided. This will return false for - * names that are available only as implicit namespaces. - * @param {string} name name of the object to look for. - * @return {boolean} Whether the name has been provided. - * @private - */ - goog.isProvided_ = function(name) { - return (name in goog.loadedModules_) || - (!goog.implicitNamespaces_[name] && - goog.isDefAndNotNull(goog.getObjectByName(name))); - }; - - /** - * Namespaces implicitly defined by goog.provide. For example, - * goog.provide('goog.events.Event') implicitly declares that 'goog' and - * 'goog.events' must be namespaces. - * - * @type {!Object<string, (boolean|undefined)>} - * @private - */ - goog.implicitNamespaces_ = {'goog.module': true}; - - // NOTE: We add goog.module as an implicit namespace as goog.module is defined - // here and because the existing module package has not been moved yet out of - // the goog.module namespace. This satisifies both the debug loader and - // ahead-of-time dependency management. -} - - -/** - * Returns an object based on its fully qualified external name. The object - * is not found if null or undefined. If you are using a compilation pass that - * renames property names beware that using this function will not find renamed - * properties. - * - * @param {string} name The fully qualified name. - * @param {Object=} opt_obj The object within which to look; default is - * |goog.global|. - * @return {?} The value (object or primitive) or, if not found, null. - */ -goog.getObjectByName = function(name, opt_obj) { - var parts = name.split('.'); - var cur = opt_obj || goog.global; - for (var part; part = parts.shift(); ) { - if (goog.isDefAndNotNull(cur[part])) { - cur = cur[part]; - } else { - return null; - } - } - return cur; -}; - - -/** - * Globalizes a whole namespace, such as goog or goog.lang. - * - * @param {!Object} obj The namespace to globalize. - * @param {Object=} opt_global The object to add the properties to. - * @deprecated Properties may be explicitly exported to the global scope, but - * this should no longer be done in bulk. - */ -goog.globalize = function(obj, opt_global) { - var global = opt_global || goog.global; - for (var x in obj) { - global[x] = obj[x]; - } -}; - - -/** - * Adds a dependency from a file to the files it requires. - * @param {string} relPath The path to the js file. - * @param {!Array<string>} provides An array of strings with - * the names of the objects this file provides. - * @param {!Array<string>} requires An array of strings with - * the names of the objects this file requires. - * @param {boolean=} opt_isModule Whether this dependency must be loaded as - * a module as declared by goog.module. - */ -goog.addDependency = function(relPath, provides, requires, opt_isModule) { - if (goog.DEPENDENCIES_ENABLED) { - var provide, require; - var path = relPath.replace(/\\/g, '/'); - var deps = goog.dependencies_; - for (var i = 0; provide = provides[i]; i++) { - deps.nameToPath[provide] = path; - deps.pathIsModule[path] = !!opt_isModule; - } - for (var j = 0; require = requires[j]; j++) { - if (!(path in deps.requires)) { - deps.requires[path] = {}; - } - deps.requires[path][require] = true; - } - } -}; - - - - -// NOTE(nnaze): The debug DOM loader was included in base.js as an original way -// to do "debug-mode" development. The dependency system can sometimes be -// confusing, as can the debug DOM loader's asynchronous nature. -// -// With the DOM loader, a call to goog.require() is not blocking -- the script -// will not load until some point after the current script. If a namespace is -// needed at runtime, it needs to be defined in a previous script, or loaded via -// require() with its registered dependencies. -// User-defined namespaces may need their own deps file. See http://go/js_deps, -// http://go/genjsdeps, or, externally, DepsWriter. -// https://developers.google.com/closure/library/docs/depswriter -// -// Because of legacy clients, the DOM loader can't be easily removed from -// base.js. Work is being done to make it disableable or replaceable for -// different environments (DOM-less JavaScript interpreters like Rhino or V8, -// for example). See bootstrap/ for more information. - - -/** - * @define {boolean} Whether to enable the debug loader. - * - * If enabled, a call to goog.require() will attempt to load the namespace by - * appending a script tag to the DOM (if the namespace has been registered). - * - * If disabled, goog.require() will simply assert that the namespace has been - * provided (and depend on the fact that some outside tool correctly ordered - * the script). - */ -goog.define('goog.ENABLE_DEBUG_LOADER', true); - - -/** - * @param {string} msg - * @private - */ -goog.logToConsole_ = function(msg) { - if (goog.global.console) { - goog.global.console['error'](msg); - } -}; - - -/** - * Implements a system for the dynamic resolution of dependencies that works in - * parallel with the BUILD system. Note that all calls to goog.require will be - * stripped by the JSCompiler when the --closure_pass option is used. - * @see goog.provide - * @param {string} name Namespace to include (as was given in goog.provide()) in - * the form "goog.package.part". - * @return {?} If called within a goog.module file, the associated namespace or - * module otherwise null. - */ -goog.require = function(name) { - - // If the object already exists we do not need do do anything. - if (!COMPILED) { - if (goog.ENABLE_DEBUG_LOADER && goog.IS_OLD_IE_) { - goog.maybeProcessDeferredDep_(name); - } - - if (goog.isProvided_(name)) { - if (goog.isInModuleLoader_()) { - return goog.module.getInternal_(name); - } else { - return null; - } - } - - if (goog.ENABLE_DEBUG_LOADER) { - var path = goog.getPathFromDeps_(name); - if (path) { - goog.included_[path] = true; - goog.writeScripts_(); - return null; - } - } - - var errorMessage = 'goog.require could not find: ' + name; - goog.logToConsole_(errorMessage); - - throw Error(errorMessage); - } -}; - - -/** - * Path for included scripts. - * @type {string} - */ -goog.basePath = ''; - - -/** - * A hook for overriding the base path. - * @type {string|undefined} - */ -goog.global.CLOSURE_BASE_PATH; - - -/** - * Whether to write out Closure's deps file. By default, the deps are written. - * @type {boolean|undefined} - */ -goog.global.CLOSURE_NO_DEPS; - - -/** - * A function to import a single script. This is meant to be overridden when - * Closure is being run in non-HTML contexts, such as web workers. It's defined - * in the global scope so that it can be set before base.js is loaded, which - * allows deps.js to be imported properly. - * - * The function is passed the script source, which is a relative URI. It should - * return true if the script was imported, false otherwise. - * @type {(function(string): boolean)|undefined} - */ -goog.global.CLOSURE_IMPORT_SCRIPT; - - -/** - * Null function used for default values of callbacks, etc. - * @return {void} Nothing. - */ -goog.nullFunction = function() {}; - - -/** - * The identity function. Returns its first argument. - * - * @param {*=} opt_returnValue The single value that will be returned. - * @param {...*} var_args Optional trailing arguments. These are ignored. - * @return {?} The first argument. We can't know the type -- just pass it along - * without type. - * @deprecated Use goog.functions.identity instead. - */ -goog.identityFunction = function(opt_returnValue, var_args) { - return opt_returnValue; -}; - - -/** - * When defining a class Foo with an abstract method bar(), you can do: - * Foo.prototype.bar = goog.abstractMethod - * - * Now if a subclass of Foo fails to override bar(), an error will be thrown - * when bar() is invoked. - * - * Note: This does not take the name of the function to override as an argument - * because that would make it more difficult to obfuscate our JavaScript code. - * - * @type {!Function} - * @throws {Error} when invoked to indicate the method should be overridden. - */ -goog.abstractMethod = function() { - throw Error('unimplemented abstract method'); -}; - - -/** - * Adds a {@code getInstance} static method that always returns the same - * instance object. - * @param {!Function} ctor The constructor for the class to add the static - * method to. - */ -goog.addSingletonGetter = function(ctor) { - ctor.getInstance = function() { - if (ctor.instance_) { - return ctor.instance_; - } - if (goog.DEBUG) { - // NOTE: JSCompiler can't optimize away Array#push. - goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor; - } - return ctor.instance_ = new ctor; - }; -}; - - -/** - * All singleton classes that have been instantiated, for testing. Don't read - * it directly, use the {@code goog.testing.singleton} module. The compiler - * removes this variable if unused. - * @type {!Array<!Function>} - * @private - */ -goog.instantiatedSingletons_ = []; - - -/** - * @define {boolean} Whether to load goog.modules using {@code eval} when using - * the debug loader. This provides a better debugging experience as the - * source is unmodified and can be edited using Chrome Workspaces or similar. - * However in some environments the use of {@code eval} is banned - * so we provide an alternative. - */ -goog.define('goog.LOAD_MODULE_USING_EVAL', true); - - -/** - * @define {boolean} Whether the exports of goog.modules should be sealed when - * possible. - */ -goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG); - - -/** - * The registry of initialized modules: - * the module identifier to module exports map. - * @private @const {!Object<string, ?>} - */ -goog.loadedModules_ = {}; - - -/** - * True if goog.dependencies_ is available. - * @const {boolean} - */ -goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER; - - -if (goog.DEPENDENCIES_ENABLED) { - /** - * Object used to keep track of urls that have already been added. This record - * allows the prevention of circular dependencies. - * @private {!Object<string, boolean>} - */ - goog.included_ = {}; - - - /** - * This object is used to keep track of dependencies and other data that is - * used for loading scripts. - * @private - * @type {{ - * pathIsModule: !Object<string, boolean>, - * nameToPath: !Object<string, string>, - * requires: !Object<string, !Object<string, boolean>>, - * visited: !Object<string, boolean>, - * written: !Object<string, boolean>, - * deferred: !Object<string, string> - * }} - */ - goog.dependencies_ = { - pathIsModule: {}, // 1 to 1 - - nameToPath: {}, // 1 to 1 - - requires: {}, // 1 to many - - // Used when resolving dependencies to prevent us from visiting file twice. - visited: {}, - - written: {}, // Used to keep track of script files we have written. - - deferred: {} // Used to track deferred module evaluations in old IEs - }; - - - /** - * Tries to detect whether is in the context of an HTML document. - * @return {boolean} True if it looks like HTML document. - * @private - */ - goog.inHtmlDocument_ = function() { - var doc = goog.global.document; - return typeof doc != 'undefined' && - 'write' in doc; // XULDocument misses write. - }; - - - /** - * Tries to detect the base path of base.js script that bootstraps Closure. - * @private - */ - goog.findBasePath_ = function() { - if (goog.isDef(goog.global.CLOSURE_BASE_PATH)) { - goog.basePath = goog.global.CLOSURE_BASE_PATH; - return; - } else if (!goog.inHtmlDocument_()) { - return; - } - var doc = goog.global.document; - var scripts = doc.getElementsByTagName('script'); - // Search backwards since the current script is in almost all cases the one - // that has base.js. - for (var i = scripts.length - 1; i >= 0; --i) { - var script = /** @type {!HTMLScriptElement} */ (scripts[i]); - var src = script.src; - var qmark = src.lastIndexOf('?'); - var l = qmark == -1 ? src.length : qmark; - if (src.substr(l - 7, 7) == 'base.js') { - goog.basePath = src.substr(0, l - 7); - return; - } - } - }; - - - /** - * Imports a script if, and only if, that script hasn't already been imported. - * (Must be called at execution time) - * @param {string} src Script source. - * @param {string=} opt_sourceText The optionally source text to evaluate - * @private - */ - goog.importScript_ = function(src, opt_sourceText) { - var importScript = goog.global.CLOSURE_IMPORT_SCRIPT || - goog.writeScriptTag_; - if (importScript(src, opt_sourceText)) { - goog.dependencies_.written[src] = true; - } - }; - - - /** @const @private {boolean} */ - goog.IS_OLD_IE_ = !goog.global.atob && goog.global.document && - goog.global.document.all; - - - /** - * Given a URL initiate retrieval and execution of the module. - * @param {string} src Script source URL. - * @private - */ - goog.importModule_ = function(src) { - // In an attempt to keep browsers from timing out loading scripts using - // synchronous XHRs, put each load in its own script block. - var bootstrap = 'goog.retrieveAndExecModule_("' + src + '");'; - - if (goog.importScript_('', bootstrap)) { - goog.dependencies_.written[src] = true; - } - }; - - - /** @private {!Array<string>} */ - goog.queuedModules_ = []; - - - /** - * Return an appropriate module text. Suitable to insert into - * a script tag (that is unescaped). - * @param {string} srcUrl - * @param {string} scriptText - * @return {string} - * @private - */ - goog.wrapModule_ = function(srcUrl, scriptText) { - if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) { - return '' + - 'goog.loadModule(function(exports) {' + - '"use strict";' + - scriptText + - '\n' + // terminate any trailing single line comment. - ';return exports' + - '});' + - '\n//# sourceURL=' + srcUrl + '\n'; - } else { - return '' + - 'goog.loadModule(' + - goog.global.JSON.stringify( - scriptText + '\n//# sourceURL=' + srcUrl + '\n') + - ');'; - } - }; - - // On IE9 and earlier, it is necessary to handle - // deferred module loads. In later browsers, the - // code to be evaluated is simply inserted as a script - // block in the correct order. To eval deferred - // code at the right time, we piggy back on goog.require to call - // goog.maybeProcessDeferredDep_. - // - // The goog.requires are used both to bootstrap - // the loading process (when no deps are available) and - // declare that they should be available. - // - // Here we eval the sources, if all the deps are available - // either already eval'd or goog.require'd. This will - // be the case when all the dependencies have already - // been loaded, and the dependent module is loaded. - // - // But this alone isn't sufficient because it is also - // necessary to handle the case where there is no root - // that is not deferred. For that there we register for an event - // and trigger goog.loadQueuedModules_ handle any remaining deferred - // evaluations. - - /** - * Handle any remaining deferred goog.module evals. - * @private - */ - goog.loadQueuedModules_ = function() { - var count = goog.queuedModules_.length; - if (count > 0) { - var queue = goog.queuedModules_; - goog.queuedModules_ = []; - for (var i = 0; i < count; i++) { - var path = queue[i]; - goog.maybeProcessDeferredPath_(path); - } - } - }; - - - /** - * Eval the named module if its dependencies are - * available. - * @param {string} name The module to load. - * @private - */ - goog.maybeProcessDeferredDep_ = function(name) { - if (goog.isDeferredModule_(name) && - goog.allDepsAreAvailable_(name)) { - var path = goog.getPathFromDeps_(name); - goog.maybeProcessDeferredPath_(goog.basePath + path); - } - }; - - /** - * @param {string} name The module to check. - * @return {boolean} Whether the name represents a - * module whose evaluation has been deferred. - * @private - */ - goog.isDeferredModule_ = function(name) { - var path = goog.getPathFromDeps_(name); - if (path && goog.dependencies_.pathIsModule[path]) { - var abspath = goog.basePath + path; - return (abspath) in goog.dependencies_.deferred; - } - return false; - }; - - /** - * @param {string} name The module to check. - * @return {boolean} Whether the name represents a - * module whose declared dependencies have all been loaded - * (eval'd or a deferred module load) - * @private - */ - goog.allDepsAreAvailable_ = function(name) { - var path = goog.getPathFromDeps_(name); - if (path && (path in goog.dependencies_.requires)) { - for (var requireName in goog.dependencies_.requires[path]) { - if (!goog.isProvided_(requireName) && - !goog.isDeferredModule_(requireName)) { - return false; - } - } - } - return true; - }; - - - /** - * @param {string} abspath - * @private - */ - goog.maybeProcessDeferredPath_ = function(abspath) { - if (abspath in goog.dependencies_.deferred) { - var src = goog.dependencies_.deferred[abspath]; - delete goog.dependencies_.deferred[abspath]; - goog.globalEval(src); - } - }; - - - /** - * @param {function(?):?|string} moduleDef The module definition. - */ - goog.loadModule = function(moduleDef) { - // NOTE: we allow function definitions to be either in the from - // of a string to eval (which keeps the original source intact) or - // in a eval forbidden environment (CSP) we allow a function definition - // which in its body must call {@code goog.module}, and return the exports - // of the module. - var previousState = goog.moduleLoaderState_; - try { - goog.moduleLoaderState_ = { - moduleName: undefined, declareTestMethods: false}; - var exports; - if (goog.isFunction(moduleDef)) { - exports = moduleDef.call(goog.global, {}); - } else if (goog.isString(moduleDef)) { - exports = goog.loadModuleFromSource_.call(goog.global, moduleDef); - } else { - throw Error('Invalid module definition'); - } - - var moduleName = goog.moduleLoaderState_.moduleName; - if (!goog.isString(moduleName) || !moduleName) { - throw Error('Invalid module name \"' + moduleName + '\"'); - } - - // Don't seal legacy namespaces as they may be uses as a parent of - // another namespace - if (goog.moduleLoaderState_.declareLegacyNamespace) { - goog.constructNamespace_(moduleName, exports); - } else if (goog.SEAL_MODULE_EXPORTS && Object.seal) { - Object.seal(exports); - } - - goog.loadedModules_[moduleName] = exports; - if (goog.moduleLoaderState_.declareTestMethods) { - for (var entry in exports) { - if (entry.indexOf('test', 0) === 0 || - entry == 'tearDown' || - entry == 'setUp' || - entry == 'setUpPage' || - entry == 'tearDownPage') { - goog.global[entry] = exports[entry]; - } - } - } - } finally { - goog.moduleLoaderState_ = previousState; - } - }; - - - /** - * @param {string} source - * @return {!Object} - * @private - */ - goog.loadModuleFromSource_ = function(source) { - // NOTE: we avoid declaring parameters or local variables here to avoid - // masking globals or leaking values into the module definition. - 'use strict'; - var exports = {}; - eval(arguments[0]); - return exports; - }; - - - /** - * The default implementation of the import function. Writes a script tag to - * import the script. - * - * @param {string} src The script url. - * @param {string=} opt_sourceText The optionally source text to evaluate - * @return {boolean} True if the script was imported, false otherwise. - * @private - */ - goog.writeScriptTag_ = function(src, opt_sourceText) { - if (goog.inHtmlDocument_()) { - var doc = goog.global.document; - - // If the user tries to require a new symbol after document load, - // something has gone terribly wrong. Doing a document.write would - // wipe out the page. - if (doc.readyState == 'complete') { - // Certain test frameworks load base.js multiple times, which tries - // to write deps.js each time. If that happens, just fail silently. - // These frameworks wipe the page between each load of base.js, so this - // is OK. - var isDeps = /\bdeps.js$/.test(src); - if (isDeps) { - return false; - } else { - throw Error('Cannot write "' + src + '" after document load'); - } - } - - var isOldIE = goog.IS_OLD_IE_; - - if (opt_sourceText === undefined) { - if (!isOldIE) { - doc.write( - '<script type="text/javascript" src="' + - src + '"></' + 'script>'); - } else { - var state = " onreadystatechange='goog.onScriptLoad_(this, " + - ++goog.lastNonModuleScriptIndex_ + ")' "; - doc.write( - '<script type="text/javascript" src="' + - src + '"' + state + '></' + 'script>'); - } - } else { - doc.write( - '<script type="text/javascript">' + - opt_sourceText + - '</' + 'script>'); - } - return true; - } else { - return false; - } - }; - - - /** @private {number} */ - goog.lastNonModuleScriptIndex_ = 0; - - - /** - * A readystatechange handler for legacy IE - * @param {!HTMLScriptElement} script - * @param {number} scriptIndex - * @return {boolean} - * @private - */ - goog.onScriptLoad_ = function(script, scriptIndex) { - // for now load the modules when we reach the last script, - // later allow more inter-mingling. - if (script.readyState == 'complete' && - goog.lastNonModuleScriptIndex_ == scriptIndex) { - goog.loadQueuedModules_(); - } - return true; - }; - - /** - * Resolves dependencies based on the dependencies added using addDependency - * and calls importScript_ in the correct order. - * @private - */ - goog.writeScripts_ = function() { - /** @type {!Array<string>} The scripts we need to write this time. */ - var scripts = []; - var seenScript = {}; - var deps = goog.dependencies_; - - /** @param {string} path */ - function visitNode(path) { - if (path in deps.written) { - return; - } - - // We have already visited this one. We can get here if we have cyclic - // dependencies. - if (path in deps.visited) { - if (!(path in seenScript)) { - seenScript[path] = true; - scripts.push(path); - } - return; - } - - deps.visited[path] = true; - - if (path in deps.requires) { - for (var requireName in deps.requires[path]) { - // If the required name is defined, we assume that it was already - // bootstrapped by other means. - if (!goog.isProvided_(requireName)) { - if (requireName in deps.nameToPath) { - visitNode(deps.nameToPath[requireName]); - } else { - throw Error('Undefined nameToPath for ' + requireName); - } - } - } - } - - if (!(path in seenScript)) { - seenScript[path] = true; - scripts.push(path); - } - } - - for (var path in goog.included_) { - if (!deps.written[path]) { - visitNode(path); - } - } - - // record that we are going to load all these scripts. - for (var i = 0; i < scripts.length; i++) { - var path = scripts[i]; - goog.dependencies_.written[path] = true; - } - - // If a module is loaded synchronously then we need to - // clear the current inModuleLoader value, and restore it when we are - // done loading the current "requires". - var moduleState = goog.moduleLoaderState_; - goog.moduleLoaderState_ = null; - - var loadingModule = false; - for (var i = 0; i < scripts.length; i++) { - var path = scripts[i]; - if (path) { - if (!deps.pathIsModule[path]) { - goog.importScript_(goog.basePath + path); - } else { - loadingModule = true; - goog.importModule_(goog.basePath + path); - } - } else { - goog.moduleLoaderState_ = moduleState; - throw Error('Undefined script input'); - } - } - - // restore the current "module loading state" - goog.moduleLoaderState_ = moduleState; - }; - - - /** - * Looks at the dependency rules and tries to determine the script file that - * fulfills a particular rule. - * @param {string} rule In the form goog.namespace.Class or project.script. - * @return {?string} Url corresponding to the rule, or null. - * @private - */ - goog.getPathFromDeps_ = function(rule) { - if (rule in goog.dependencies_.nameToPath) { - return goog.dependencies_.nameToPath[rule]; - } else { - return null; - } - }; - - goog.findBasePath_(); - - // Allow projects to manage the deps files themselves. - if (!goog.global.CLOSURE_NO_DEPS) { - goog.importScript_(goog.basePath + 'deps.js'); - } -} - - -/** - * Normalize a file path by removing redundant ".." and extraneous "." file - * path components. - * @param {string} path - * @return {string} - * @private - */ -goog.normalizePath_ = function(path) { - var components = path.split('/'); - var i = 0; - while (i < components.length) { - if (components[i] == '.') { - components.splice(i, 1); - } else if (i && components[i] == '..' && - components[i - 1] && components[i - 1] != '..') { - components.splice(--i, 2); - } else { - i++; - } - } - return components.join('/'); -}; - - -/** - * Retrieve and execute a module. - * @param {string} src Script source URL. - * @private - */ -goog.retrieveAndExecModule_ = function(src) { - if (!COMPILED) { - // The full but non-canonicalized URL for later use. - var originalPath = src; - // Canonicalize the path, removing any /./ or /../ since Chrome's debugging - // console doesn't auto-canonicalize XHR loads as it does <script> srcs. - src = goog.normalizePath_(src); - - var importScript = goog.global.CLOSURE_IMPORT_SCRIPT || - goog.writeScriptTag_; - - var scriptText = null; - - var xhr = new goog.global['XMLHttpRequest'](); - - /** @this {Object} */ - xhr.onload = function() { - scriptText = this.responseText; - }; - xhr.open('get', src, false); - xhr.send(); - - scriptText = xhr.responseText; - - if (scriptText != null) { - var execModuleScript = goog.wrapModule_(src, scriptText); - var isOldIE = goog.IS_OLD_IE_; - if (isOldIE) { - goog.dependencies_.deferred[originalPath] = execModuleScript; - goog.queuedModules_.push(originalPath); - } else { - importScript(src, execModuleScript); - } - } else { - throw new Error('load of ' + src + 'failed'); - } - } -}; - - -//============================================================================== -// Language Enhancements -//============================================================================== - - -/** - * This is a "fixed" version of the typeof operator. It differs from the typeof - * operator in such a way that null returns 'null' and arrays return 'array'. - * @param {*} value The value to get the type of. - * @return {string} The name of the type. - */ -goog.typeOf = function(value) { - var s = typeof value; - if (s == 'object') { - if (value) { - // Check these first, so we can avoid calling Object.prototype.toString if - // possible. - // - // IE improperly marshals tyepof across execution contexts, but a - // cross-context object will still return false for "instanceof Object". - if (value instanceof Array) { - return 'array'; - } else if (value instanceof Object) { - return s; - } - - // HACK: In order to use an Object prototype method on the arbitrary - // value, the compiler requires the value be cast to type Object, - // even though the ECMA spec explicitly allows it. - var className = Object.prototype.toString.call( - /** @type {Object} */ (value)); - // In Firefox 3.6, attempting to access iframe window objects' length - // property throws an NS_ERROR_FAILURE, so we need to special-case it - // here. - if (className == '[object Window]') { - return 'object'; - } - - // We cannot always use constructor == Array or instanceof Array because - // different frames have different Array objects. In IE6, if the iframe - // where the array was created is destroyed, the array loses its - // prototype. Then dereferencing val.splice here throws an exception, so - // we can't use goog.isFunction. Calling typeof directly returns 'unknown' - // so that will work. In this case, this function will return false and - // most array functions will still work because the array is still - // array-like (supports length and []) even though it has lost its - // prototype. - // Mark Miller noticed that Object.prototype.toString - // allows access to the unforgeable [[Class]] property. - // 15.2.4.2 Object.prototype.toString ( ) - // When the toString method is called, the following steps are taken: - // 1. Get the [[Class]] property of this object. - // 2. Compute a string value by concatenating the three strings - // "[object ", Result(1), and "]". - // 3. Return Result(2). - // and this behavior survives the destruction of the execution context. - if ((className == '[object Array]' || - // In IE all non value types are wrapped as objects across window - // boundaries (not iframe though) so we have to do object detection - // for this edge case. - typeof value.length == 'number' && - typeof value.splice != 'undefined' && - typeof value.propertyIsEnumerable != 'undefined' && - !value.propertyIsEnumerable('splice') - - )) { - return 'array'; - } - // HACK: There is still an array case that fails. - // function ArrayImpostor() {} - // ArrayImpostor.prototype = []; - // var impostor = new ArrayImpostor; - // this can be fixed by getting rid of the fast path - // (value instanceof Array) and solely relying on - // (value && Object.prototype.toString.vall(value) === '[object Array]') - // but that would require many more function calls and is not warranted - // unless closure code is receiving objects from untrusted sources. - - // IE in cross-window calls does not correctly marshal the function type - // (it appears just as an object) so we cannot use just typeof val == - // 'function'. However, if the object has a call property, it is a - // function. - if ((className == '[object Function]' || - typeof value.call != 'undefined' && - typeof value.propertyIsEnumerable != 'undefined' && - !value.propertyIsEnumerable('call'))) { - return 'function'; - } - - } else { - return 'null'; - } - - } else if (s == 'function' && typeof value.call == 'undefined') { - // In Safari typeof nodeList returns 'function', and on Firefox typeof - // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We - // would like to return object for those and we can detect an invalid - // function by making sure that the function object has a call method. - return 'object'; - } - return s; -}; - - -/** - * Returns true if the specified value is null. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is null. - */ -goog.isNull = function(val) { - return val === null; -}; - - -/** - * Returns true if the specified value is defined and not null. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is defined and not null. - */ -goog.isDefAndNotNull = function(val) { - // Note that undefined == null. - return val != null; -}; - - -/** - * Returns true if the specified value is an array. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is an array. - */ -goog.isArray = function(val) { - return goog.typeOf(val) == 'array'; -}; - - -/** - * Returns true if the object looks like an array. To qualify as array like - * the value needs to be either a NodeList or an object with a Number length - * property. As a special case, a function value is not array like, because its - * length property is fixed to correspond to the number of expected arguments. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is an array. - */ -goog.isArrayLike = function(val) { - var type = goog.typeOf(val); - // We do not use goog.isObject here in order to exclude function values. - return type == 'array' || type == 'object' && typeof val.length == 'number'; -}; - - -/** - * Returns true if the object looks like a Date. To qualify as Date-like the - * value needs to be an object and have a getFullYear() function. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is a like a Date. - */ -goog.isDateLike = function(val) { - return goog.isObject(val) && typeof val.getFullYear == 'function'; -}; - - -/** - * Returns true if the specified value is a string. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is a string. - */ -goog.isString = function(val) { - return typeof val == 'string'; -}; - - -/** - * Returns true if the specified value is a boolean. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is boolean. - */ -goog.isBoolean = function(val) { - return typeof val == 'boolean'; -}; - - -/** - * Returns true if the specified value is a number. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is a number. - */ -goog.isNumber = function(val) { - return typeof val == 'number'; -}; - - -/** - * Returns true if the specified value is a function. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is a function. - */ -goog.isFunction = function(val) { - return goog.typeOf(val) == 'function'; -}; - - -/** - * Returns true if the specified value is an object. This includes arrays and - * functions. - * @param {?} val Variable to test. - * @return {boolean} Whether variable is an object. - */ -goog.isObject = function(val) { - var type = typeof val; - return type == 'object' && val != null || type == 'function'; - // return Object(val) === val also works, but is slower, especially if val is - // not an object. -}; - - -/** - * Gets a unique ID for an object. This mutates the object so that further calls - * with the same object as a parameter returns the same value. The unique ID is - * guaranteed to be unique across the current session amongst objects that are - * passed into {@code getUid}. There is no guarantee that the ID is unique or - * consistent across sessions. It is unsafe to generate unique ID for function - * prototypes. - * - * @param {Object} obj The object to get the unique ID for. - * @return {number} The unique ID for the object. - */ -goog.getUid = function(obj) { - // TODO(arv): Make the type stricter, do not accept null. - - // In Opera window.hasOwnProperty exists but always returns false so we avoid - // using it. As a consequence the unique ID generated for BaseClass.prototype - // and SubClass.prototype will be the same. - return obj[goog.UID_PROPERTY_] || - (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_); -}; - - -/** - * Whether the given object is already assigned a unique ID. - * - * This does not modify the object. - * - * @param {!Object} obj The object to check. - * @return {boolean} Whether there is an assigned unique id for the object. - */ -goog.hasUid = function(obj) { - return !!obj[goog.UID_PROPERTY_]; -}; - - -/** - * Removes the unique ID from an object. This is useful if the object was - * previously mutated using {@code goog.getUid} in which case the mutation is - * undone. - * @param {Object} obj The object to remove the unique ID field from. - */ -goog.removeUid = function(obj) { - // TODO(arv): Make the type stricter, do not accept null. - - // In IE, DOM nodes are not instances of Object and throw an exception if we - // try to delete. Instead we try to use removeAttribute. - if ('removeAttribute' in obj) { - obj.removeAttribute(goog.UID_PROPERTY_); - } - /** @preserveTry */ - try { - delete obj[goog.UID_PROPERTY_]; - } catch (ex) { - } -}; - - -/** - * Name for unique ID property. Initialized in a way to help avoid collisions - * with other closure JavaScript on the same page. - * @type {string} - * @private - */ -goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0); - - -/** - * Counter for UID. - * @type {number} - * @private - */ -goog.uidCounter_ = 0; - - -/** - * Adds a hash code field to an object. The hash code is unique for the - * given object. - * @param {Object} obj The object to get the hash code for. - * @return {number} The hash code for the object. - * @deprecated Use goog.getUid instead. - */ -goog.getHashCode = goog.getUid; - - -/** - * Removes the hash code field from an object. - * @param {Object} obj The object to remove the field from. - * @deprecated Use goog.removeUid instead. - */ -goog.removeHashCode = goog.removeUid; - - -/** - * Clones a value. The input may be an Object, Array, or basic type. Objects and - * arrays will be cloned recursively. - * - * WARNINGS: - * <code>goog.cloneObject</code> does not detect reference loops. Objects that - * refer to themselves will cause infinite recursion. - * - * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies - * UIDs created by <code>getUid</code> into cloned results. - * - * @param {*} obj The value to clone. - * @return {*} A clone of the input value. - * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods. - */ -goog.cloneObject = function(obj) { - var type = goog.typeOf(obj); - if (type == 'object' || type == 'array') { - if (obj.clone) { - return obj.clone(); - } - var clone = type == 'array' ? [] : {}; - for (var key in obj) { - clone[key] = goog.cloneObject(obj[key]); - } - return clone; - } - - return obj; -}; - - -/** - * A native implementation of goog.bind. - * @param {Function} fn A function to partially apply. - * @param {Object|undefined} selfObj Specifies the object which this should - * point to when the function is run. - * @param {...*} var_args Additional arguments that are partially applied to the - * function. - * @return {!Function} A partially-applied form of the function bind() was - * invoked as a method of. - * @private - * @suppress {deprecated} The compiler thinks that Function.prototype.bind is - * deprecated because some people have declared a pure-JS version. - * Only the pure-JS version is truly deprecated. - */ -goog.bindNative_ = function(fn, selfObj, var_args) { - return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments)); -}; - - -/** - * A pure-JS implementation of goog.bind. - * @param {Function} fn A function to partially apply. - * @param {Object|undefined} selfObj Specifies the object which this should - * point to when the function is run. - * @param {...*} var_args Additional arguments that are partially applied to the - * function. - * @return {!Function} A partially-applied form of the function bind() was - * invoked as a method of. - * @private - */ -goog.bindJs_ = function(fn, selfObj, var_args) { - if (!fn) { - throw new Error(); - } - - if (arguments.length > 2) { - var boundArgs = Array.prototype.slice.call(arguments, 2); - return function() { - // Prepend the bound arguments to the current arguments. - var newArgs = Array.prototype.slice.call(arguments); - Array.prototype.unshift.apply(newArgs, boundArgs); - return fn.apply(selfObj, newArgs); - }; - - } else { - return function() { - return fn.apply(selfObj, arguments); - }; - } -}; - - -/** - * Partially applies this function to a particular 'this object' and zero or - * more arguments. The result is a new function with some arguments of the first - * function pre-filled and the value of this 'pre-specified'. - * - * Remaining arguments specified at call-time are appended to the pre-specified - * ones. - * - * Also see: {@link #partial}. - * - * Usage: - * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2'); - * barMethBound('arg3', 'arg4');</pre> - * - * @param {?function(this:T, ...)} fn A function to partially apply. - * @param {T} selfObj Specifies the object which this should point to when the - * function is run. - * @param {...*} var_args Additional arguments that are partially applied to the - * function. - * @return {!Function} A partially-applied form of the function bind() was - * invoked as a method of. - * @template T - * @suppress {deprecated} See above. - */ -goog.bind = function(fn, selfObj, var_args) { - // TODO(nicksantos): narrow the type signature. - if (Function.prototype.bind && - // NOTE(nicksantos): Somebody pulled base.js into the default Chrome - // extension environment. This means that for Chrome extensions, they get - // the implementation of Function.prototype.bind that calls goog.bind - // instead of the native one. Even worse, we don't want to introduce a - // circular dependency between goog.bind and Function.prototype.bind, so - // we have to hack this to make sure it works correctly. - Function.prototype.bind.toString().indexOf('native code') != -1) { - goog.bind = goog.bindNative_; - } else { - goog.bind = goog.bindJs_; - } - return goog.bind.apply(null, arguments); -}; - - -/** - * Like bind(), except that a 'this object' is not required. Useful when the - * target function is already bound. - * - * Usage: - * var g = partial(f, arg1, arg2); - * g(arg3, arg4); - * - * @param {Function} fn A function to partially apply. - * @param {...*} var_args Additional arguments that are partially applied to fn. - * @return {!Function} A partially-applied form of the function bind() was - * invoked as a method of. - */ -goog.partial = function(fn, var_args) { - var args = Array.prototype.slice.call(arguments, 1); - return function() { - // Clone the array (with slice()) and append additional arguments - // to the existing arguments. - var newArgs = args.slice(); - newArgs.push.apply(newArgs, arguments); - return fn.apply(this, newArgs); - }; -}; - - -/** - * Copies all the members of a source object to a target object. This method - * does not work on all browsers for all objects that contain keys such as - * toString or hasOwnProperty. Use goog.object.extend for this purpose. - * @param {Object} target Target. - * @param {Object} source Source. - */ -goog.mixin = function(target, source) { - for (var x in source) { - target[x] = source[x]; - } - - // For IE7 or lower, the for-in-loop does not contain any properties that are - // not enumerable on the prototype object (for example, isPrototypeOf from - // Object.prototype) but also it will not include 'replace' on objects that - // extend String and change 'replace' (not that it is common for anyone to - // extend anything except Object). -}; - - -/** - * @return {number} An integer value representing the number of milliseconds - * between midnight, January 1, 1970 and the current time. - */ -goog.now = (goog.TRUSTED_SITE && Date.now) || (function() { - // Unary plus operator converts its operand to a number which in the case of - // a date is done by calling getTime(). - return +new Date(); -}); - - -/** - * Evals JavaScript in the global scope. In IE this uses execScript, other - * browsers use goog.global.eval. If goog.global.eval does not evaluate in the - * global scope (for example, in Safari), appends a script tag instead. - * Throws an exception if neither execScript or eval is defined. - * @param {string} script JavaScript string. - */ -goog.globalEval = function(script) { - if (goog.global.execScript) { - goog.global.execScript(script, 'JavaScript'); - } else if (goog.global.eval) { - // Test to see if eval works - if (goog.evalWorksForGlobals_ == null) { - goog.global.eval('var _et_ = 1;'); - if (typeof goog.global['_et_'] != 'undefined') { - delete goog.global['_et_']; - goog.evalWorksForGlobals_ = true; - } else { - goog.evalWorksForGlobals_ = false; - } - } - - if (goog.evalWorksForGlobals_) { - goog.global.eval(script); - } else { - var doc = goog.global.document; - var scriptElt = doc.createElement('script'); - scriptElt.type = 'text/javascript'; - scriptElt.defer = false; - // Note(user): can't use .innerHTML since "t('<test>')" will fail and - // .text doesn't work in Safari 2. Therefore we append a text node. - scriptElt.appendChild(doc.createTextNode(script)); - doc.body.appendChild(scriptElt); - doc.body.removeChild(scriptElt); - } - } else { - throw Error('goog.globalEval not available'); - } -}; - - -/** - * Indicates whether or not we can call 'eval' directly to eval code in the - * global scope. Set to a Boolean by the first call to goog.globalEval (which - * empirically tests whether eval works for globals). @see goog.globalEval - * @type {?boolean} - * @private - */ -goog.evalWorksForGlobals_ = null; - - -/** - * Optional map of CSS class names to obfuscated names used with - * goog.getCssName(). - * @private {!Object<string, string>|undefined} - * @see goog.setCssNameMapping - */ -goog.cssNameMapping_; - - -/** - * Optional obfuscation style for CSS class names. Should be set to either - * 'BY_WHOLE' or 'BY_PART' if defined. - * @type {string|undefined} - * @private - * @see goog.setCssNameMapping - */ -goog.cssNameMappingStyle_; - - -/** - * Handles strings that are intended to be used as CSS class names. - * - * This function works in tandem with @see goog.setCssNameMapping. - * - * Without any mapping set, the arguments are simple joined with a hyphen and - * passed through unaltered. - * - * When there is a mapping, there are two possible styles in which these - * mappings are used. In the BY_PART style, each part (i.e. in between hyphens) - * of the passed in css name is rewritten according to the map. In the BY_WHOLE - * style, the full css name is looked up in the map directly. If a rewrite is - * not specified by the map, the compiler will output a warning. - * - * When the mapping is passed to the compiler, it will replace calls to - * goog.getCssName with the strings from the mapping, e.g. - * var x = goog.getCssName('foo'); - * var y = goog.getCssName(this.baseClass, 'active'); - * becomes: - * var x= 'foo'; - * var y = this.baseClass + '-active'; - * - * If one argument is passed it will be processed, if two are passed only the - * modifier will be processed, as it is assumed the first argument was generated - * as a result of calling goog.getCssName. - * - * @param {string} className The class name. - * @param {string=} opt_modifier A modifier to be appended to the class name. - * @return {string} The class name or the concatenation of the class name and - * the modifier. - */ -goog.getCssName = function(className, opt_modifier) { - var getMapping = function(cssName) { - return goog.cssNameMapping_[cssName] || cssName; - }; - - var renameByParts = function(cssName) { - // Remap all the parts individually. - var parts = cssName.split('-'); - var mapped = []; - for (var i = 0; i < parts.length; i++) { - mapped.push(getMapping(parts[i])); - } - return mapped.join('-'); - }; - - var rename; - if (goog.cssNameMapping_) { - rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ? - getMapping : renameByParts; - } else { - rename = function(a) { - return a; - }; - } - - if (opt_modifier) { - return className + '-' + rename(opt_modifier); - } else { - return rename(className); - } -}; - - -/** - * Sets the map to check when returning a value from goog.getCssName(). Example: - * <pre> - * goog.setCssNameMapping({ - * "goog": "a", - * "disabled": "b", - * }); - * - * var x = goog.getCssName('goog'); - * // The following evaluates to: "a a-b". - * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled') - * </pre> - * When declared as a map of string literals to string literals, the JSCompiler - * will replace all calls to goog.getCssName() using the supplied map if the - * --closure_pass flag is set. - * - * @param {!Object} mapping A map of strings to strings where keys are possible - * arguments to goog.getCssName() and values are the corresponding values - * that should be returned. - * @param {string=} opt_style The style of css name mapping. There are two valid - * options: 'BY_PART', and 'BY_WHOLE'. - * @see goog.getCssName for a description. - */ -goog.setCssNameMapping = function(mapping, opt_style) { - goog.cssNameMapping_ = mapping; - goog.cssNameMappingStyle_ = opt_style; -}; - - -/** - * To use CSS renaming in compiled mode, one of the input files should have a - * call to goog.setCssNameMapping() with an object literal that the JSCompiler - * can extract and use to replace all calls to goog.getCssName(). In uncompiled - * mode, JavaScript code should be loaded before this base.js file that declares - * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is - * to ensure that the mapping is loaded before any calls to goog.getCssName() - * are made in uncompiled mode. - * - * A hook for overriding the CSS name mapping. - * @type {!Object<string, string>|undefined} - */ -goog.global.CLOSURE_CSS_NAME_MAPPING; - - -if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) { - // This does not call goog.setCssNameMapping() because the JSCompiler - // requires that goog.setCssNameMapping() be called with an object literal. - goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING; -} - - -/** - * Gets a localized message. - * - * This function is a compiler primitive. If you give the compiler a localized - * message bundle, it will replace the string at compile-time with a localized - * version, and expand goog.getMsg call to a concatenated string. - * - * Messages must be initialized in the form: - * <code> - * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'}); - * </code> - * - * @param {string} str Translatable string, places holders in the form {$foo}. - * @param {Object<string, string>=} opt_values Maps place holder name to value. - * @return {string} message with placeholders filled. - */ -goog.getMsg = function(str, opt_values) { - if (opt_values) { - str = str.replace(/\{\$([^}]+)}/g, function(match, key) { - return key in opt_values ? opt_values[key] : match; - }); - } - return str; -}; - - -/** - * Gets a localized message. If the message does not have a translation, gives a - * fallback message. - * - * This is useful when introducing a new message that has not yet been - * translated into all languages. - * - * This function is a compiler primitive. Must be used in the form: - * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code> - * where MSG_A and MSG_B were initialized with goog.getMsg. - * - * @param {string} a The preferred message. - * @param {string} b The fallback message. - * @return {string} The best translated message. - */ -goog.getMsgWithFallback = function(a, b) { - return a; -}; - - -/** - * Exposes an unobfuscated global namespace path for the given object. - * Note that fields of the exported object *will* be obfuscated, unless they are - * exported in turn via this function or goog.exportProperty. - * - * Also handy for making public items that are defined in anonymous closures. - * - * ex. goog.exportSymbol('public.path.Foo', Foo); - * - * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction); - * public.path.Foo.staticFunction(); - * - * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod', - * Foo.prototype.myMethod); - * new public.path.Foo().myMethod(); - * - * @param {string} publicPath Unobfuscated name to export. - * @param {*} object Object the name should point to. - * @param {Object=} opt_objectToExportTo The object to add the path to; default - * is goog.global. - */ -goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) { - goog.exportPath_(publicPath, object, opt_objectToExportTo); -}; - - -/** - * Exports a property unobfuscated into the object's namespace. - * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction); - * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod); - * @param {Object} object Object whose static property is being exported. - * @param {string} publicName Unobfuscated name to export. - * @param {*} symbol Object the name should point to. - */ -goog.exportProperty = function(object, publicName, symbol) { - object[publicName] = symbol; -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * Usage: - * <pre> - * function ParentClass(a, b) { } - * ParentClass.prototype.foo = function(a) { }; - * - * function ChildClass(a, b, c) { - * ChildClass.base(this, 'constructor', a, b); - * } - * goog.inherits(ChildClass, ParentClass); - * - * var child = new ChildClass('a', 'b', 'see'); - * child.foo(); // This works. - * </pre> - * - * @param {Function} childCtor Child class. - * @param {Function} parentCtor Parent class. - */ -goog.inherits = function(childCtor, parentCtor) { - /** @constructor */ - function tempCtor() {}; - tempCtor.prototype = parentCtor.prototype; - childCtor.superClass_ = parentCtor.prototype; - childCtor.prototype = new tempCtor(); - /** @override */ - childCtor.prototype.constructor = childCtor; - - /** - * Calls superclass constructor/method. - * - * This function is only available if you use goog.inherits to - * express inheritance relationships between classes. - * - * NOTE: This is a replacement for goog.base and for superClass_ - * property defined in childCtor. - * - * @param {!Object} me Should always be "this". - * @param {string} methodName The method name to call. Calling - * superclass constructor can be done with the special string - * 'constructor'. - * @param {...*} var_args The arguments to pass to superclass - * method/constructor. - * @return {*} The return value of the superclass method/constructor. - */ - childCtor.base = function(me, methodName, var_args) { - // Copying using loop to avoid deop due to passing arguments object to - // function. This is faster in many JS engines as of late 2014. - var args = new Array(arguments.length - 2); - for (var i = 2; i < arguments.length; i++) { - args[i - 2] = arguments[i]; - } - return parentCtor.prototype[methodName].apply(me, args); - }; -}; - - -/** - * Call up to the superclass. - * - * If this is called from a constructor, then this calls the superclass - * constructor with arguments 1-N. - * - * If this is called from a prototype method, then you must pass the name of the - * method as the second argument to this function. If you do not, you will get a - * runtime error. This calls the superclass' method with arguments 2-N. - * - * This function only works if you use goog.inherits to express inheritance - * relationships between your classes. - * - * This function is a compiler primitive. At compile-time, the compiler will do - * macro expansion to remove a lot of the extra overhead that this function - * introduces. The compiler will also enforce a lot of the assumptions that this - * function makes, and treat it as a compiler error if you break them. - * - * @param {!Object} me Should always be "this". - * @param {*=} opt_methodName The method name if calling a super method. - * @param {...*} var_args The rest of the arguments. - * @return {*} The return value of the superclass method. - * @suppress {es5Strict} This method can not be used in strict mode, but - * all Closure Library consumers must depend on this file. - */ -goog.base = function(me, opt_methodName, var_args) { - var caller = arguments.callee.caller; - - if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) { - throw Error('arguments.caller not defined. goog.base() cannot be used ' + - 'with strict mode code. See ' + - 'http://www.ecma-international.org/ecma-262/5.1/#sec-C'); - } - - if (caller.superClass_) { - // Copying using loop to avoid deop due to passing arguments object to - // function. This is faster in many JS engines as of late 2014. - var ctorArgs = new Array(arguments.length - 1); - for (var i = 1; i < arguments.length; i++) { - ctorArgs[i - 1] = arguments[i]; - } - // This is a constructor. Call the superclass constructor. - return caller.superClass_.constructor.apply(me, ctorArgs); - } - - // Copying using loop to avoid deop due to passing arguments object to - // function. This is faster in many JS engines as of late 2014. - var args = new Array(arguments.length - 2); - for (var i = 2; i < arguments.length; i++) { - args[i - 2] = arguments[i]; - } - var foundCaller = false; - for (var ctor = me.constructor; - ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) { - if (ctor.prototype[opt_methodName] === caller) { - foundCaller = true; - } else if (foundCaller) { - return ctor.prototype[opt_methodName].apply(me, args); - } - } - - // If we did not find the caller in the prototype chain, then one of two - // things happened: - // 1) The caller is an instance method. - // 2) This method was not called by the right caller. - if (me[opt_methodName] === caller) { - return me.constructor.prototype[opt_methodName].apply(me, args); - } else { - throw Error( - 'goog.base called from a method of one name ' + - 'to a method of a different name'); - } -}; - - -/** - * Allow for aliasing within scope functions. This function exists for - * uncompiled code - in compiled code the calls will be inlined and the aliases - * applied. In uncompiled code the function is simply run since the aliases as - * written are valid JavaScript. - * - * - * @param {function()} fn Function to call. This function can contain aliases - * to namespaces (e.g. "var dom = goog.dom") or classes - * (e.g. "var Timer = goog.Timer"). - */ -goog.scope = function(fn) { - fn.call(goog.global); -}; - - -/* - * To support uncompiled, strict mode bundles that use eval to divide source - * like so: - * eval('someSource;//# sourceUrl sourcefile.js'); - * We need to export the globally defined symbols "goog" and "COMPILED". - * Exporting "goog" breaks the compiler optimizations, so we required that - * be defined externally. - * NOTE: We don't use goog.exportSymbol here because we don't want to trigger - * extern generation when that compiler option is enabled. - */ -if (!COMPILED) { - goog.global['COMPILED'] = COMPILED; -} - - - -//============================================================================== -// goog.defineClass implementation -//============================================================================== - - -/** - * Creates a restricted form of a Closure "class": - * - from the compiler's perspective, the instance returned from the - * constructor is sealed (no new properties may be added). This enables - * better checks. - * - the compiler will rewrite this definition to a form that is optimal - * for type checking and optimization (initially this will be a more - * traditional form). - * - * @param {Function} superClass The superclass, Object or null. - * @param {goog.defineClass.ClassDescriptor} def - * An object literal describing - * the class. It may have the following properties: - * "constructor": the constructor function - * "statics": an object literal containing methods to add to the constructor - * as "static" methods or a function that will receive the constructor - * function as its only parameter to which static properties can - * be added. - * all other properties are added to the prototype. - * @return {!Function} The class constructor. - */ -goog.defineClass = function(superClass, def) { - // TODO(johnlenz): consider making the superClass an optional parameter. - var constructor = def.constructor; - var statics = def.statics; - // Wrap the constructor prior to setting up the prototype and static methods. - if (!constructor || constructor == Object.prototype.constructor) { - constructor = function() { - throw Error('cannot instantiate an interface (no constructor defined).'); - }; - } - - var cls = goog.defineClass.createSealingConstructor_(constructor, superClass); - if (superClass) { - goog.inherits(cls, superClass); - } - - // Remove all the properties that should not be copied to the prototype. - delete def.constructor; - delete def.statics; - - goog.defineClass.applyProperties_(cls.prototype, def); - if (statics != null) { - if (statics instanceof Function) { - statics(cls); - } else { - goog.defineClass.applyProperties_(cls, statics); - } - } - - return cls; -}; - - -/** - * @typedef { - * !Object| - * {constructor:!Function}| - * {constructor:!Function, statics:(Object|function(Function):void)}} - * @suppress {missingProvide} - */ -goog.defineClass.ClassDescriptor; - - -/** - * @define {boolean} Whether the instances returned by - * goog.defineClass should be sealed when possible. - */ -goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG); - - -/** - * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is - * defined, this function will wrap the constructor in a function that seals the - * results of the provided constructor function. - * - * @param {!Function} ctr The constructor whose results maybe be sealed. - * @param {Function} superClass The superclass constructor. - * @return {!Function} The replacement constructor. - * @private - */ -goog.defineClass.createSealingConstructor_ = function(ctr, superClass) { - if (goog.defineClass.SEAL_CLASS_INSTANCES && - Object.seal instanceof Function) { - // Don't seal subclasses of unsealable-tagged legacy classes. - if (superClass && superClass.prototype && - superClass.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_]) { - return ctr; - } - /** - * @this {*} - * @return {?} - */ - var wrappedCtr = function() { - // Don't seal an instance of a subclass when it calls the constructor of - // its super class as there is most likely still setup to do. - var instance = ctr.apply(this, arguments) || this; - instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_]; - if (this.constructor === wrappedCtr) { - Object.seal(instance); - } - return instance; - }; - return wrappedCtr; - } - return ctr; -}; - - -// TODO(johnlenz): share these values with the goog.object -/** - * The names of the fields that are defined on Object.prototype. - * @type {!Array<string>} - * @private - * @const - */ -goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [ - 'constructor', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'toLocaleString', - 'toString', - 'valueOf' -]; - - -// TODO(johnlenz): share this function with the goog.object -/** - * @param {!Object} target The object to add properties to. - * @param {!Object} source The object to copy properties from. - * @private - */ -goog.defineClass.applyProperties_ = function(target, source) { - // TODO(johnlenz): update this to support ES5 getters/setters - - var key; - for (key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - - // For IE the for-in-loop does not contain any properties that are not - // enumerable on the prototype object (for example isPrototypeOf from - // Object.prototype) and it will also not include 'replace' on objects that - // extend String and change 'replace' (not that it is common for anyone to - // extend anything except Object). - for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) { - key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i]; - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } -}; - - -/** - * Sealing classes breaks the older idiom of assigning properties on the - * prototype rather than in the constructor. As such, goog.defineClass - * must not seal subclasses of these old-style classes until they are fixed. - * Until then, this marks a class as "broken", instructing defineClass - * not to seal subclasses. - * @param {!Function} ctr The legacy constructor to tag as unsealable. - */ -goog.tagUnsealableClass = function(ctr) { - if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) { - ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true; - } -}; - - -/** - * Name for unsealable tag property. - * @const @private {string} - */ -goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable'; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/debug.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/debug.js deleted file mode 100644 index 5abce3c..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/debug.js +++ /dev/null @@ -1,632 +0,0 @@ -// 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 Logging and debugging utilities. - * - * @see ../demos/debug.html - */ - -goog.provide('goog.debug'); - -goog.require('goog.array'); -goog.require('goog.html.SafeHtml'); -goog.require('goog.html.SafeUrl'); -goog.require('goog.html.uncheckedconversions'); -goog.require('goog.string.Const'); -goog.require('goog.structs.Set'); -goog.require('goog.userAgent'); - - -/** @define {boolean} Whether logging should be enabled. */ -goog.define('goog.debug.LOGGING_ENABLED', goog.DEBUG); - - -/** - * Catches onerror events fired by windows and similar objects. - * @param {function(Object)} logFunc The function to call with the error - * information. - * @param {boolean=} opt_cancel Whether to stop the error from reaching the - * browser. - * @param {Object=} opt_target Object that fires onerror events. - */ -goog.debug.catchErrors = function(logFunc, opt_cancel, opt_target) { - var target = opt_target || goog.global; - var oldErrorHandler = target.onerror; - var retVal = !!opt_cancel; - - // Chrome interprets onerror return value backwards (http://crbug.com/92062) - // until it was fixed in webkit revision r94061 (Webkit 535.3). This - // workaround still needs to be skipped in Safari after the webkit change - // gets pushed out in Safari. - // See https://bugs.webkit.org/show_bug.cgi?id=67119 - if (goog.userAgent.WEBKIT && - !goog.userAgent.isVersionOrHigher('535.3')) { - retVal = !retVal; - } - - /** - * New onerror handler for this target. This onerror handler follows the spec - * according to - * http://www.whatwg.org/specs/web-apps/current-work/#runtime-script-errors - * The spec was changed in August 2013 to support receiving column information - * and an error object for all scripts on the same origin or cross origin - * scripts with the proper headers. See - * https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror - * - * @param {string} message The error message. For cross-origin errors, this - * will be scrubbed to just "Script error.". For new browsers that have - * updated to follow the latest spec, errors that come from origins that - * have proper cross origin headers will not be scrubbed. - * @param {string} url The URL of the script that caused the error. The URL - * will be scrubbed to "" for cross origin scripts unless the script has - * proper cross origin headers and the browser has updated to the latest - * spec. - * @param {number} line The line number in the script that the error - * occurred on. - * @param {number=} opt_col The optional column number that the error - * occurred on. Only browsers that have updated to the latest spec will - * include this. - * @param {Error=} opt_error The optional actual error object for this - * error that should include the stack. Only browsers that have updated - * to the latest spec will inlude this parameter. - * @return {boolean} Whether to prevent the error from reaching the browser. - */ - target.onerror = function(message, url, line, opt_col, opt_error) { - if (oldErrorHandler) { - oldErrorHandler(message, url, line, opt_col, opt_error); - } - logFunc({ - message: message, - fileName: url, - line: line, - col: opt_col, - error: opt_error - }); - return retVal; - }; -}; - - -/** - * Creates a string representing an object and all its properties. - * @param {Object|null|undefined} obj Object to expose. - * @param {boolean=} opt_showFn Show the functions as well as the properties, - * default is false. - * @return {string} The string representation of {@code obj}. - */ -goog.debug.expose = function(obj, opt_showFn) { - if (typeof obj == 'undefined') { - return 'undefined'; - } - if (obj == null) { - return 'NULL'; - } - var str = []; - - for (var x in obj) { - if (!opt_showFn && goog.isFunction(obj[x])) { - continue; - } - var s = x + ' = '; - /** @preserveTry */ - try { - s += obj[x]; - } catch (e) { - s += '*** ' + e + ' ***'; - } - str.push(s); - } - return str.join('\n'); -}; - - -/** - * Creates a string representing a given primitive or object, and for an - * object, all its properties and nested objects. WARNING: If an object is - * given, it and all its nested objects will be modified. To detect reference - * cycles, this method identifies objects using goog.getUid() which mutates the - * object. - * @param {*} obj Object to expose. - * @param {boolean=} opt_showFn Also show properties that are functions (by - * default, functions are omitted). - * @return {string} A string representation of {@code obj}. - */ -goog.debug.deepExpose = function(obj, opt_showFn) { - var str = []; - - var helper = function(obj, space, parentSeen) { - var nestspace = space + ' '; - var seen = new goog.structs.Set(parentSeen); - - var indentMultiline = function(str) { - return str.replace(/\n/g, '\n' + space); - }; - - /** @preserveTry */ - try { - if (!goog.isDef(obj)) { - str.push('undefined'); - } else if (goog.isNull(obj)) { - str.push('NULL'); - } else if (goog.isString(obj)) { - str.push('"' + indentMultiline(obj) + '"'); - } else if (goog.isFunction(obj)) { - str.push(indentMultiline(String(obj))); - } else if (goog.isObject(obj)) { - if (seen.contains(obj)) { - str.push('*** reference loop detected ***'); - } else { - seen.add(obj); - str.push('{'); - for (var x in obj) { - if (!opt_showFn && goog.isFunction(obj[x])) { - continue; - } - str.push('\n'); - str.push(nestspace); - str.push(x + ' = '); - helper(obj[x], nestspace, seen); - } - str.push('\n' + space + '}'); - } - } else { - str.push(obj); - } - } catch (e) { - str.push('*** ' + e + ' ***'); - } - }; - - helper(obj, '', new goog.structs.Set()); - return str.join(''); -}; - - -/** - * Recursively outputs a nested array as a string. - * @param {Array<?>} arr The array. - * @return {string} String representing nested array. - */ -goog.debug.exposeArray = function(arr) { - var str = []; - for (var i = 0; i < arr.length; i++) { - if (goog.isArray(arr[i])) { - str.push(goog.debug.exposeArray(arr[i])); - } else { - str.push(arr[i]); - } - } - return '[ ' + str.join(', ') + ' ]'; -}; - - -/** - * Exposes an exception that has been caught by a try...catch and outputs the - * error as HTML with a stack trace. - * @param {Object} err Error object or string. - * @param {Function=} opt_fn Optional function to start stack trace from. - * @return {string} Details of exception, as HTML. - */ -goog.debug.exposeException = function(err, opt_fn) { - var html = goog.debug.exposeExceptionAsHtml(err, opt_fn); - return goog.html.SafeHtml.unwrap(html); -}; - - -/** - * Exposes an exception that has been caught by a try...catch and outputs the - * error with a stack trace. - * @param {Object} err Error object or string. - * @param {Function=} opt_fn Optional function to start stack trace from. - * @return {!goog.html.SafeHtml} Details of exception. - */ -goog.debug.exposeExceptionAsHtml = function(err, opt_fn) { - /** @preserveTry */ - try { - var e = goog.debug.normalizeErrorObject(err); - // Create the error message - var viewSourceUrl = goog.debug.createViewSourceUrl_(e.fileName); - var error = goog.html.SafeHtml.concat( - goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces( - 'Message: ' + e.message + '\nUrl: '), - goog.html.SafeHtml.create('a', - {href: viewSourceUrl, target: '_new'}, e.fileName), - goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces( - '\nLine: ' + e.lineNumber + '\n\nBrowser stack:\n' + - e.stack + '-> ' + '[end]\n\nJS stack traversal:\n' + - goog.debug.getStacktrace(opt_fn) + '-> ')); - return error; - } catch (e2) { - return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces( - 'Exception trying to expose exception! You win, we lose. ' + e2); - } -}; - - -/** - * @param {?string=} opt_fileName - * @return {!goog.html.SafeUrl} SafeUrl with view-source scheme, pointing at - * fileName. - * @private - */ -goog.debug.createViewSourceUrl_ = function(opt_fileName) { - if (!goog.isDefAndNotNull(opt_fileName)) { - opt_fileName = ''; - } - if (!/^https?:\/\//i.test(opt_fileName)) { - return goog.html.SafeUrl.fromConstant( - goog.string.Const.from('sanitizedviewsrc')); - } - var sanitizedFileName = goog.html.SafeUrl.sanitize(opt_fileName); - return goog.html.uncheckedconversions. - safeUrlFromStringKnownToSatisfyTypeContract( - goog.string.Const.from('view-source scheme plus HTTP/HTTPS URL'), - 'view-source:' + goog.html.SafeUrl.unwrap(sanitizedFileName)); -}; - - -/** - * Normalizes the error/exception object between browsers. - * @param {Object} err Raw error object. - * @return {!Object} Normalized error object. - */ -goog.debug.normalizeErrorObject = function(err) { - var href = goog.getObjectByName('window.location.href'); - if (goog.isString(err)) { - return { - 'message': err, - 'name': 'Unknown error', - 'lineNumber': 'Not available', - 'fileName': href, - 'stack': 'Not available' - }; - } - - var lineNumber, fileName; - var threwError = false; - - try { - lineNumber = err.lineNumber || err.line || 'Not available'; - } catch (e) { - // Firefox 2 sometimes throws an error when accessing 'lineNumber': - // Message: Permission denied to get property UnnamedClass.lineNumber - lineNumber = 'Not available'; - threwError = true; - } - - try { - fileName = err.fileName || err.filename || err.sourceURL || - // $googDebugFname may be set before a call to eval to set the filename - // that the eval is supposed to present. - goog.global['$googDebugFname'] || href; - } catch (e) { - // Firefox 2 may also throw an error when accessing 'filename'. - fileName = 'Not available'; - threwError = true; - } - - // The IE Error object contains only the name and the message. - // The Safari Error object uses the line and sourceURL fields. - if (threwError || !err.lineNumber || !err.fileName || !err.stack || - !err.message || !err.name) { - return { - 'message': err.message || 'Not available', - 'name': err.name || 'UnknownError', - 'lineNumber': lineNumber, - 'fileName': fileName, - 'stack': err.stack || 'Not available' - }; - } - - // Standards error object - return err; -}; - - -/** - * Converts an object to an Error if it's a String, - * adds a stacktrace if there isn't one, - * and optionally adds an extra message. - * @param {Error|string} err the original thrown object or string. - * @param {string=} opt_message optional additional message to add to the - * error. - * @return {!Error} If err is a string, it is used to create a new Error, - * which is enhanced and returned. Otherwise err itself is enhanced - * and returned. - */ -goog.debug.enhanceError = function(err, opt_message) { - var error; - if (typeof err == 'string') { - error = Error(err); - if (Error.captureStackTrace) { - // Trim this function off the call stack, if we can. - Error.captureStackTrace(error, goog.debug.enhanceError); - } - } else { - error = err; - } - - if (!error.stack) { - error.stack = goog.debug.getStacktrace(goog.debug.enhanceError); - } - if (opt_message) { - // find the first unoccupied 'messageX' property - var x = 0; - while (error['message' + x]) { - ++x; - } - error['message' + x] = String(opt_message); - } - return error; -}; - - -/** - * Gets the current stack trace. Simple and iterative - doesn't worry about - * catching circular references or getting the args. - * @param {number=} opt_depth Optional maximum depth to trace back to. - * @return {string} A string with the function names of all functions in the - * stack, separated by \n. - * @suppress {es5Strict} - */ -goog.debug.getStacktraceSimple = function(opt_depth) { - if (goog.STRICT_MODE_COMPATIBLE) { - var stack = goog.debug.getNativeStackTrace_(goog.debug.getStacktraceSimple); - if (stack) { - return stack; - } - // NOTE: browsers that have strict mode support also have native "stack" - // properties. Fall-through for legacy browser support. - } - - var sb = []; - var fn = arguments.callee.caller; - var depth = 0; - - while (fn && (!opt_depth || depth < opt_depth)) { - sb.push(goog.debug.getFunctionName(fn)); - sb.push('()\n'); - /** @preserveTry */ - try { - fn = fn.caller; - } catch (e) { - sb.push('[exception trying to get caller]\n'); - break; - } - depth++; - if (depth >= goog.debug.MAX_STACK_DEPTH) { - sb.push('[...long stack...]'); - break; - } - } - if (opt_depth && depth >= opt_depth) { - sb.push('[...reached max depth limit...]'); - } else { - sb.push('[end]'); - } - - return sb.join(''); -}; - - -/** - * Max length of stack to try and output - * @type {number} - */ -goog.debug.MAX_STACK_DEPTH = 50; - - -/** - * @param {Function} fn The function to start getting the trace from. - * @return {?string} - * @private - */ -goog.debug.getNativeStackTrace_ = function(fn) { - var tempErr = new Error(); - if (Error.captureStackTrace) { - Error.captureStackTrace(tempErr, fn); - return String(tempErr.stack); - } else { - // IE10, only adds stack traces when an exception is thrown. - try { - throw tempErr; - } catch (e) { - tempErr = e; - } - var stack = tempErr.stack; - if (stack) { - return String(stack); - } - } - return null; -}; - - -/** - * Gets the current stack trace, either starting from the caller or starting - * from a specified function that's currently on the call stack. - * @param {Function=} opt_fn Optional function to start getting the trace from. - * If not provided, defaults to the function that called this. - * @return {string} Stack trace. - * @suppress {es5Strict} - */ -goog.debug.getStacktrace = function(opt_fn) { - var stack; - if (goog.STRICT_MODE_COMPATIBLE) { - // Try to get the stack trace from the environment if it is available. - var contextFn = opt_fn || goog.debug.getStacktrace; - stack = goog.debug.getNativeStackTrace_(contextFn); - } - if (!stack) { - // NOTE: browsers that have strict mode support also have native "stack" - // properties. This function will throw in strict mode. - stack = goog.debug.getStacktraceHelper_( - opt_fn || arguments.callee.caller, []); - } - return stack; -}; - - -/** - * Private helper for getStacktrace(). - * @param {Function} fn Function to start getting the trace from. - * @param {Array<!Function>} visited List of functions visited so far. - * @return {string} Stack trace starting from function fn. - * @suppress {es5Strict} - * @private - */ -goog.debug.getStacktraceHelper_ = function(fn, visited) { - var sb = []; - - // Circular reference, certain functions like bind seem to cause a recursive - // loop so we need to catch circular references - if (goog.array.contains(visited, fn)) { - sb.push('[...circular reference...]'); - - // Traverse the call stack until function not found or max depth is reached - } else if (fn && visited.length < goog.debug.MAX_STACK_DEPTH) { - sb.push(goog.debug.getFunctionName(fn) + '('); - var args = fn.arguments; - // Args may be null for some special functions such as host objects or eval. - for (var i = 0; args && i < args.length; i++) { - if (i > 0) { - sb.push(', '); - } - var argDesc; - var arg = args[i]; - switch (typeof arg) { - case 'object': - argDesc = arg ? 'object' : 'null'; - break; - - case 'string': - argDesc = arg; - break; - - case 'number': - argDesc = String(arg); - break; - - case 'boolean': - argDesc = arg ? 'true' : 'false'; - break; - - case 'function': - argDesc = goog.debug.getFunctionName(arg); - argDesc = argDesc ? argDesc : '[fn]'; - break; - - case 'undefined': - default: - argDesc = typeof arg; - break; - } - - if (argDesc.length > 40) { - argDesc = argDesc.substr(0, 40) + '...'; - } - sb.push(argDesc); - } - visited.push(fn); - sb.push(')\n'); - /** @preserveTry */ - try { - sb.push(goog.debug.getStacktraceHelper_(fn.caller, visited)); - } catch (e) { - sb.push('[exception trying to get caller]\n'); - } - - } else if (fn) { - sb.push('[...long stack...]'); - } else { - sb.push('[end]'); - } - return sb.join(''); -}; - - -/** - * Set a custom function name resolver. - * @param {function(Function): string} resolver Resolves functions to their - * names. - */ -goog.debug.setFunctionResolver = function(resolver) { - goog.debug.fnNameResolver_ = resolver; -}; - - -/** - * Gets a function name - * @param {Function} fn Function to get name of. - * @return {string} Function's name. - */ -goog.debug.getFunctionName = function(fn) { - if (goog.debug.fnNameCache_[fn]) { - return goog.debug.fnNameCache_[fn]; - } - if (goog.debug.fnNameResolver_) { - var name = goog.debug.fnNameResolver_(fn); - if (name) { - goog.debug.fnNameCache_[fn] = name; - return name; - } - } - - // Heuristically determine function name based on code. - var functionSource = String(fn); - if (!goog.debug.fnNameCache_[functionSource]) { - var matches = /function ([^\(]+)/.exec(functionSource); - if (matches) { - var method = matches[1]; - goog.debug.fnNameCache_[functionSource] = method; - } else { - goog.debug.fnNameCache_[functionSource] = '[Anonymous]'; - } - } - - return goog.debug.fnNameCache_[functionSource]; -}; - - -/** - * Makes whitespace visible by replacing it with printable characters. - * This is useful in finding diffrences between the expected and the actual - * output strings of a testcase. - * @param {string} string whose whitespace needs to be made visible. - * @return {string} string whose whitespace is made visible. - */ -goog.debug.makeWhitespaceVisible = function(string) { - return string.replace(/ /g, '[_]') - .replace(/\f/g, '[f]') - .replace(/\n/g, '[n]\n') - .replace(/\r/g, '[r]') - .replace(/\t/g, '[t]'); -}; - - -/** - * Hash map for storing function names that have already been looked up. - * @type {Object} - * @private - */ -goog.debug.fnNameCache_ = {}; - - -/** - * Resolves functions to their names. Resolved function names will be cached. - * @type {function(Function):string} - * @private - */ -goog.debug.fnNameResolver_; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/entrypointregistry.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/entrypointregistry.js deleted file mode 100644 index 3ae7549..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/entrypointregistry.js +++ /dev/null @@ -1,158 +0,0 @@ -// 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 A global registry for entry points into a program, - * so that they can be instrumented. Each module should register their - * entry points with this registry. Designed to be compiled out - * if no instrumentation is requested. - * - * Entry points may be registered before or after a call to - * goog.debug.entryPointRegistry.monitorAll. If an entry point is registered - * later, the existing monitor will instrument the new entry point. - * - * @author nicksantos@google.com (Nick Santos) - */ - -goog.provide('goog.debug.EntryPointMonitor'); -goog.provide('goog.debug.entryPointRegistry'); - -goog.require('goog.asserts'); - - - -/** - * @interface - */ -goog.debug.EntryPointMonitor = function() {}; - - -/** - * Instruments a function. - * - * @param {!Function} fn A function to instrument. - * @return {!Function} The instrumented function. - */ -goog.debug.EntryPointMonitor.prototype.wrap; - - -/** - * Try to remove an instrumentation wrapper created by this monitor. - * If the function passed to unwrap is not a wrapper created by this - * monitor, then we will do nothing. - * - * Notice that some wrappers may not be unwrappable. For example, if other - * monitors have applied their own wrappers, then it will be impossible to - * unwrap them because their wrappers will have captured our wrapper. - * - * So it is important that entry points are unwrapped in the reverse - * order that they were wrapped. - * - * @param {!Function} fn A function to unwrap. - * @return {!Function} The unwrapped function, or {@code fn} if it was not - * a wrapped function created by this monitor. - */ -goog.debug.EntryPointMonitor.prototype.unwrap; - - -/** - * An array of entry point callbacks. - * @type {!Array<function(!Function)>} - * @private - */ -goog.debug.entryPointRegistry.refList_ = []; - - -/** - * Monitors that should wrap all the entry points. - * @type {!Array<!goog.debug.EntryPointMonitor>} - * @private - */ -goog.debug.entryPointRegistry.monitors_ = []; - - -/** - * Whether goog.debug.entryPointRegistry.monitorAll has ever been called. - * Checking this allows the compiler to optimize out the registrations. - * @type {boolean} - * @private - */ -goog.debug.entryPointRegistry.monitorsMayExist_ = false; - - -/** - * Register an entry point with this module. - * - * The entry point will be instrumented when a monitor is passed to - * goog.debug.entryPointRegistry.monitorAll. If this has already occurred, the - * entry point is instrumented immediately. - * - * @param {function(!Function)} callback A callback function which is called - * with a transforming function to instrument the entry point. The callback - * is responsible for wrapping the relevant entry point with the - * transforming function. - */ -goog.debug.entryPointRegistry.register = function(callback) { - // Don't use push(), so that this can be compiled out. - goog.debug.entryPointRegistry.refList_[ - goog.debug.entryPointRegistry.refList_.length] = callback; - // If no one calls monitorAll, this can be compiled out. - if (goog.debug.entryPointRegistry.monitorsMayExist_) { - var monitors = goog.debug.entryPointRegistry.monitors_; - for (var i = 0; i < monitors.length; i++) { - callback(goog.bind(monitors[i].wrap, monitors[i])); - } - } -}; - - -/** - * Configures a monitor to wrap all entry points. - * - * Entry points that have already been registered are immediately wrapped by - * the monitor. When an entry point is registered in the future, it will also - * be wrapped by the monitor when it is registered. - * - * @param {!goog.debug.EntryPointMonitor} monitor An entry point monitor. - */ -goog.debug.entryPointRegistry.monitorAll = function(monitor) { - goog.debug.entryPointRegistry.monitorsMayExist_ = true; - var transformer = goog.bind(monitor.wrap, monitor); - for (var i = 0; i < goog.debug.entryPointRegistry.refList_.length; i++) { - goog.debug.entryPointRegistry.refList_[i](transformer); - } - goog.debug.entryPointRegistry.monitors_.push(monitor); -}; - - -/** - * Try to unmonitor all the entry points that have already been registered. If - * an entry point is registered in the future, it will not be wrapped by the - * monitor when it is registered. Note that this may fail if the entry points - * have additional wrapping. - * - * @param {!goog.debug.EntryPointMonitor} monitor The last monitor to wrap - * the entry points. - * @throws {Error} If the monitor is not the most recently configured monitor. - */ -goog.debug.entryPointRegistry.unmonitorAllIfPossible = function(monitor) { - var monitors = goog.debug.entryPointRegistry.monitors_; - goog.asserts.assert(monitor == monitors[monitors.length - 1], - 'Only the most recent monitor can be unwrapped.'); - var transformer = goog.bind(monitor.unwrap, monitor); - for (var i = 0; i < goog.debug.entryPointRegistry.refList_.length; i++) { - goog.debug.entryPointRegistry.refList_[i](transformer); - } - monitors.length--; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/error.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/error.js deleted file mode 100644 index 6fed470..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/error.js +++ /dev/null @@ -1,54 +0,0 @@ -// 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 base class for custom Error objects such that the - * stack is correctly maintained. - * - * You should never need to throw goog.debug.Error(msg) directly, Error(msg) is - * sufficient. - * - */ - -goog.provide('goog.debug.Error'); - - - -/** - * Base class for custom error objects. - * @param {*=} opt_msg The message associated with the error. - * @constructor - * @extends {Error} - */ -goog.debug.Error = function(opt_msg) { - - // Attempt to ensure there is a stack trace. - if (Error.captureStackTrace) { - Error.captureStackTrace(this, goog.debug.Error); - } else { - var stack = new Error().stack; - if (stack) { - this.stack = stack; - } - } - - if (opt_msg) { - this.message = String(opt_msg); - } -}; -goog.inherits(goog.debug.Error, Error); - - -/** @override */ -goog.debug.Error.prototype.name = 'CustomError'; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/errorhandler.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/errorhandler.js deleted file mode 100644 index 3d8b004..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/errorhandler.js +++ /dev/null @@ -1,367 +0,0 @@ -// 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 Error handling utilities. - * - */ - -goog.provide('goog.debug.ErrorHandler'); -goog.provide('goog.debug.ErrorHandler.ProtectedFunctionError'); - -goog.require('goog.Disposable'); -goog.require('goog.asserts'); -goog.require('goog.debug'); -goog.require('goog.debug.EntryPointMonitor'); -goog.require('goog.debug.Error'); -goog.require('goog.debug.Trace'); - - - -/** - * The ErrorHandler can be used to to wrap functions with a try/catch - * statement. If an exception is thrown, the given error handler function will - * be called. - * - * When this object is disposed, it will stop handling exceptions and tracing. - * It will also try to restore window.setTimeout and window.setInterval - * if it wrapped them. Notice that in the general case, it is not technically - * possible to remove the wrapper, because functions have no knowledge of - * what they have been assigned to. So the app is responsible for other - * forms of unwrapping. - * - * @param {Function} handler Handler for exceptions. - * @constructor - * @extends {goog.Disposable} - * @implements {goog.debug.EntryPointMonitor} - */ -goog.debug.ErrorHandler = function(handler) { - goog.debug.ErrorHandler.base(this, 'constructor'); - - /** - * Handler for exceptions, which can do logging, reporting, etc. - * @type {Function} - * @private - */ - this.errorHandlerFn_ = handler; - - /** - * Whether errors should be wrapped in - * goog.debug.ErrorHandler.ProtectedFunctionError before rethrowing. - * @type {boolean} - * @private - */ - this.wrapErrors_ = true; // TODO(user) Change default. - - /** - * Whether to add a prefix to all error messages. The prefix is - * goog.debug.ErrorHandler.ProtectedFunctionError.MESSAGE_PREFIX. This option - * only has an effect if this.wrapErrors_ is set to false. - * @type {boolean} - * @private - */ - this.prefixErrorMessages_ = false; -}; -goog.inherits(goog.debug.ErrorHandler, goog.Disposable); - - -/** - * Whether to add tracers when instrumenting entry points. - * @type {boolean} - * @private - */ -goog.debug.ErrorHandler.prototype.addTracersToProtectedFunctions_ = false; - - -/** - * Enable tracers when instrumenting entry points. - * @param {boolean} newVal See above. - */ -goog.debug.ErrorHandler.prototype.setAddTracersToProtectedFunctions = - function(newVal) { - this.addTracersToProtectedFunctions_ = newVal; -}; - - -/** @override */ -goog.debug.ErrorHandler.prototype.wrap = function(fn) { - return this.protectEntryPoint(goog.asserts.assertFunction(fn)); -}; - - -/** @override */ -goog.debug.ErrorHandler.prototype.unwrap = function(fn) { - goog.asserts.assertFunction(fn); - return fn[this.getFunctionIndex_(false)] || fn; -}; - - -/** - * Private helper function to return a span that can be clicked on to display - * an alert with the current stack trace. Newlines are replaced with a - * placeholder so that they will not be html-escaped. - * @param {string} stackTrace The stack trace to create a span for. - * @return {string} A span which can be clicked on to show the stack trace. - * @private - */ -goog.debug.ErrorHandler.prototype.getStackTraceHolder_ = function(stackTrace) { - var buffer = []; - buffer.push('##PE_STACK_START##'); - buffer.push(stackTrace.replace(/(\r\n|\r|\n)/g, '##STACK_BR##')); - buffer.push('##PE_STACK_END##'); - return buffer.join(''); -}; - - -/** - * Get the index for a function. Used for internal indexing. - * @param {boolean} wrapper True for the wrapper; false for the wrapped. - * @return {string} The index where we should store the function in its - * wrapper/wrapped function. - * @private - */ -goog.debug.ErrorHandler.prototype.getFunctionIndex_ = function(wrapper) { - return (wrapper ? '__wrapper_' : '__protected_') + goog.getUid(this) + '__'; -}; - - -/** - * Installs exception protection for an entry point function. When an exception - * is thrown from a protected function, a handler will be invoked to handle it. - * - * @param {Function} fn An entry point function to be protected. - * @return {!Function} A protected wrapper function that calls the entry point - * function. - */ -goog.debug.ErrorHandler.prototype.protectEntryPoint = function(fn) { - var protectedFnName = this.getFunctionIndex_(true); - if (!fn[protectedFnName]) { - var wrapper = fn[protectedFnName] = this.getProtectedFunction(fn); - wrapper[this.getFunctionIndex_(false)] = fn; - } - return fn[protectedFnName]; -}; - - -/** - * Helps {@link #protectEntryPoint} by actually creating the protected - * wrapper function, after {@link #protectEntryPoint} determines that one does - * not already exist for the given function. Can be overriden by subclasses - * that may want to implement different error handling, or add additional - * entry point hooks. - * @param {!Function} fn An entry point function to be protected. - * @return {!Function} protected wrapper function. - * @protected - */ -goog.debug.ErrorHandler.prototype.getProtectedFunction = function(fn) { - var that = this; - var tracers = this.addTracersToProtectedFunctions_; - if (tracers) { - var stackTrace = goog.debug.getStacktraceSimple(15); - } - var googDebugErrorHandlerProtectedFunction = function() { - if (that.isDisposed()) { - return fn.apply(this, arguments); - } - - if (tracers) { - var tracer = goog.debug.Trace.startTracer('protectedEntryPoint: ' + - that.getStackTraceHolder_(stackTrace)); - } - try { - return fn.apply(this, arguments); - } catch (e) { - that.errorHandlerFn_(e); - if (!that.wrapErrors_) { - // Add the prefix to the existing message. - if (that.prefixErrorMessages_) { - if (typeof e === 'object') { - e.message = - goog.debug.ErrorHandler.ProtectedFunctionError.MESSAGE_PREFIX + - e.message; - } else { - e = goog.debug.ErrorHandler.ProtectedFunctionError.MESSAGE_PREFIX + - e; - } - } - if (goog.DEBUG) { - // Work around for https://code.google.com/p/v8/issues/detail?id=2625 - // and https://code.google.com/p/chromium/issues/detail?id=237059 - // Custom errors and errors with custom stack traces show the wrong - // stack trace - // If it has a stack and Error.captureStackTrace is supported (only - // supported in V8 as of May 2013) log the stack to the console. - if (e && e.stack && Error.captureStackTrace && - goog.global['console']) { - goog.global['console']['error'](e.message, e.stack); - } - } - // Re-throw original error. This is great for debugging as it makes - // browser JS dev consoles show the correct error and stack trace. - throw e; - } - // Re-throw it since this may be expected by the caller. - throw new goog.debug.ErrorHandler.ProtectedFunctionError(e); - } finally { - if (tracers) { - goog.debug.Trace.stopTracer(tracer); - } - } - }; - googDebugErrorHandlerProtectedFunction[this.getFunctionIndex_(false)] = fn; - return googDebugErrorHandlerProtectedFunction; -}; - - -// TODO(mknichel): Allow these functions to take in the window to protect. -/** - * Installs exception protection for window.setTimeout to handle exceptions. - */ -goog.debug.ErrorHandler.prototype.protectWindowSetTimeout = - function() { - this.protectWindowFunctionsHelper_('setTimeout'); -}; - - -/** - * Install exception protection for window.setInterval to handle exceptions. - */ -goog.debug.ErrorHandler.prototype.protectWindowSetInterval = - function() { - this.protectWindowFunctionsHelper_('setInterval'); -}; - - -/** - * Install exception protection for window.requestAnimationFrame to handle - * exceptions. - */ -goog.debug.ErrorHandler.prototype.protectWindowRequestAnimationFrame = - function() { - var win = goog.getObjectByName('window'); - var fnNames = [ - 'requestAnimationFrame', - 'mozRequestAnimationFrame', - 'webkitAnimationFrame', - 'msRequestAnimationFrame' - ]; - for (var i = 0; i < fnNames.length; i++) { - var fnName = fnNames[i]; - if (fnNames[i] in win) { - this.protectWindowFunctionsHelper_(fnName); - } - } -}; - - -/** - * Helper function for protecting a function that causes a function to be - * asynchronously called, for example setTimeout or requestAnimationFrame. - * @param {string} fnName The name of the function to protect. - * @private - */ -goog.debug.ErrorHandler.prototype.protectWindowFunctionsHelper_ = - function(fnName) { - var win = goog.getObjectByName('window'); - var originalFn = win[fnName]; - var that = this; - win[fnName] = function(fn, time) { - // Don't try to protect strings. In theory, we could try to globalEval - // the string, but this seems to lead to permission errors on IE6. - if (goog.isString(fn)) { - fn = goog.partial(goog.globalEval, fn); - } - fn = that.protectEntryPoint(fn); - - // IE doesn't support .call for setInterval/setTimeout, but it - // also doesn't care what "this" is, so we can just call the - // original function directly - if (originalFn.call) { - return originalFn.call(this, fn, time); - } else { - return originalFn(fn, time); - } - }; - win[fnName][this.getFunctionIndex_(false)] = originalFn; -}; - - -/** - * Set whether to wrap errors that occur in protected functions in a - * goog.debug.ErrorHandler.ProtectedFunctionError. - * @param {boolean} wrapErrors Whether to wrap errors. - */ -goog.debug.ErrorHandler.prototype.setWrapErrors = function(wrapErrors) { - this.wrapErrors_ = wrapErrors; -}; - - -/** - * Set whether to add a prefix to all error messages that occur in protected - * functions. - * @param {boolean} prefixErrorMessages Whether to add a prefix to error - * messages. - */ -goog.debug.ErrorHandler.prototype.setPrefixErrorMessages = - function(prefixErrorMessages) { - this.prefixErrorMessages_ = prefixErrorMessages; -}; - - -/** @override */ -goog.debug.ErrorHandler.prototype.disposeInternal = function() { - // Try to unwrap window.setTimeout and window.setInterval. - var win = goog.getObjectByName('window'); - win.setTimeout = this.unwrap(win.setTimeout); - win.setInterval = this.unwrap(win.setInterval); - - goog.debug.ErrorHandler.base(this, 'disposeInternal'); -}; - - - -/** - * Error thrown to the caller of a protected entry point if the entry point - * throws an error. - * @param {*} cause The error thrown by the entry point. - * @constructor - * @extends {goog.debug.Error} - * @final - */ -goog.debug.ErrorHandler.ProtectedFunctionError = function(cause) { - var message = goog.debug.ErrorHandler.ProtectedFunctionError.MESSAGE_PREFIX + - (cause && cause.message ? String(cause.message) : String(cause)); - goog.debug.ErrorHandler.ProtectedFunctionError.base( - this, 'constructor', message); - - /** - * The error thrown by the entry point. - * @type {*} - */ - this.cause = cause; - - var stack = cause && cause.stack; - if (stack && goog.isString(stack)) { - this.stack = /** @type {string} */ (stack); - } -}; -goog.inherits(goog.debug.ErrorHandler.ProtectedFunctionError, goog.debug.Error); - - -/** - * Text to prefix the message with. - * @type {string} - */ -goog.debug.ErrorHandler.ProtectedFunctionError.MESSAGE_PREFIX = - 'Error in protected function: '; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logbuffer.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logbuffer.js deleted file mode 100644 index 7e3de4b..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logbuffer.js +++ /dev/null @@ -1,148 +0,0 @@ -// 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 A buffer for log records. The purpose of this is to improve - * logging performance by re-using old objects when the buffer becomes full and - * to eliminate the need for each app to implement their own log buffer. The - * disadvantage to doing this is that log handlers cannot maintain references to - * log records and expect that they are not overwriten at a later point. - * - * @author agrieve@google.com (Andrew Grieve) - */ - -goog.provide('goog.debug.LogBuffer'); - -goog.require('goog.asserts'); -goog.require('goog.debug.LogRecord'); - - - -/** - * Creates the log buffer. - * @constructor - * @final - */ -goog.debug.LogBuffer = function() { - goog.asserts.assert(goog.debug.LogBuffer.isBufferingEnabled(), - 'Cannot use goog.debug.LogBuffer without defining ' + - 'goog.debug.LogBuffer.CAPACITY.'); - this.clear(); -}; - - -/** - * A static method that always returns the same instance of LogBuffer. - * @return {!goog.debug.LogBuffer} The LogBuffer singleton instance. - */ -goog.debug.LogBuffer.getInstance = function() { - if (!goog.debug.LogBuffer.instance_) { - // This function is written with the return statement after the assignment - // to avoid the jscompiler StripCode bug described in http://b/2608064. - // After that bug is fixed this can be refactored. - goog.debug.LogBuffer.instance_ = new goog.debug.LogBuffer(); - } - return goog.debug.LogBuffer.instance_; -}; - - -/** - * @define {number} The number of log records to buffer. 0 means disable - * buffering. - */ -goog.define('goog.debug.LogBuffer.CAPACITY', 0); - - -/** - * The array to store the records. - * @type {!Array<!goog.debug.LogRecord|undefined>} - * @private - */ -goog.debug.LogBuffer.prototype.buffer_; - - -/** - * The index of the most recently added record or -1 if there are no records. - * @type {number} - * @private - */ -goog.debug.LogBuffer.prototype.curIndex_; - - -/** - * Whether the buffer is at capacity. - * @type {boolean} - * @private - */ -goog.debug.LogBuffer.prototype.isFull_; - - -/** - * Adds a log record to the buffer, possibly overwriting the oldest record. - * @param {goog.debug.Logger.Level} level One of the level identifiers. - * @param {string} msg The string message. - * @param {string} loggerName The name of the source logger. - * @return {!goog.debug.LogRecord} The log record. - */ -goog.debug.LogBuffer.prototype.addRecord = function(level, msg, loggerName) { - var curIndex = (this.curIndex_ + 1) % goog.debug.LogBuffer.CAPACITY; - this.curIndex_ = curIndex; - if (this.isFull_) { - var ret = this.buffer_[curIndex]; - ret.reset(level, msg, loggerName); - return ret; - } - this.isFull_ = curIndex == goog.debug.LogBuffer.CAPACITY - 1; - return this.buffer_[curIndex] = - new goog.debug.LogRecord(level, msg, loggerName); -}; - - -/** - * @return {boolean} Whether the log buffer is enabled. - */ -goog.debug.LogBuffer.isBufferingEnabled = function() { - return goog.debug.LogBuffer.CAPACITY > 0; -}; - - -/** - * Removes all buffered log records. - */ -goog.debug.LogBuffer.prototype.clear = function() { - this.buffer_ = new Array(goog.debug.LogBuffer.CAPACITY); - this.curIndex_ = -1; - this.isFull_ = false; -}; - - -/** - * Calls the given function for each buffered log record, starting with the - * oldest one. - * @param {function(!goog.debug.LogRecord)} func The function to call. - */ -goog.debug.LogBuffer.prototype.forEachRecord = function(func) { - var buffer = this.buffer_; - // Corner case: no records. - if (!buffer[0]) { - return; - } - var curIndex = this.curIndex_; - var i = this.isFull_ ? curIndex : -1; - do { - i = (i + 1) % goog.debug.LogBuffer.CAPACITY; - func(/** @type {!goog.debug.LogRecord} */ (buffer[i])); - } while (i != curIndex); -}; - diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logger.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logger.js deleted file mode 100644 index 5ced90a..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logger.js +++ /dev/null @@ -1,873 +0,0 @@ -// 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 Definition of the Logger class. Please minimize dependencies - * this file has on other closure classes as any dependency it takes won't be - * able to use the logging infrastructure. - * - * @see ../demos/debug.html - */ - -goog.provide('goog.debug.LogManager'); -goog.provide('goog.debug.Loggable'); -goog.provide('goog.debug.Logger'); -goog.provide('goog.debug.Logger.Level'); - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.debug'); -goog.require('goog.debug.LogBuffer'); -goog.require('goog.debug.LogRecord'); - - -/** - * A message value that can be handled by a Logger. - * - * Functions are treated like callbacks, but are only called when the event's - * log level is enabled. This is useful for logging messages that are expensive - * to construct. - * - * @typedef {string|function(): string} - */ -goog.debug.Loggable; - - - -/** - * The Logger is an object used for logging debug messages. Loggers are - * normally named, using a hierarchical dot-separated namespace. Logger names - * can be arbitrary strings, but they should normally be based on the package - * name or class name of the logged component, such as goog.net.BrowserChannel. - * - * The Logger object is loosely based on the java class - * java.util.logging.Logger. It supports different levels of filtering for - * different loggers. - * - * The logger object should never be instantiated by application code. It - * should always use the goog.debug.Logger.getLogger function. - * - * @constructor - * @param {string} name The name of the Logger. - * @final - */ -goog.debug.Logger = function(name) { - /** - * Name of the Logger. Generally a dot-separated namespace - * @private {string} - */ - this.name_ = name; - - /** - * Parent Logger. - * @private {goog.debug.Logger} - */ - this.parent_ = null; - - /** - * Level that this logger only filters above. Null indicates it should - * inherit from the parent. - * @private {goog.debug.Logger.Level} - */ - this.level_ = null; - - /** - * Map of children loggers. The keys are the leaf names of the children and - * the values are the child loggers. - * @private {Object} - */ - this.children_ = null; - - /** - * Handlers that are listening to this logger. - * @private {Array<Function>} - */ - this.handlers_ = null; -}; - - -/** @const */ -goog.debug.Logger.ROOT_LOGGER_NAME = ''; - - -/** - * @define {boolean} Toggles whether loggers other than the root logger can have - * log handlers attached to them and whether they can have their log level - * set. Logging is a bit faster when this is set to false. - */ -goog.define('goog.debug.Logger.ENABLE_HIERARCHY', true); - - -if (!goog.debug.Logger.ENABLE_HIERARCHY) { - /** - * @type {!Array<Function>} - * @private - */ - goog.debug.Logger.rootHandlers_ = []; - - - /** - * @type {goog.debug.Logger.Level} - * @private - */ - goog.debug.Logger.rootLevel_; -} - - - -/** - * The Level class defines a set of standard logging levels that - * can be used to control logging output. The logging Level objects - * are ordered and are specified by ordered integers. Enabling logging - * at a given level also enables logging at all higher levels. - * <p> - * Clients should normally use the predefined Level constants such - * as Level.SEVERE. - * <p> - * The levels in descending order are: - * <ul> - * <li>SEVERE (highest value) - * <li>WARNING - * <li>INFO - * <li>CONFIG - * <li>FINE - * <li>FINER - * <li>FINEST (lowest value) - * </ul> - * In addition there is a level OFF that can be used to turn - * off logging, and a level ALL that can be used to enable - * logging of all messages. - * - * @param {string} name The name of the level. - * @param {number} value The numeric value of the level. - * @constructor - * @final - */ -goog.debug.Logger.Level = function(name, value) { - /** - * The name of the level - * @type {string} - */ - this.name = name; - - /** - * The numeric value of the level - * @type {number} - */ - this.value = value; -}; - - -/** - * @return {string} String representation of the logger level. - * @override - */ -goog.debug.Logger.Level.prototype.toString = function() { - return this.name; -}; - - -/** - * OFF is a special level that can be used to turn off logging. - * This level is initialized to <CODE>Infinity</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.OFF = - new goog.debug.Logger.Level('OFF', Infinity); - - -/** - * SHOUT is a message level for extra debugging loudness. - * This level is initialized to <CODE>1200</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.SHOUT = new goog.debug.Logger.Level('SHOUT', 1200); - - -/** - * SEVERE is a message level indicating a serious failure. - * This level is initialized to <CODE>1000</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.SEVERE = new goog.debug.Logger.Level('SEVERE', 1000); - - -/** - * WARNING is a message level indicating a potential problem. - * This level is initialized to <CODE>900</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.WARNING = new goog.debug.Logger.Level('WARNING', 900); - - -/** - * INFO is a message level for informational messages. - * This level is initialized to <CODE>800</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.INFO = new goog.debug.Logger.Level('INFO', 800); - - -/** - * CONFIG is a message level for static configuration messages. - * This level is initialized to <CODE>700</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.CONFIG = new goog.debug.Logger.Level('CONFIG', 700); - - -/** - * FINE is a message level providing tracing information. - * This level is initialized to <CODE>500</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.FINE = new goog.debug.Logger.Level('FINE', 500); - - -/** - * FINER indicates a fairly detailed tracing message. - * This level is initialized to <CODE>400</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.FINER = new goog.debug.Logger.Level('FINER', 400); - -/** - * FINEST indicates a highly detailed tracing message. - * This level is initialized to <CODE>300</CODE>. - * @type {!goog.debug.Logger.Level} - */ - -goog.debug.Logger.Level.FINEST = new goog.debug.Logger.Level('FINEST', 300); - - -/** - * ALL indicates that all messages should be logged. - * This level is initialized to <CODE>0</CODE>. - * @type {!goog.debug.Logger.Level} - */ -goog.debug.Logger.Level.ALL = new goog.debug.Logger.Level('ALL', 0); - - -/** - * The predefined levels. - * @type {!Array<!goog.debug.Logger.Level>} - * @final - */ -goog.debug.Logger.Level.PREDEFINED_LEVELS = [ - goog.debug.Logger.Level.OFF, - goog.debug.Logger.Level.SHOUT, - goog.debug.Logger.Level.SEVERE, - goog.debug.Logger.Level.WARNING, - goog.debug.Logger.Level.INFO, - goog.debug.Logger.Level.CONFIG, - goog.debug.Logger.Level.FINE, - goog.debug.Logger.Level.FINER, - goog.debug.Logger.Level.FINEST, - goog.debug.Logger.Level.ALL]; - - -/** - * A lookup map used to find the level object based on the name or value of - * the level object. - * @type {Object} - * @private - */ -goog.debug.Logger.Level.predefinedLevelsCache_ = null; - - -/** - * Creates the predefined levels cache and populates it. - * @private - */ -goog.debug.Logger.Level.createPredefinedLevelsCache_ = function() { - goog.debug.Logger.Level.predefinedLevelsCache_ = {}; - for (var i = 0, level; level = goog.debug.Logger.Level.PREDEFINED_LEVELS[i]; - i++) { - goog.debug.Logger.Level.predefinedLevelsCache_[level.value] = level; - goog.debug.Logger.Level.predefinedLevelsCache_[level.name] = level; - } -}; - - -/** - * Gets the predefined level with the given name. - * @param {string} name The name of the level. - * @return {goog.debug.Logger.Level} The level, or null if none found. - */ -goog.debug.Logger.Level.getPredefinedLevel = function(name) { - if (!goog.debug.Logger.Level.predefinedLevelsCache_) { - goog.debug.Logger.Level.createPredefinedLevelsCache_(); - } - - return goog.debug.Logger.Level.predefinedLevelsCache_[name] || null; -}; - - -/** - * Gets the highest predefined level <= #value. - * @param {number} value Level value. - * @return {goog.debug.Logger.Level} The level, or null if none found. - */ -goog.debug.Logger.Level.getPredefinedLevelByValue = function(value) { - if (!goog.debug.Logger.Level.predefinedLevelsCache_) { - goog.debug.Logger.Level.createPredefinedLevelsCache_(); - } - - if (value in goog.debug.Logger.Level.predefinedLevelsCache_) { - return goog.debug.Logger.Level.predefinedLevelsCache_[value]; - } - - for (var i = 0; i < goog.debug.Logger.Level.PREDEFINED_LEVELS.length; ++i) { - var level = goog.debug.Logger.Level.PREDEFINED_LEVELS[i]; - if (level.value <= value) { - return level; - } - } - return null; -}; - - -/** - * Finds or creates a logger for a named subsystem. If a logger has already been - * created with the given name it is returned. Otherwise a new logger is - * created. If a new logger is created its log level will be configured based - * on the LogManager configuration and it will configured to also send logging - * output to its parent's handlers. It will be registered in the LogManager - * global namespace. - * - * @param {string} name A name for the logger. This should be a dot-separated - * name and should normally be based on the package name or class name of the - * subsystem, such as goog.net.BrowserChannel. - * @return {!goog.debug.Logger} The named logger. - * @deprecated use goog.log instead. http://go/goog-debug-logger-deprecated - */ -goog.debug.Logger.getLogger = function(name) { - return goog.debug.LogManager.getLogger(name); -}; - - -/** - * Logs a message to profiling tools, if available. - * {@see https://developers.google.com/web-toolkit/speedtracer/logging-api} - * {@see http://msdn.microsoft.com/en-us/library/dd433074(VS.85).aspx} - * @param {string} msg The message to log. - */ -goog.debug.Logger.logToProfilers = function(msg) { - // Using goog.global, as loggers might be used in window-less contexts. - if (goog.global['console']) { - if (goog.global['console']['timeStamp']) { - // Logs a message to Firebug, Web Inspector, SpeedTracer, etc. - goog.global['console']['timeStamp'](msg); - } else if (goog.global['console']['markTimeline']) { - // TODO(user): markTimeline is deprecated. Drop this else clause entirely - // after Chrome M14 hits stable. - goog.global['console']['markTimeline'](msg); - } - } - - if (goog.global['msWriteProfilerMark']) { - // Logs a message to the Microsoft profiler - goog.global['msWriteProfilerMark'](msg); - } -}; - - -/** - * Gets the name of this logger. - * @return {string} The name of this logger. - */ -goog.debug.Logger.prototype.getName = function() { - return this.name_; -}; - - -/** - * Adds a handler to the logger. This doesn't use the event system because - * we want to be able to add logging to the event system. - * @param {Function} handler Handler function to add. - */ -goog.debug.Logger.prototype.addHandler = function(handler) { - if (goog.debug.LOGGING_ENABLED) { - if (goog.debug.Logger.ENABLE_HIERARCHY) { - if (!this.handlers_) { - this.handlers_ = []; - } - this.handlers_.push(handler); - } else { - goog.asserts.assert(!this.name_, - 'Cannot call addHandler on a non-root logger when ' + - 'goog.debug.Logger.ENABLE_HIERARCHY is false.'); - goog.debug.Logger.rootHandlers_.push(handler); - } - } -}; - - -/** - * Removes a handler from the logger. This doesn't use the event system because - * we want to be able to add logging to the event system. - * @param {Function} handler Handler function to remove. - * @return {boolean} Whether the handler was removed. - */ -goog.debug.Logger.prototype.removeHandler = function(handler) { - if (goog.debug.LOGGING_ENABLED) { - var handlers = goog.debug.Logger.ENABLE_HIERARCHY ? this.handlers_ : - goog.debug.Logger.rootHandlers_; - return !!handlers && goog.array.remove(handlers, handler); - } else { - return false; - } -}; - - -/** - * Returns the parent of this logger. - * @return {goog.debug.Logger} The parent logger or null if this is the root. - */ -goog.debug.Logger.prototype.getParent = function() { - return this.parent_; -}; - - -/** - * Returns the children of this logger as a map of the child name to the logger. - * @return {!Object} The map where the keys are the child leaf names and the - * values are the Logger objects. - */ -goog.debug.Logger.prototype.getChildren = function() { - if (!this.children_) { - this.children_ = {}; - } - return this.children_; -}; - - -/** - * Set the log level specifying which message levels will be logged by this - * logger. Message levels lower than this value will be discarded. - * The level value Level.OFF can be used to turn off logging. If the new level - * is null, it means that this node should inherit its level from its nearest - * ancestor with a specific (non-null) level value. - * - * @param {goog.debug.Logger.Level} level The new level. - */ -goog.debug.Logger.prototype.setLevel = function(level) { - if (goog.debug.LOGGING_ENABLED) { - if (goog.debug.Logger.ENABLE_HIERARCHY) { - this.level_ = level; - } else { - goog.asserts.assert(!this.name_, - 'Cannot call setLevel() on a non-root logger when ' + - 'goog.debug.Logger.ENABLE_HIERARCHY is false.'); - goog.debug.Logger.rootLevel_ = level; - } - } -}; - - -/** - * Gets the log level specifying which message levels will be logged by this - * logger. Message levels lower than this value will be discarded. - * The level value Level.OFF can be used to turn off logging. If the level - * is null, it means that this node should inherit its level from its nearest - * ancestor with a specific (non-null) level value. - * - * @return {goog.debug.Logger.Level} The level. - */ -goog.debug.Logger.prototype.getLevel = function() { - return goog.debug.LOGGING_ENABLED ? - this.level_ : goog.debug.Logger.Level.OFF; -}; - - -/** - * Returns the effective level of the logger based on its ancestors' levels. - * @return {goog.debug.Logger.Level} The level. - */ -goog.debug.Logger.prototype.getEffectiveLevel = function() { - if (!goog.debug.LOGGING_ENABLED) { - return goog.debug.Logger.Level.OFF; - } - - if (!goog.debug.Logger.ENABLE_HIERARCHY) { - return goog.debug.Logger.rootLevel_; - } - if (this.level_) { - return this.level_; - } - if (this.parent_) { - return this.parent_.getEffectiveLevel(); - } - goog.asserts.fail('Root logger has no level set.'); - return null; -}; - - -/** - * Checks if a message of the given level would actually be logged by this - * logger. This check is based on the Loggers effective level, which may be - * inherited from its parent. - * @param {goog.debug.Logger.Level} level The level to check. - * @return {boolean} Whether the message would be logged. - */ -goog.debug.Logger.prototype.isLoggable = function(level) { - return goog.debug.LOGGING_ENABLED && - level.value >= this.getEffectiveLevel().value; -}; - - -/** - * Logs a message. If the logger is currently enabled for the - * given message level then the given message is forwarded to all the - * registered output Handler objects. - * @param {goog.debug.Logger.Level} level One of the level identifiers. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error|Object=} opt_exception An exception associated with the - * message. - */ -goog.debug.Logger.prototype.log = function(level, msg, opt_exception) { - // java caches the effective level, not sure it's necessary here - if (goog.debug.LOGGING_ENABLED && this.isLoggable(level)) { - // Message callbacks can be useful when a log message is expensive to build. - if (goog.isFunction(msg)) { - msg = msg(); - } - - this.doLogRecord_(this.getLogRecord(level, msg, opt_exception)); - } -}; - - -/** - * Creates a new log record and adds the exception (if present) to it. - * @param {goog.debug.Logger.Level} level One of the level identifiers. - * @param {string} msg The string message. - * @param {Error|Object=} opt_exception An exception associated with the - * message. - * @return {!goog.debug.LogRecord} A log record. - * @suppress {es5Strict} - */ -goog.debug.Logger.prototype.getLogRecord = function( - level, msg, opt_exception) { - if (goog.debug.LogBuffer.isBufferingEnabled()) { - var logRecord = - goog.debug.LogBuffer.getInstance().addRecord(level, msg, this.name_); - } else { - logRecord = new goog.debug.LogRecord(level, String(msg), this.name_); - } - if (opt_exception) { - logRecord.setException(opt_exception); - } - return logRecord; -}; - - -/** - * Logs a message at the Logger.Level.SHOUT level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.shout = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.SHOUT, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Logger.Level.SEVERE level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.severe = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.SEVERE, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Logger.Level.WARNING level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.warning = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.WARNING, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Logger.Level.INFO level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.info = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.INFO, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Logger.Level.CONFIG level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.config = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.CONFIG, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Logger.Level.FINE level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.fine = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.FINE, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Logger.Level.FINER level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.finer = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.FINER, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Logger.Level.FINEST level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.debug.Logger.prototype.finest = function(msg, opt_exception) { - if (goog.debug.LOGGING_ENABLED) { - this.log(goog.debug.Logger.Level.FINEST, msg, opt_exception); - } -}; - - -/** - * Logs a LogRecord. If the logger is currently enabled for the - * given message level then the given message is forwarded to all the - * registered output Handler objects. - * @param {goog.debug.LogRecord} logRecord A log record to log. - */ -goog.debug.Logger.prototype.logRecord = function(logRecord) { - if (goog.debug.LOGGING_ENABLED && this.isLoggable(logRecord.getLevel())) { - this.doLogRecord_(logRecord); - } -}; - - -/** - * Logs a LogRecord. - * @param {goog.debug.LogRecord} logRecord A log record to log. - * @private - */ -goog.debug.Logger.prototype.doLogRecord_ = function(logRecord) { - goog.debug.Logger.logToProfilers('log:' + logRecord.getMessage()); - if (goog.debug.Logger.ENABLE_HIERARCHY) { - var target = this; - while (target) { - target.callPublish_(logRecord); - target = target.getParent(); - } - } else { - for (var i = 0, handler; handler = goog.debug.Logger.rootHandlers_[i++]; ) { - handler(logRecord); - } - } -}; - - -/** - * Calls the handlers for publish. - * @param {goog.debug.LogRecord} logRecord The log record to publish. - * @private - */ -goog.debug.Logger.prototype.callPublish_ = function(logRecord) { - if (this.handlers_) { - for (var i = 0, handler; handler = this.handlers_[i]; i++) { - handler(logRecord); - } - } -}; - - -/** - * Sets the parent of this logger. This is used for setting up the logger tree. - * @param {goog.debug.Logger} parent The parent logger. - * @private - */ -goog.debug.Logger.prototype.setParent_ = function(parent) { - this.parent_ = parent; -}; - - -/** - * Adds a child to this logger. This is used for setting up the logger tree. - * @param {string} name The leaf name of the child. - * @param {goog.debug.Logger} logger The child logger. - * @private - */ -goog.debug.Logger.prototype.addChild_ = function(name, logger) { - this.getChildren()[name] = logger; -}; - - -/** - * There is a single global LogManager object that is used to maintain a set of - * shared state about Loggers and log services. This is loosely based on the - * java class java.util.logging.LogManager. - * @const - */ -goog.debug.LogManager = {}; - - -/** - * Map of logger names to logger objects. - * - * @type {!Object<string, !goog.debug.Logger>} - * @private - */ -goog.debug.LogManager.loggers_ = {}; - - -/** - * The root logger which is the root of the logger tree. - * @type {goog.debug.Logger} - * @private - */ -goog.debug.LogManager.rootLogger_ = null; - - -/** - * Initializes the LogManager if not already initialized. - */ -goog.debug.LogManager.initialize = function() { - if (!goog.debug.LogManager.rootLogger_) { - goog.debug.LogManager.rootLogger_ = new goog.debug.Logger( - goog.debug.Logger.ROOT_LOGGER_NAME); - goog.debug.LogManager.loggers_[goog.debug.Logger.ROOT_LOGGER_NAME] = - goog.debug.LogManager.rootLogger_; - goog.debug.LogManager.rootLogger_.setLevel(goog.debug.Logger.Level.CONFIG); - } -}; - - -/** - * Returns all the loggers. - * @return {!Object<string, !goog.debug.Logger>} Map of logger names to logger - * objects. - */ -goog.debug.LogManager.getLoggers = function() { - return goog.debug.LogManager.loggers_; -}; - - -/** - * Returns the root of the logger tree namespace, the logger with the empty - * string as its name. - * - * @return {!goog.debug.Logger} The root logger. - */ -goog.debug.LogManager.getRoot = function() { - goog.debug.LogManager.initialize(); - return /** @type {!goog.debug.Logger} */ (goog.debug.LogManager.rootLogger_); -}; - - -/** - * Finds a named logger. - * - * @param {string} name A name for the logger. This should be a dot-separated - * name and should normally be based on the package name or class name of the - * subsystem, such as goog.net.BrowserChannel. - * @return {!goog.debug.Logger} The named logger. - */ -goog.debug.LogManager.getLogger = function(name) { - goog.debug.LogManager.initialize(); - var ret = goog.debug.LogManager.loggers_[name]; - return ret || goog.debug.LogManager.createLogger_(name); -}; - - -/** - * Creates a function that can be passed to goog.debug.catchErrors. The function - * will log all reported errors using the given logger. - * @param {goog.debug.Logger=} opt_logger The logger to log the errors to. - * Defaults to the root logger. - * @return {function(Object)} The created function. - */ -goog.debug.LogManager.createFunctionForCatchErrors = function(opt_logger) { - return function(info) { - var logger = opt_logger || goog.debug.LogManager.getRoot(); - logger.severe('Error: ' + info.message + ' (' + info.fileName + - ' @ Line: ' + info.line + ')'); - }; -}; - - -/** - * Creates the named logger. Will also create the parents of the named logger - * if they don't yet exist. - * @param {string} name The name of the logger. - * @return {!goog.debug.Logger} The named logger. - * @private - */ -goog.debug.LogManager.createLogger_ = function(name) { - // find parent logger - var logger = new goog.debug.Logger(name); - if (goog.debug.Logger.ENABLE_HIERARCHY) { - var lastDotIndex = name.lastIndexOf('.'); - var parentName = name.substr(0, lastDotIndex); - var leafName = name.substr(lastDotIndex + 1); - var parentLogger = goog.debug.LogManager.getLogger(parentName); - - // tell the parent about the child and the child about the parent - parentLogger.addChild_(leafName, logger); - logger.setParent_(parentLogger); - } - - goog.debug.LogManager.loggers_[name] = logger; - return logger; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logrecord.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logrecord.js deleted file mode 100644 index df5f982..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/logrecord.js +++ /dev/null @@ -1,242 +0,0 @@ -// 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 Definition of the LogRecord class. Please minimize - * dependencies this file has on other closure classes as any dependency it - * takes won't be able to use the logging infrastructure. - * - */ - -goog.provide('goog.debug.LogRecord'); - - - -/** - * LogRecord objects are used to pass logging requests between - * the logging framework and individual log Handlers. - * @constructor - * @param {goog.debug.Logger.Level} level One of the level identifiers. - * @param {string} msg The string message. - * @param {string} loggerName The name of the source logger. - * @param {number=} opt_time Time this log record was created if other than now. - * If 0, we use #goog.now. - * @param {number=} opt_sequenceNumber Sequence number of this log record. This - * should only be passed in when restoring a log record from persistence. - */ -goog.debug.LogRecord = function(level, msg, loggerName, - opt_time, opt_sequenceNumber) { - this.reset(level, msg, loggerName, opt_time, opt_sequenceNumber); -}; - - -/** - * Time the LogRecord was created. - * @type {number} - * @private - */ -goog.debug.LogRecord.prototype.time_; - - -/** - * Level of the LogRecord - * @type {goog.debug.Logger.Level} - * @private - */ -goog.debug.LogRecord.prototype.level_; - - -/** - * Message associated with the record - * @type {string} - * @private - */ -goog.debug.LogRecord.prototype.msg_; - - -/** - * Name of the logger that created the record. - * @type {string} - * @private - */ -goog.debug.LogRecord.prototype.loggerName_; - - -/** - * Sequence number for the LogRecord. Each record has a unique sequence number - * that is greater than all log records created before it. - * @type {number} - * @private - */ -goog.debug.LogRecord.prototype.sequenceNumber_ = 0; - - -/** - * Exception associated with the record - * @type {Object} - * @private - */ -goog.debug.LogRecord.prototype.exception_ = null; - - -/** - * @define {boolean} Whether to enable log sequence numbers. - */ -goog.define('goog.debug.LogRecord.ENABLE_SEQUENCE_NUMBERS', true); - - -/** - * A sequence counter for assigning increasing sequence numbers to LogRecord - * objects. - * @type {number} - * @private - */ -goog.debug.LogRecord.nextSequenceNumber_ = 0; - - -/** - * Sets all fields of the log record. - * @param {goog.debug.Logger.Level} level One of the level identifiers. - * @param {string} msg The string message. - * @param {string} loggerName The name of the source logger. - * @param {number=} opt_time Time this log record was created if other than now. - * If 0, we use #goog.now. - * @param {number=} opt_sequenceNumber Sequence number of this log record. This - * should only be passed in when restoring a log record from persistence. - */ -goog.debug.LogRecord.prototype.reset = function(level, msg, loggerName, - opt_time, opt_sequenceNumber) { - if (goog.debug.LogRecord.ENABLE_SEQUENCE_NUMBERS) { - this.sequenceNumber_ = typeof opt_sequenceNumber == 'number' ? - opt_sequenceNumber : goog.debug.LogRecord.nextSequenceNumber_++; - } - - this.time_ = opt_time || goog.now(); - this.level_ = level; - this.msg_ = msg; - this.loggerName_ = loggerName; - delete this.exception_; -}; - - -/** - * Get the source Logger's name. - * - * @return {string} source logger name (may be null). - */ -goog.debug.LogRecord.prototype.getLoggerName = function() { - return this.loggerName_; -}; - - -/** - * Get the exception that is part of the log record. - * - * @return {Object} the exception. - */ -goog.debug.LogRecord.prototype.getException = function() { - return this.exception_; -}; - - -/** - * Set the exception that is part of the log record. - * - * @param {Object} exception the exception. - */ -goog.debug.LogRecord.prototype.setException = function(exception) { - this.exception_ = exception; -}; - - -/** - * Get the source Logger's name. - * - * @param {string} loggerName source logger name (may be null). - */ -goog.debug.LogRecord.prototype.setLoggerName = function(loggerName) { - this.loggerName_ = loggerName; -}; - - -/** - * Get the logging message level, for example Level.SEVERE. - * @return {goog.debug.Logger.Level} the logging message level. - */ -goog.debug.LogRecord.prototype.getLevel = function() { - return this.level_; -}; - - -/** - * Set the logging message level, for example Level.SEVERE. - * @param {goog.debug.Logger.Level} level the logging message level. - */ -goog.debug.LogRecord.prototype.setLevel = function(level) { - this.level_ = level; -}; - - -/** - * Get the "raw" log message, before localization or formatting. - * - * @return {string} the raw message string. - */ -goog.debug.LogRecord.prototype.getMessage = function() { - return this.msg_; -}; - - -/** - * Set the "raw" log message, before localization or formatting. - * - * @param {string} msg the raw message string. - */ -goog.debug.LogRecord.prototype.setMessage = function(msg) { - this.msg_ = msg; -}; - - -/** - * Get event time in milliseconds since 1970. - * - * @return {number} event time in millis since 1970. - */ -goog.debug.LogRecord.prototype.getMillis = function() { - return this.time_; -}; - - -/** - * Set event time in milliseconds since 1970. - * - * @param {number} time event time in millis since 1970. - */ -goog.debug.LogRecord.prototype.setMillis = function(time) { - this.time_ = time; -}; - - -/** - * Get the sequence number. - * <p> - * Sequence numbers are normally assigned in the LogRecord - * constructor, which assigns unique sequence numbers to - * each new LogRecord in increasing order. - * @return {number} the sequence number. - */ -goog.debug.LogRecord.prototype.getSequenceNumber = function() { - return this.sequenceNumber_; -}; - diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/tracer.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/tracer.js deleted file mode 100644 index 474241d..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/debug/tracer.js +++ /dev/null @@ -1,725 +0,0 @@ -// 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 Definition of the Tracer class and associated classes. - * - * @see ../demos/tracer.html - */ - -goog.provide('goog.debug.Trace'); - -goog.require('goog.array'); -goog.require('goog.debug.Logger'); -goog.require('goog.iter'); -goog.require('goog.log'); -goog.require('goog.structs.Map'); -goog.require('goog.structs.SimplePool'); - - - -/** - * Class used for singleton goog.debug.Trace. Used for timing slow points in - * the code. Based on the java Tracer class but optimized for javascript. - * See com.google.common.tracing.Tracer. - * @constructor - * @private - */ -goog.debug.Trace_ = function() { - - /** - * Events in order. - * @type {Array<goog.debug.Trace_.Event_>} - * @private - */ - this.events_ = []; - - /** - * Outstanding events that have started but haven't yet ended. The keys are - * numeric ids and the values are goog.debug.Trace_.Event_ objects. - * @type {goog.structs.Map} - * @private - */ - this.outstandingEvents_ = new goog.structs.Map(); - - /** - * Start time of the event trace - * @type {number} - * @private - */ - this.startTime_ = 0; - - /** - * Cummulative overhead of calls to startTracer - * @type {number} - * @private - */ - this.tracerOverheadStart_ = 0; - - /** - * Cummulative overhead of calls to endTracer - * @type {number} - * @private - */ - this.tracerOverheadEnd_ = 0; - - /** - * Cummulative overhead of calls to addComment - * @type {number} - * @private - */ - this.tracerOverheadComment_ = 0; - - /** - * Keeps stats on different types of tracers. The keys are strings and the - * values are goog.debug.Stat - * @type {goog.structs.Map} - * @private - */ - this.stats_ = new goog.structs.Map(); - - /** - * Total number of traces created in the trace. - * @type {number} - * @private - */ - this.tracerCount_ = 0; - - /** - * Total number of comments created in the trace. - * @type {number} - * @private - */ - this.commentCount_ = 0; - - /** - * Next id to use for the trace. - * @type {number} - * @private - */ - this.nextId_ = 1; - - /** - * A pool for goog.debug.Trace_.Event_ objects so we don't keep creating and - * garbage collecting these (which is very expensive in IE6). - * @type {goog.structs.SimplePool} - * @private - */ - this.eventPool_ = new goog.structs.SimplePool(0, 4000); - this.eventPool_.createObject = function() { - return new goog.debug.Trace_.Event_(); - }; - - - /** - * A pool for goog.debug.Trace_.Stat_ objects so we don't keep creating and - * garbage collecting these (which is very expensive in IE6). - * @type {goog.structs.SimplePool} - * @private - */ - this.statPool_ = new goog.structs.SimplePool(0, 50); - this.statPool_.createObject = function() { - return new goog.debug.Trace_.Stat_(); - }; - - var that = this; - this.idPool_ = new goog.structs.SimplePool(0, 2000); - - // TODO(nicksantos): SimplePool is supposed to only return objects. - // Reconcile this so that we don't have to cast to number below. - this.idPool_.createObject = function() { - return String(that.nextId_++); - }; - this.idPool_.disposeObject = function(obj) {}; - - /** - * Default threshold below which a tracer shouldn't be reported - * @type {number} - * @private - */ - this.defaultThreshold_ = 3; -}; - - -/** - * Logger for the tracer - * @type {goog.log.Logger} - * @private - */ -goog.debug.Trace_.prototype.logger_ = - goog.log.getLogger('goog.debug.Trace'); - - -/** - * Maximum size of the trace before we discard events - * @type {number} - */ -goog.debug.Trace_.prototype.MAX_TRACE_SIZE = 1000; - - -/** - * Event type supported by tracer - * @enum {number} - */ -goog.debug.Trace_.EventType = { - /** - * Start event type - */ - START: 0, - - /** - * Stop event type - */ - STOP: 1, - - /** - * Comment event type - */ - COMMENT: 2 -}; - - - -/** - * Class to keep track of a stat of a single tracer type. Stores the count - * and cumulative time. - * @constructor - * @private - */ -goog.debug.Trace_.Stat_ = function() { - /** - * Number of tracers - * @type {number} - */ - this.count = 0; - - /** - * Cumulative time of traces - * @type {number} - */ - this.time = 0; - - /** - * Total number of allocations for this tracer type - * @type {number} - */ - this.varAlloc = 0; -}; - - -/** - * @type {string|null|undefined} - */ -goog.debug.Trace_.Stat_.prototype.type; - - -/** - * @return {string} A string describing the tracer stat. - * @override - */ -goog.debug.Trace_.Stat_.prototype.toString = function() { - var sb = []; - sb.push(this.type, ' ', this.count, ' (', Math.round(this.time * 10) / 10, - ' ms)'); - if (this.varAlloc) { - sb.push(' [VarAlloc = ', this.varAlloc, ']'); - } - return sb.join(''); -}; - - - -/** - * Private class used to encapsulate a single event, either the start or stop - * of a tracer. - * @constructor - * @private - */ -goog.debug.Trace_.Event_ = function() { - // the fields are different for different events - see usage in code -}; - - -/** - * @type {string|null|undefined} - */ -goog.debug.Trace_.Event_.prototype.type; - - -/** - * Returns a formatted string for the event. - * @param {number} startTime The start time of the trace to generate relative - * times. - * @param {number} prevTime The completion time of the previous event or -1. - * @param {string} indent Extra indent for the message - * if there was no previous event. - * @return {string} The formatted tracer string. - */ -goog.debug.Trace_.Event_.prototype.toTraceString = function(startTime, prevTime, - indent) { - var sb = []; - - if (prevTime == -1) { - sb.push(' '); - } else { - sb.push(goog.debug.Trace_.longToPaddedString_(this.eventTime - prevTime)); - } - - sb.push(' ', goog.debug.Trace_.formatTime_(this.eventTime - startTime)); - if (this.eventType == goog.debug.Trace_.EventType.START) { - sb.push(' Start '); - } else if (this.eventType == goog.debug.Trace_.EventType.STOP) { - sb.push(' Done '); - var delta = this.stopTime - this.startTime; - sb.push(goog.debug.Trace_.longToPaddedString_(delta), ' ms '); - } else { - sb.push(' Comment '); - } - - sb.push(indent, this); - if (this.totalVarAlloc > 0) { - sb.push('[VarAlloc ', this.totalVarAlloc, '] '); - } - return sb.join(''); -}; - - -/** - * @return {string} A string describing the tracer event. - * @override - */ -goog.debug.Trace_.Event_.prototype.toString = function() { - if (this.type == null) { - return this.comment; - } else { - return '[' + this.type + '] ' + this.comment; - } -}; - - -/** - * Add the ability to explicitly set the start time. This is useful for example - * for measuring initial load time where you can set a variable as soon as the - * main page of the app is loaded and then later call this function when the - * Tracer code has been loaded. - * @param {number} startTime The start time to set. - */ -goog.debug.Trace_.prototype.setStartTime = function(startTime) { - this.startTime_ = startTime; -}; - - -/** - * Initializes and resets the current trace - * @param {number} defaultThreshold The default threshold below which the - * tracer output will be supressed. Can be overridden on a per-Tracer basis. - */ -goog.debug.Trace_.prototype.initCurrentTrace = function(defaultThreshold) { - this.reset(defaultThreshold); -}; - - -/** - * Clears the current trace - */ -goog.debug.Trace_.prototype.clearCurrentTrace = function() { - this.reset(0); -}; - - -/** - * Resets the trace. - * @param {number} defaultThreshold The default threshold below which the - * tracer output will be supressed. Can be overridden on a per-Tracer basis. - */ -goog.debug.Trace_.prototype.reset = function(defaultThreshold) { - this.defaultThreshold_ = defaultThreshold; - - for (var i = 0; i < this.events_.length; i++) { - var id = /** @type {Object} */ (this.eventPool_).id; - if (id) { - this.idPool_.releaseObject(id); - } - this.eventPool_.releaseObject(this.events_[i]); - } - - this.events_.length = 0; - this.outstandingEvents_.clear(); - this.startTime_ = goog.debug.Trace_.now(); - this.tracerOverheadStart_ = 0; - this.tracerOverheadEnd_ = 0; - this.tracerOverheadComment_ = 0; - this.tracerCount_ = 0; - this.commentCount_ = 0; - - var keys = this.stats_.getKeys(); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var stat = this.stats_.get(key); - stat.count = 0; - stat.time = 0; - stat.varAlloc = 0; - this.statPool_.releaseObject(/** @type {Object} */ (stat)); - } - this.stats_.clear(); -}; - - -/** - * Starts a tracer - * @param {string} comment A comment used to identify the tracer. Does not - * need to be unique. - * @param {string=} opt_type Type used to identify the tracer. If a Trace is - * given a type (the first argument to the constructor) and multiple Traces - * are done on that type then a "TOTAL line will be produced showing the - * total number of traces and the sum of the time - * ("TOTAL Database 2 (37 ms)" in our example). These traces should be - * mutually exclusive or else the sum won't make sense (the time will - * be double counted if the second starts before the first ends). - * @return {number} The identifier for the tracer that should be passed to the - * the stopTracer method. - */ -goog.debug.Trace_.prototype.startTracer = function(comment, opt_type) { - var tracerStartTime = goog.debug.Trace_.now(); - var varAlloc = this.getTotalVarAlloc(); - var outstandingEventCount = this.outstandingEvents_.getCount(); - if (this.events_.length + outstandingEventCount > this.MAX_TRACE_SIZE) { - goog.log.warning(this.logger_, - 'Giant thread trace. Clearing to avoid memory leak.'); - // This is the more likely case. This usually means that we - // either forgot to clear the trace or else we are performing a - // very large number of events - if (this.events_.length > this.MAX_TRACE_SIZE / 2) { - for (var i = 0; i < this.events_.length; i++) { - var event = this.events_[i]; - if (event.id) { - this.idPool_.releaseObject(event.id); - } - this.eventPool_.releaseObject(event); - } - this.events_.length = 0; - } - - // This is less likely and probably indicates that a lot of traces - // aren't being closed. We want to avoid unnecessarily clearing - // this though in case the events do eventually finish. - if (outstandingEventCount > this.MAX_TRACE_SIZE / 2) { - this.outstandingEvents_.clear(); - } - } - - goog.debug.Logger.logToProfilers('Start : ' + comment); - - var event = /** @type {goog.debug.Trace_.Event_} */ ( - this.eventPool_.getObject()); - event.totalVarAlloc = varAlloc; - event.eventType = goog.debug.Trace_.EventType.START; - event.id = Number(this.idPool_.getObject()); - event.comment = comment; - event.type = opt_type; - this.events_.push(event); - this.outstandingEvents_.set(String(event.id), event); - this.tracerCount_++; - var now = goog.debug.Trace_.now(); - event.startTime = event.eventTime = now; - this.tracerOverheadStart_ += now - tracerStartTime; - return event.id; -}; - - -/** - * Stops a tracer - * @param {number|undefined|null} id The id of the tracer that is ending. - * @param {number=} opt_silenceThreshold Threshold below which the tracer is - * silenced. - * @return {?number} The elapsed time for the tracer or null if the tracer - * identitifer was not recognized. - */ -goog.debug.Trace_.prototype.stopTracer = function(id, opt_silenceThreshold) { - // this used to call goog.isDef(opt_silenceThreshold) but that causes an - // object allocation in IE for some reason (doh!). The following code doesn't - // cause an allocation - var now = goog.debug.Trace_.now(); - var silenceThreshold; - if (opt_silenceThreshold === 0) { - silenceThreshold = 0; - } else if (opt_silenceThreshold) { - silenceThreshold = opt_silenceThreshold; - } else { - silenceThreshold = this.defaultThreshold_; - } - - var startEvent = this.outstandingEvents_.get(String(id)); - if (startEvent == null) { - return null; - } - - this.outstandingEvents_.remove(String(id)); - - var stopEvent; - var elapsed = now - startEvent.startTime; - if (elapsed < silenceThreshold) { - var count = this.events_.length; - for (var i = count - 1; i >= 0; i--) { - var nextEvent = this.events_[i]; - if (nextEvent == startEvent) { - this.events_.splice(i, 1); - this.idPool_.releaseObject(startEvent.id); - this.eventPool_.releaseObject(/** @type {Object} */ (startEvent)); - break; - } - } - - } else { - stopEvent = /** @type {goog.debug.Trace_.Event_} */ ( - this.eventPool_.getObject()); - stopEvent.eventType = goog.debug.Trace_.EventType.STOP; - stopEvent.startTime = startEvent.startTime; - stopEvent.comment = startEvent.comment; - stopEvent.type = startEvent.type; - stopEvent.stopTime = stopEvent.eventTime = now; - - this.events_.push(stopEvent); - } - - var type = startEvent.type; - var stat = null; - if (type) { - stat = this.getStat_(type); - stat.count++; - stat.time += elapsed; - } - if (stopEvent) { - goog.debug.Logger.logToProfilers('Stop : ' + stopEvent.comment); - - stopEvent.totalVarAlloc = this.getTotalVarAlloc(); - - if (stat) { - stat.varAlloc += (stopEvent.totalVarAlloc - startEvent.totalVarAlloc); - } - } - var tracerFinishTime = goog.debug.Trace_.now(); - this.tracerOverheadEnd_ += tracerFinishTime - now; - return elapsed; -}; - - -/** - * Sets the ActiveX object that can be used to get GC tracing in IE6. - * @param {Object} gcTracer GCTracer ActiveX object. - */ -goog.debug.Trace_.prototype.setGcTracer = function(gcTracer) { - this.gcTracer_ = gcTracer; -}; - - -/** - * Returns the total number of allocations since the GC stats were reset. Only - * works in IE. - * @return {number} The number of allocaitons or -1 if not supported. - */ -goog.debug.Trace_.prototype.getTotalVarAlloc = function() { - var gcTracer = this.gcTracer_; - // isTracing is defined on the ActiveX object. - if (gcTracer && gcTracer['isTracing']()) { - return gcTracer['totalVarAlloc']; - } - return -1; -}; - - -/** - * Adds a comment to the trace. Makes it possible to see when a specific event - * happened in relation to the traces. - * @param {string} comment A comment that is inserted into the trace. - * @param {?string=} opt_type Type used to identify the tracer. If a comment is - * given a type and multiple comments are done on that type then a "TOTAL - * line will be produced showing the total number of comments of that type. - * @param {?number=} opt_timeStamp The timestamp to insert the comment. If not - * specified, the current time wil be used. - */ -goog.debug.Trace_.prototype.addComment = function(comment, opt_type, - opt_timeStamp) { - var now = goog.debug.Trace_.now(); - var timeStamp = opt_timeStamp ? opt_timeStamp : now; - - var eventComment = /** @type {goog.debug.Trace_.Event_} */ ( - this.eventPool_.getObject()); - eventComment.eventType = goog.debug.Trace_.EventType.COMMENT; - eventComment.eventTime = timeStamp; - eventComment.type = opt_type; - eventComment.comment = comment; - eventComment.totalVarAlloc = this.getTotalVarAlloc(); - this.commentCount_++; - - if (opt_timeStamp) { - var numEvents = this.events_.length; - for (var i = 0; i < numEvents; i++) { - var event = this.events_[i]; - var eventTime = event.eventTime; - - if (eventTime > timeStamp) { - goog.array.insertAt(this.events_, eventComment, i); - break; - } - } - if (i == numEvents) { - this.events_.push(eventComment); - } - } else { - this.events_.push(eventComment); - } - - var type = eventComment.type; - if (type) { - var stat = this.getStat_(type); - stat.count++; - } - - this.tracerOverheadComment_ += goog.debug.Trace_.now() - now; -}; - - -/** - * Gets a stat object for a particular type. The stat object is created if it - * hasn't yet been. - * @param {string} type The type of stat. - * @return {goog.debug.Trace_.Stat_} The stat object. - * @private - */ -goog.debug.Trace_.prototype.getStat_ = function(type) { - var stat = this.stats_.get(type); - if (!stat) { - stat = /** @type {goog.debug.Trace_.Event_} */ ( - this.statPool_.getObject()); - stat.type = type; - this.stats_.set(type, stat); - } - return /** @type {goog.debug.Trace_.Stat_} */(stat); -}; - - -/** - * Returns a formatted string for the current trace - * @return {string} A formatted string that shows the timings of the current - * trace. - */ -goog.debug.Trace_.prototype.getFormattedTrace = function() { - return this.toString(); -}; - - -/** - * Returns a formatted string that describes the thread trace. - * @return {string} A formatted string. - * @override - */ -goog.debug.Trace_.prototype.toString = function() { - var sb = []; - var etime = -1; - var indent = []; - for (var i = 0; i < this.events_.length; i++) { - var e = this.events_[i]; - if (e.eventType == goog.debug.Trace_.EventType.STOP) { - indent.pop(); - } - sb.push(' ', e.toTraceString(this.startTime_, etime, indent.join(''))); - etime = e.eventTime; - sb.push('\n'); - if (e.eventType == goog.debug.Trace_.EventType.START) { - indent.push('| '); - } - } - - if (this.outstandingEvents_.getCount() != 0) { - var now = goog.debug.Trace_.now(); - - sb.push(' Unstopped timers:\n'); - goog.iter.forEach(this.outstandingEvents_, function(startEvent) { - sb.push(' ', startEvent, ' (', now - startEvent.startTime, - ' ms, started at ', - goog.debug.Trace_.formatTime_(startEvent.startTime), - ')\n'); - }); - } - - var statKeys = this.stats_.getKeys(); - for (var i = 0; i < statKeys.length; i++) { - var stat = this.stats_.get(statKeys[i]); - if (stat.count > 1) { - sb.push(' TOTAL ', stat, '\n'); - } - } - - sb.push('Total tracers created ', this.tracerCount_, '\n', - 'Total comments created ', this.commentCount_, '\n', - 'Overhead start: ', this.tracerOverheadStart_, ' ms\n', - 'Overhead end: ', this.tracerOverheadEnd_, ' ms\n', - 'Overhead comment: ', this.tracerOverheadComment_, ' ms\n'); - - return sb.join(''); -}; - - -/** - * Converts 'v' to a string and pads it with up to 3 spaces for - * improved alignment. TODO there must be a better way - * @param {number} v A number. - * @return {string} A padded string. - * @private - */ -goog.debug.Trace_.longToPaddedString_ = function(v) { - v = Math.round(v); - // todo (pupius) - there should be a generic string in goog.string for this - var space = ''; - if (v < 1000) space = ' '; - if (v < 100) space = ' '; - if (v < 10) space = ' '; - return space + v; -}; - - -/** - * Return the sec.ms part of time (if time = "20:06:11.566", "11.566 - * @param {number} time The time in MS. - * @return {string} A formatted string as sec.ms'. - * @private - */ -goog.debug.Trace_.formatTime_ = function(time) { - time = Math.round(time); - var sec = (time / 1000) % 60; - var ms = time % 1000; - - // TODO their must be a nicer way to get zero padded integers - return String(100 + sec).substring(1, 3) + '.' + - String(1000 + ms).substring(1, 4); -}; - - -/** - * Returns the current time. Done through a wrapper function so it can be - * overridden by application code. Gmail has an ActiveX extension that provides - * higher precision timing info. - * @return {number} The current time in milliseconds. - */ -goog.debug.Trace_.now = function() { - return goog.now(); -}; - - -/** - * Singleton trace object - * @type {goog.debug.Trace_} - */ -goog.debug.Trace = new goog.debug.Trace_(); diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/disposable/disposable.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/disposable/disposable.js deleted file mode 100644 index d9c89d9..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/disposable/disposable.js +++ /dev/null @@ -1,307 +0,0 @@ -// 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 Implements the disposable interface. The dispose method is used - * to clean up references and resources. - * @author arv@google.com (Erik Arvidsson) - */ - - -goog.provide('goog.Disposable'); -/** @suppress {extraProvide} */ -goog.provide('goog.dispose'); -/** @suppress {extraProvide} */ -goog.provide('goog.disposeAll'); - -goog.require('goog.disposable.IDisposable'); - - - -/** - * Class that provides the basic implementation for disposable objects. If your - * class holds one or more references to COM objects, DOM nodes, or other - * disposable objects, it should extend this class or implement the disposable - * interface (defined in goog.disposable.IDisposable). - * @constructor - * @implements {goog.disposable.IDisposable} - */ -goog.Disposable = function() { - if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) { - if (goog.Disposable.INCLUDE_STACK_ON_CREATION) { - this.creationStack = new Error().stack; - } - goog.Disposable.instances_[goog.getUid(this)] = this; - } - // Support sealing - this.disposed_ = this.disposed_; - this.onDisposeCallbacks_ = this.onDisposeCallbacks_; -}; - - -/** - * @enum {number} Different monitoring modes for Disposable. - */ -goog.Disposable.MonitoringMode = { - /** - * No monitoring. - */ - OFF: 0, - /** - * Creating and disposing the goog.Disposable instances is monitored. All - * disposable objects need to call the {@code goog.Disposable} base - * constructor. The PERMANENT mode must be switched on before creating any - * goog.Disposable instances. - */ - PERMANENT: 1, - /** - * INTERACTIVE mode can be switched on and off on the fly without producing - * errors. It also doesn't warn if the disposable objects don't call the - * {@code goog.Disposable} base constructor. - */ - INTERACTIVE: 2 -}; - - -/** - * @define {number} The monitoring mode of the goog.Disposable - * instances. Default is OFF. Switching on the monitoring is only - * recommended for debugging because it has a significant impact on - * performance and memory usage. If switched off, the monitoring code - * compiles down to 0 bytes. - */ -goog.define('goog.Disposable.MONITORING_MODE', 0); - - -/** - * @define {boolean} Whether to attach creation stack to each created disposable - * instance; This is only relevant for when MonitoringMode != OFF. - */ -goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true); - - -/** - * Maps the unique ID of every undisposed {@code goog.Disposable} object to - * the object itself. - * @type {!Object<number, !goog.Disposable>} - * @private - */ -goog.Disposable.instances_ = {}; - - -/** - * @return {!Array<!goog.Disposable>} All {@code goog.Disposable} objects that - * haven't been disposed of. - */ -goog.Disposable.getUndisposedObjects = function() { - var ret = []; - for (var id in goog.Disposable.instances_) { - if (goog.Disposable.instances_.hasOwnProperty(id)) { - ret.push(goog.Disposable.instances_[Number(id)]); - } - } - return ret; -}; - - -/** - * Clears the registry of undisposed objects but doesn't dispose of them. - */ -goog.Disposable.clearUndisposedObjects = function() { - goog.Disposable.instances_ = {}; -}; - - -/** - * Whether the object has been disposed of. - * @type {boolean} - * @private - */ -goog.Disposable.prototype.disposed_ = false; - - -/** - * Callbacks to invoke when this object is disposed. - * @type {Array<!Function>} - * @private - */ -goog.Disposable.prototype.onDisposeCallbacks_; - - -/** - * If monitoring the goog.Disposable instances is enabled, stores the creation - * stack trace of the Disposable instance. - * @const {string} - */ -goog.Disposable.prototype.creationStack; - - -/** - * @return {boolean} Whether the object has been disposed of. - * @override - */ -goog.Disposable.prototype.isDisposed = function() { - return this.disposed_; -}; - - -/** - * @return {boolean} Whether the object has been disposed of. - * @deprecated Use {@link #isDisposed} instead. - */ -goog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed; - - -/** - * Disposes of the object. If the object hasn't already been disposed of, calls - * {@link #disposeInternal}. Classes that extend {@code goog.Disposable} should - * override {@link #disposeInternal} in order to delete references to COM - * objects, DOM nodes, and other disposable objects. Reentrant. - * - * @return {void} Nothing. - * @override - */ -goog.Disposable.prototype.dispose = function() { - if (!this.disposed_) { - // Set disposed_ to true first, in case during the chain of disposal this - // gets disposed recursively. - this.disposed_ = true; - this.disposeInternal(); - if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) { - var uid = goog.getUid(this); - if (goog.Disposable.MONITORING_MODE == - goog.Disposable.MonitoringMode.PERMANENT && - !goog.Disposable.instances_.hasOwnProperty(uid)) { - throw Error(this + ' did not call the goog.Disposable base ' + - 'constructor or was disposed of after a clearUndisposedObjects ' + - 'call'); - } - delete goog.Disposable.instances_[uid]; - } - } -}; - - -/** - * Associates a disposable object with this object so that they will be disposed - * together. - * @param {goog.disposable.IDisposable} disposable that will be disposed when - * this object is disposed. - */ -goog.Disposable.prototype.registerDisposable = function(disposable) { - this.addOnDisposeCallback(goog.partial(goog.dispose, disposable)); -}; - - -/** - * Invokes a callback function when this object is disposed. Callbacks are - * invoked in the order in which they were added. If a callback is added to - * an already disposed Disposable, it will be called immediately. - * @param {function(this:T):?} callback The callback function. - * @param {T=} opt_scope An optional scope to call the callback in. - * @template T - */ -goog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) { - if (this.disposed_) { - callback.call(opt_scope); - return; - } - if (!this.onDisposeCallbacks_) { - this.onDisposeCallbacks_ = []; - } - - this.onDisposeCallbacks_.push( - goog.isDef(opt_scope) ? goog.bind(callback, opt_scope) : callback); -}; - - -/** - * Deletes or nulls out any references to COM objects, DOM nodes, or other - * disposable objects. Classes that extend {@code goog.Disposable} should - * override this method. - * Not reentrant. To avoid calling it twice, it must only be called from the - * subclass' {@code disposeInternal} method. Everywhere else the public - * {@code dispose} method must be used. - * For example: - * <pre> - * mypackage.MyClass = function() { - * mypackage.MyClass.base(this, 'constructor'); - * // Constructor logic specific to MyClass. - * ... - * }; - * goog.inherits(mypackage.MyClass, goog.Disposable); - * - * mypackage.MyClass.prototype.disposeInternal = function() { - * // Dispose logic specific to MyClass. - * ... - * // Call superclass's disposeInternal at the end of the subclass's, like - * // in C++, to avoid hard-to-catch issues. - * mypackage.MyClass.base(this, 'disposeInternal'); - * }; - * </pre> - * @protected - */ -goog.Disposable.prototype.disposeInternal = function() { - if (this.onDisposeCallbacks_) { - while (this.onDisposeCallbacks_.length) { - this.onDisposeCallbacks_.shift()(); - } - } -}; - - -/** - * Returns True if we can verify the object is disposed. - * Calls {@code isDisposed} on the argument if it supports it. If obj - * is not an object with an isDisposed() method, return false. - * @param {*} obj The object to investigate. - * @return {boolean} True if we can verify the object is disposed. - */ -goog.Disposable.isDisposed = function(obj) { - if (obj && typeof obj.isDisposed == 'function') { - return obj.isDisposed(); - } - return false; -}; - - -/** - * Calls {@code dispose} on the argument if it supports it. If obj is not an - * object with a dispose() method, this is a no-op. - * @param {*} obj The object to dispose of. - */ -goog.dispose = function(obj) { - if (obj && typeof obj.dispose == 'function') { - obj.dispose(); - } -}; - - -/** - * Calls {@code dispose} on each member of the list that supports it. (If the - * member is an ArrayLike, then {@code goog.disposeAll()} will be called - * recursively on each of its members.) If the member is not an object with a - * {@code dispose()} method, then it is ignored. - * @param {...*} var_args The list. - */ -goog.disposeAll = function(var_args) { - for (var i = 0, len = arguments.length; i < len; ++i) { - var disposable = arguments[i]; - if (goog.isArrayLike(disposable)) { - goog.disposeAll.apply(null, disposable); - } else { - goog.dispose(disposable); - } - } -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/disposable/idisposable.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/disposable/idisposable.js deleted file mode 100644 index 917d17e..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/disposable/idisposable.js +++ /dev/null @@ -1,45 +0,0 @@ -// 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 Definition of the disposable interface. A disposable object - * has a dispose method to to clean up references and resources. - * @author nnaze@google.com (Nathan Naze) - */ - - -goog.provide('goog.disposable.IDisposable'); - - - -/** - * Interface for a disposable object. If a instance requires cleanup - * (references COM objects, DOM notes, or other disposable objects), it should - * implement this interface (it may subclass goog.Disposable). - * @interface - */ -goog.disposable.IDisposable = function() {}; - - -/** - * Disposes of the object and its resources. - * @return {void} Nothing. - */ -goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod; - - -/** - * @return {boolean} Whether the object has been disposed of. - */ -goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/browserfeature.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/browserfeature.js deleted file mode 100644 index 2c70cda..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/browserfeature.js +++ /dev/null @@ -1,72 +0,0 @@ -// 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 Browser capability checks for the dom package. - * - */ - - -goog.provide('goog.dom.BrowserFeature'); - -goog.require('goog.userAgent'); - - -/** - * Enum of browser capabilities. - * @enum {boolean} - */ -goog.dom.BrowserFeature = { - /** - * Whether attributes 'name' and 'type' can be added to an element after it's - * created. False in Internet Explorer prior to version 9. - */ - CAN_ADD_NAME_OR_TYPE_ATTRIBUTES: !goog.userAgent.IE || - goog.userAgent.isDocumentModeOrHigher(9), - - /** - * Whether we can use element.children to access an element's Element - * children. Available since Gecko 1.9.1, IE 9. (IE<9 also includes comment - * nodes in the collection.) - */ - CAN_USE_CHILDREN_ATTRIBUTE: !goog.userAgent.GECKO && !goog.userAgent.IE || - goog.userAgent.IE && goog.userAgent.isDocumentModeOrHigher(9) || - goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9.1'), - - /** - * Opera, Safari 3, and Internet Explorer 9 all support innerText but they - * include text nodes in script and style tags. Not document-mode-dependent. - */ - CAN_USE_INNER_TEXT: ( - goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9')), - - /** - * MSIE, Opera, and Safari>=4 support element.parentElement to access an - * element's parent if it is an Element. - */ - CAN_USE_PARENT_ELEMENT_PROPERTY: goog.userAgent.IE || goog.userAgent.OPERA || - goog.userAgent.WEBKIT, - - /** - * Whether NoScope elements need a scoped element written before them in - * innerHTML. - * MSDN: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx#1 - */ - INNER_HTML_NEEDS_SCOPED_ELEMENT: goog.userAgent.IE, - - /** - * Whether we use legacy IE range API. - */ - LEGACY_IE_RANGES: goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9) -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/classlist.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/classlist.js deleted file mode 100644 index dcbb7ed..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/classlist.js +++ /dev/null @@ -1,277 +0,0 @@ -// 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 Utilities for detecting, adding and removing classes. Prefer - * this over goog.dom.classes for new code since it attempts to use classList - * (DOMTokenList: http://dom.spec.whatwg.org/#domtokenlist) which is faster - * and requires less code. - * - * Note: these utilities are meant to operate on HTMLElements - * and may have unexpected behavior on elements with differing interfaces - * (such as SVGElements). - */ - - -goog.provide('goog.dom.classlist'); - -goog.require('goog.array'); - - -/** - * Override this define at build-time if you know your target supports it. - * @define {boolean} Whether to use the classList property (DOMTokenList). - */ -goog.define('goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST', false); - - -/** - * Gets an array-like object of class names on an element. - * @param {Element} element DOM node to get the classes of. - * @return {!goog.array.ArrayLike} Class names on {@code element}. - */ -goog.dom.classlist.get = function(element) { - if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) { - return element.classList; - } - - var className = element.className; - // Some types of elements don't have a className in IE (e.g. iframes). - // Furthermore, in Firefox, className is not a string when the element is - // an SVG element. - return goog.isString(className) && className.match(/\S+/g) || []; -}; - - -/** - * Sets the entire class name of an element. - * @param {Element} element DOM node to set class of. - * @param {string} className Class name(s) to apply to element. - */ -goog.dom.classlist.set = function(element, className) { - element.className = className; -}; - - -/** - * Returns true if an element has a class. This method may throw a DOM - * exception for an invalid or empty class name if DOMTokenList is used. - * @param {Element} element DOM node to test. - * @param {string} className Class name to test for. - * @return {boolean} Whether element has the class. - */ -goog.dom.classlist.contains = function(element, className) { - if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) { - return element.classList.contains(className); - } - return goog.array.contains(goog.dom.classlist.get(element), className); -}; - - -/** - * Adds a class to an element. Does not add multiples of class names. This - * method may throw a DOM exception for an invalid or empty class name if - * DOMTokenList is used. - * @param {Element} element DOM node to add class to. - * @param {string} className Class name to add. - */ -goog.dom.classlist.add = function(element, className) { - if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) { - element.classList.add(className); - return; - } - - if (!goog.dom.classlist.contains(element, className)) { - // Ensure we add a space if this is not the first class name added. - element.className += element.className.length > 0 ? - (' ' + className) : className; - } -}; - - -/** - * Convenience method to add a number of class names at once. - * @param {Element} element The element to which to add classes. - * @param {goog.array.ArrayLike<string>} classesToAdd An array-like object - * containing a collection of class names to add to the element. - * This method may throw a DOM exception if classesToAdd contains invalid - * or empty class names. - */ -goog.dom.classlist.addAll = function(element, classesToAdd) { - if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) { - goog.array.forEach(classesToAdd, function(className) { - goog.dom.classlist.add(element, className); - }); - return; - } - - var classMap = {}; - - // Get all current class names into a map. - goog.array.forEach(goog.dom.classlist.get(element), - function(className) { - classMap[className] = true; - }); - - // Add new class names to the map. - goog.array.forEach(classesToAdd, - function(className) { - classMap[className] = true; - }); - - // Flatten the keys of the map into the className. - element.className = ''; - for (var className in classMap) { - element.className += element.className.length > 0 ? - (' ' + className) : className; - } -}; - - -/** - * Removes a class from an element. This method may throw a DOM exception - * for an invalid or empty class name if DOMTokenList is used. - * @param {Element} element DOM node to remove class from. - * @param {string} className Class name to remove. - */ -goog.dom.classlist.remove = function(element, className) { - if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) { - element.classList.remove(className); - return; - } - - if (goog.dom.classlist.contains(element, className)) { - // Filter out the class name. - element.className = goog.array.filter( - goog.dom.classlist.get(element), - function(c) { - return c != className; - }).join(' '); - } -}; - - -/** - * Removes a set of classes from an element. Prefer this call to - * repeatedly calling {@code goog.dom.classlist.remove} if you want to remove - * a large set of class names at once. - * @param {Element} element The element from which to remove classes. - * @param {goog.array.ArrayLike<string>} classesToRemove An array-like object - * containing a collection of class names to remove from the element. - * This method may throw a DOM exception if classesToRemove contains invalid - * or empty class names. - */ -goog.dom.classlist.removeAll = function(element, classesToRemove) { - if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) { - goog.array.forEach(classesToRemove, function(className) { - goog.dom.classlist.remove(element, className); - }); - return; - } - // Filter out those classes in classesToRemove. - element.className = goog.array.filter( - goog.dom.classlist.get(element), - function(className) { - // If this class is not one we are trying to remove, - // add it to the array of new class names. - return !goog.array.contains(classesToRemove, className); - }).join(' '); -}; - - -/** - * Adds or removes a class depending on the enabled argument. This method - * may throw a DOM exception for an invalid or empty class name if DOMTokenList - * is used. - * @param {Element} element DOM node to add or remove the class on. - * @param {string} className Class name to add or remove. - * @param {boolean} enabled Whether to add or remove the class (true adds, - * false removes). - */ -goog.dom.classlist.enable = function(element, className, enabled) { - if (enabled) { - goog.dom.classlist.add(element, className); - } else { - goog.dom.classlist.remove(element, className); - } -}; - - -/** - * Adds or removes a set of classes depending on the enabled argument. This - * method may throw a DOM exception for an invalid or empty class name if - * DOMTokenList is used. - * @param {!Element} element DOM node to add or remove the class on. - * @param {goog.array.ArrayLike<string>} classesToEnable An array-like object - * containing a collection of class names to add or remove from the element. - * @param {boolean} enabled Whether to add or remove the classes (true adds, - * false removes). - */ -goog.dom.classlist.enableAll = function(element, classesToEnable, enabled) { - var f = enabled ? goog.dom.classlist.addAll : - goog.dom.classlist.removeAll; - f(element, classesToEnable); -}; - - -/** - * Switches a class on an element from one to another without disturbing other - * classes. If the fromClass isn't removed, the toClass won't be added. This - * method may throw a DOM exception if the class names are empty or invalid. - * @param {Element} element DOM node to swap classes on. - * @param {string} fromClass Class to remove. - * @param {string} toClass Class to add. - * @return {boolean} Whether classes were switched. - */ -goog.dom.classlist.swap = function(element, fromClass, toClass) { - if (goog.dom.classlist.contains(element, fromClass)) { - goog.dom.classlist.remove(element, fromClass); - goog.dom.classlist.add(element, toClass); - return true; - } - return false; -}; - - -/** - * Removes a class if an element has it, and adds it the element doesn't have - * it. Won't affect other classes on the node. This method may throw a DOM - * exception if the class name is empty or invalid. - * @param {Element} element DOM node to toggle class on. - * @param {string} className Class to toggle. - * @return {boolean} True if class was added, false if it was removed - * (in other words, whether element has the class after this function has - * been called). - */ -goog.dom.classlist.toggle = function(element, className) { - var add = !goog.dom.classlist.contains(element, className); - goog.dom.classlist.enable(element, className, add); - return add; -}; - - -/** - * Adds and removes a class of an element. Unlike - * {@link goog.dom.classlist.swap}, this method adds the classToAdd regardless - * of whether the classToRemove was present and had been removed. This method - * may throw a DOM exception if the class names are empty or invalid. - * - * @param {Element} element DOM node to swap classes on. - * @param {string} classToRemove Class to remove. - * @param {string} classToAdd Class to add. - */ -goog.dom.classlist.addRemove = function(element, classToRemove, classToAdd) { - goog.dom.classlist.remove(element, classToRemove); - goog.dom.classlist.add(element, classToAdd); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/dom.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/dom.js deleted file mode 100644 index 2d0cdd0..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/dom.js +++ /dev/null @@ -1,2989 +0,0 @@ -// 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 for manipulating the browser's Document Object Model - * Inspiration taken *heavily* from mochikit (http://mochikit.com/). - * - * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer - * to a different document object. This is useful if you are working with - * frames or multiple windows. - * - * @author arv@google.com (Erik Arvidsson) - */ - - -// TODO(arv): Rename/refactor getTextContent and getRawTextContent. The problem -// is that getTextContent should mimic the DOM3 textContent. We should add a -// getInnerText (or getText) which tries to return the visible text, innerText. - - -goog.provide('goog.dom'); -goog.provide('goog.dom.Appendable'); -goog.provide('goog.dom.DomHelper'); - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.dom.BrowserFeature'); -goog.require('goog.dom.NodeType'); -goog.require('goog.dom.TagName'); -goog.require('goog.dom.safe'); -goog.require('goog.html.SafeHtml'); -goog.require('goog.math.Coordinate'); -goog.require('goog.math.Size'); -goog.require('goog.object'); -goog.require('goog.string'); -goog.require('goog.string.Unicode'); -goog.require('goog.userAgent'); - - -/** - * @define {boolean} Whether we know at compile time that the browser is in - * quirks mode. - */ -goog.define('goog.dom.ASSUME_QUIRKS_MODE', false); - - -/** - * @define {boolean} Whether we know at compile time that the browser is in - * standards compliance mode. - */ -goog.define('goog.dom.ASSUME_STANDARDS_MODE', false); - - -/** - * Whether we know the compatibility mode at compile time. - * @type {boolean} - * @private - */ -goog.dom.COMPAT_MODE_KNOWN_ = - goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE; - - -/** - * Gets the DomHelper object for the document where the element resides. - * @param {(Node|Window)=} opt_element If present, gets the DomHelper for this - * element. - * @return {!goog.dom.DomHelper} The DomHelper. - */ -goog.dom.getDomHelper = function(opt_element) { - return opt_element ? - new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) : - (goog.dom.defaultDomHelper_ || - (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper())); -}; - - -/** - * Cached default DOM helper. - * @type {goog.dom.DomHelper} - * @private - */ -goog.dom.defaultDomHelper_; - - -/** - * Gets the document object being used by the dom library. - * @return {!Document} Document object. - */ -goog.dom.getDocument = function() { - return document; -}; - - -/** - * Gets an element from the current document by element id. - * - * If an Element is passed in, it is returned. - * - * @param {string|Element} element Element ID or a DOM node. - * @return {Element} The element with the given ID, or the node passed in. - */ -goog.dom.getElement = function(element) { - return goog.dom.getElementHelper_(document, element); -}; - - -/** - * Gets an element by id from the given document (if present). - * If an element is given, it is returned. - * @param {!Document} doc - * @param {string|Element} element Element ID or a DOM node. - * @return {Element} The resulting element. - * @private - */ -goog.dom.getElementHelper_ = function(doc, element) { - return goog.isString(element) ? - doc.getElementById(element) : - element; -}; - - -/** - * Gets an element by id, asserting that the element is found. - * - * This is used when an element is expected to exist, and should fail with - * an assertion error if it does not (if assertions are enabled). - * - * @param {string} id Element ID. - * @return {!Element} The element with the given ID, if it exists. - */ -goog.dom.getRequiredElement = function(id) { - return goog.dom.getRequiredElementHelper_(document, id); -}; - - -/** - * Helper function for getRequiredElementHelper functions, both static and - * on DomHelper. Asserts the element with the given id exists. - * @param {!Document} doc - * @param {string} id - * @return {!Element} The element with the given ID, if it exists. - * @private - */ -goog.dom.getRequiredElementHelper_ = function(doc, id) { - // To prevent users passing in Elements as is permitted in getElement(). - goog.asserts.assertString(id); - var element = goog.dom.getElementHelper_(doc, id); - element = goog.asserts.assertElement(element, - 'No element found with id: ' + id); - return element; -}; - - -/** - * Alias for getElement. - * @param {string|Element} element Element ID or a DOM node. - * @return {Element} The element with the given ID, or the node passed in. - * @deprecated Use {@link goog.dom.getElement} instead. - */ -goog.dom.$ = goog.dom.getElement; - - -/** - * Looks up elements by both tag and class name, using browser native functions - * ({@code querySelectorAll}, {@code getElementsByTagName} or - * {@code getElementsByClassName}) where possible. This function - * is a useful, if limited, way of collecting a list of DOM elements - * with certain characteristics. {@code goog.dom.query} offers a - * more powerful and general solution which allows matching on CSS3 - * selector expressions, but at increased cost in code size. If all you - * need is particular tags belonging to a single class, this function - * is fast and sleek. - * - * Note that tag names are case sensitive in the SVG namespace, and this - * function converts opt_tag to uppercase for comparisons. For queries in the - * SVG namespace you should use querySelector or querySelectorAll instead. - * https://bugzilla.mozilla.org/show_bug.cgi?id=963870 - * https://bugs.webkit.org/show_bug.cgi?id=83438 - * - * @see {goog.dom.query} - * - * @param {?string=} opt_tag Element tag name. - * @param {?string=} opt_class Optional class name. - * @param {(Document|Element)=} opt_el Optional element to look in. - * @return { {length: number} } Array-like list of elements (only a length - * property and numerical indices are guaranteed to exist). - */ -goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) { - return goog.dom.getElementsByTagNameAndClass_(document, opt_tag, opt_class, - opt_el); -}; - - -/** - * Returns a static, array-like list of the elements with the provided - * className. - * @see {goog.dom.query} - * @param {string} className the name of the class to look for. - * @param {(Document|Element)=} opt_el Optional element to look in. - * @return { {length: number} } The items found with the class name provided. - */ -goog.dom.getElementsByClass = function(className, opt_el) { - var parent = opt_el || document; - if (goog.dom.canUseQuerySelector_(parent)) { - return parent.querySelectorAll('.' + className); - } - return goog.dom.getElementsByTagNameAndClass_( - document, '*', className, opt_el); -}; - - -/** - * Returns the first element with the provided className. - * @see {goog.dom.query} - * @param {string} className the name of the class to look for. - * @param {Element|Document=} opt_el Optional element to look in. - * @return {Element} The first item with the class name provided. - */ -goog.dom.getElementByClass = function(className, opt_el) { - var parent = opt_el || document; - var retVal = null; - if (parent.getElementsByClassName) { - retVal = parent.getElementsByClassName(className)[0]; - } else if (goog.dom.canUseQuerySelector_(parent)) { - retVal = parent.querySelector('.' + className); - } else { - retVal = goog.dom.getElementsByTagNameAndClass_( - document, '*', className, opt_el)[0]; - } - return retVal || null; -}; - - -/** - * Ensures an element with the given className exists, and then returns the - * first element with the provided className. - * @see {goog.dom.query} - * @param {string} className the name of the class to look for. - * @param {!Element|!Document=} opt_root Optional element or document to look - * in. - * @return {!Element|null} The first item with the class name provided. - * @throws {goog.asserts.AssertionError} Thrown if no element is found. - */ -goog.dom.getRequiredElementByClass = function(className, opt_root) { - var retValue = goog.dom.getElementByClass(className, opt_root); - return goog.asserts.assert(retValue, - 'No element found with className: ' + className); -}; - - -/** - * Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and - * fast W3C Selectors API. - * @param {!(Element|Document)} parent The parent document object. - * @return {boolean} whether or not we can use parent.querySelector* APIs. - * @private - */ -goog.dom.canUseQuerySelector_ = function(parent) { - return !!(parent.querySelectorAll && parent.querySelector); -}; - - -/** - * Helper for {@code getElementsByTagNameAndClass}. - * @param {!Document} doc The document to get the elements in. - * @param {?string=} opt_tag Element tag name. - * @param {?string=} opt_class Optional class name. - * @param {(Document|Element)=} opt_el Optional element to look in. - * @return { {length: number} } Array-like list of elements (only a length - * property and numerical indices are guaranteed to exist). - * @private - */ -goog.dom.getElementsByTagNameAndClass_ = function(doc, opt_tag, opt_class, - opt_el) { - var parent = opt_el || doc; - var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toUpperCase() : ''; - - if (goog.dom.canUseQuerySelector_(parent) && - (tagName || opt_class)) { - var query = tagName + (opt_class ? '.' + opt_class : ''); - return parent.querySelectorAll(query); - } - - // Use the native getElementsByClassName if available, under the assumption - // that even when the tag name is specified, there will be fewer elements to - // filter through when going by class than by tag name - if (opt_class && parent.getElementsByClassName) { - var els = parent.getElementsByClassName(opt_class); - - if (tagName) { - var arrayLike = {}; - var len = 0; - - // Filter for specific tags if requested. - for (var i = 0, el; el = els[i]; i++) { - if (tagName == el.nodeName) { - arrayLike[len++] = el; - } - } - arrayLike.length = len; - - return arrayLike; - } else { - return els; - } - } - - var els = parent.getElementsByTagName(tagName || '*'); - - if (opt_class) { - var arrayLike = {}; - var len = 0; - for (var i = 0, el; el = els[i]; i++) { - var className = el.className; - // Check if className has a split function since SVG className does not. - if (typeof className.split == 'function' && - goog.array.contains(className.split(/\s+/), opt_class)) { - arrayLike[len++] = el; - } - } - arrayLike.length = len; - return arrayLike; - } else { - return els; - } -}; - - -/** - * Alias for {@code getElementsByTagNameAndClass}. - * @param {?string=} opt_tag Element tag name. - * @param {?string=} opt_class Optional class name. - * @param {Element=} opt_el Optional element to look in. - * @return { {length: number} } Array-like list of elements (only a length - * property and numerical indices are guaranteed to exist). - * @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead. - */ -goog.dom.$$ = goog.dom.getElementsByTagNameAndClass; - - -/** - * Sets multiple properties on a node. - * @param {Element} element DOM node to set properties on. - * @param {Object} properties Hash of property:value pairs. - */ -goog.dom.setProperties = function(element, properties) { - goog.object.forEach(properties, function(val, key) { - if (key == 'style') { - element.style.cssText = val; - } else if (key == 'class') { - element.className = val; - } else if (key == 'for') { - element.htmlFor = val; - } else if (key in goog.dom.DIRECT_ATTRIBUTE_MAP_) { - element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val); - } else if (goog.string.startsWith(key, 'aria-') || - goog.string.startsWith(key, 'data-')) { - element.setAttribute(key, val); - } else { - element[key] = val; - } - }); -}; - - -/** - * Map of attributes that should be set using - * element.setAttribute(key, val) instead of element[key] = val. Used - * by goog.dom.setProperties. - * - * @private {!Object<string, string>} - * @const - */ -goog.dom.DIRECT_ATTRIBUTE_MAP_ = { - 'cellpadding': 'cellPadding', - 'cellspacing': 'cellSpacing', - 'colspan': 'colSpan', - 'frameborder': 'frameBorder', - 'height': 'height', - 'maxlength': 'maxLength', - 'role': 'role', - 'rowspan': 'rowSpan', - 'type': 'type', - 'usemap': 'useMap', - 'valign': 'vAlign', - 'width': 'width' -}; - - -/** - * Gets the dimensions of the viewport. - * - * Gecko Standards mode: - * docEl.clientWidth Width of viewport excluding scrollbar. - * win.innerWidth Width of viewport including scrollbar. - * body.clientWidth Width of body element. - * - * docEl.clientHeight Height of viewport excluding scrollbar. - * win.innerHeight Height of viewport including scrollbar. - * body.clientHeight Height of document. - * - * Gecko Backwards compatible mode: - * docEl.clientWidth Width of viewport excluding scrollbar. - * win.innerWidth Width of viewport including scrollbar. - * body.clientWidth Width of viewport excluding scrollbar. - * - * docEl.clientHeight Height of document. - * win.innerHeight Height of viewport including scrollbar. - * body.clientHeight Height of viewport excluding scrollbar. - * - * IE6/7 Standards mode: - * docEl.clientWidth Width of viewport excluding scrollbar. - * win.innerWidth Undefined. - * body.clientWidth Width of body element. - * - * docEl.clientHeight Height of viewport excluding scrollbar. - * win.innerHeight Undefined. - * body.clientHeight Height of document element. - * - * IE5 + IE6/7 Backwards compatible mode: - * docEl.clientWidth 0. - * win.innerWidth Undefined. - * body.clientWidth Width of viewport excluding scrollbar. - * - * docEl.clientHeight 0. - * win.innerHeight Undefined. - * body.clientHeight Height of viewport excluding scrollbar. - * - * Opera 9 Standards and backwards compatible mode: - * docEl.clientWidth Width of viewport excluding scrollbar. - * win.innerWidth Width of viewport including scrollbar. - * body.clientWidth Width of viewport excluding scrollbar. - * - * docEl.clientHeight Height of document. - * win.innerHeight Height of viewport including scrollbar. - * body.clientHeight Height of viewport excluding scrollbar. - * - * WebKit: - * Safari 2 - * docEl.clientHeight Same as scrollHeight. - * docEl.clientWidth Same as innerWidth. - * win.innerWidth Width of viewport excluding scrollbar. - * win.innerHeight Height of the viewport including scrollbar. - * frame.innerHeight Height of the viewport exluding scrollbar. - * - * Safari 3 (tested in 522) - * - * docEl.clientWidth Width of viewport excluding scrollbar. - * docEl.clientHeight Height of viewport excluding scrollbar in strict mode. - * body.clientHeight Height of viewport excluding scrollbar in quirks mode. - * - * @param {Window=} opt_window Optional window element to test. - * @return {!goog.math.Size} Object with values 'width' and 'height'. - */ -goog.dom.getViewportSize = function(opt_window) { - // TODO(arv): This should not take an argument - return goog.dom.getViewportSize_(opt_window || window); -}; - - -/** - * Helper for {@code getViewportSize}. - * @param {Window} win The window to get the view port size for. - * @return {!goog.math.Size} Object with values 'width' and 'height'. - * @private - */ -goog.dom.getViewportSize_ = function(win) { - var doc = win.document; - var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body; - return new goog.math.Size(el.clientWidth, el.clientHeight); -}; - - -/** - * Calculates the height of the document. - * - * @return {number} The height of the current document. - */ -goog.dom.getDocumentHeight = function() { - return goog.dom.getDocumentHeight_(window); -}; - - -/** - * Calculates the height of the document of the given window. - * - * Function code copied from the opensocial gadget api: - * gadgets.window.adjustHeight(opt_height) - * - * @private - * @param {!Window} win The window whose document height to retrieve. - * @return {number} The height of the document of the given window. - */ -goog.dom.getDocumentHeight_ = function(win) { - // NOTE(eae): This method will return the window size rather than the document - // size in webkit quirks mode. - var doc = win.document; - var height = 0; - - if (doc) { - // Calculating inner content height is hard and different between - // browsers rendering in Strict vs. Quirks mode. We use a combination of - // three properties within document.body and document.documentElement: - // - scrollHeight - // - offsetHeight - // - clientHeight - // These values differ significantly between browsers and rendering modes. - // But there are patterns. It just takes a lot of time and persistence - // to figure out. - - var body = doc.body; - var docEl = doc.documentElement; - if (!(docEl && body)) { - return 0; - } - - // Get the height of the viewport - var vh = goog.dom.getViewportSize_(win).height; - if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) { - // In Strict mode: - // The inner content height is contained in either: - // document.documentElement.scrollHeight - // document.documentElement.offsetHeight - // Based on studying the values output by different browsers, - // use the value that's NOT equal to the viewport height found above. - height = docEl.scrollHeight != vh ? - docEl.scrollHeight : docEl.offsetHeight; - } else { - // In Quirks mode: - // documentElement.clientHeight is equal to documentElement.offsetHeight - // except in IE. In most browsers, document.documentElement can be used - // to calculate the inner content height. - // However, in other browsers (e.g. IE), document.body must be used - // instead. How do we know which one to use? - // If document.documentElement.clientHeight does NOT equal - // document.documentElement.offsetHeight, then use document.body. - var sh = docEl.scrollHeight; - var oh = docEl.offsetHeight; - if (docEl.clientHeight != oh) { - sh = body.scrollHeight; - oh = body.offsetHeight; - } - - // Detect whether the inner content height is bigger or smaller - // than the bounding box (viewport). If bigger, take the larger - // value. If smaller, take the smaller value. - if (sh > vh) { - // Content is larger - height = sh > oh ? sh : oh; - } else { - // Content is smaller - height = sh < oh ? sh : oh; - } - } - } - - return height; -}; - - -/** - * Gets the page scroll distance as a coordinate object. - * - * @param {Window=} opt_window Optional window element to test. - * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. - * @deprecated Use {@link goog.dom.getDocumentScroll} instead. - */ -goog.dom.getPageScroll = function(opt_window) { - var win = opt_window || goog.global || window; - return goog.dom.getDomHelper(win.document).getDocumentScroll(); -}; - - -/** - * Gets the document scroll distance as a coordinate object. - * - * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. - */ -goog.dom.getDocumentScroll = function() { - return goog.dom.getDocumentScroll_(document); -}; - - -/** - * Helper for {@code getDocumentScroll}. - * - * @param {!Document} doc The document to get the scroll for. - * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. - * @private - */ -goog.dom.getDocumentScroll_ = function(doc) { - var el = goog.dom.getDocumentScrollElement_(doc); - var win = goog.dom.getWindow_(doc); - if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('10') && - win.pageYOffset != el.scrollTop) { - // The keyboard on IE10 touch devices shifts the page using the pageYOffset - // without modifying scrollTop. For this case, we want the body scroll - // offsets. - return new goog.math.Coordinate(el.scrollLeft, el.scrollTop); - } - return new goog.math.Coordinate(win.pageXOffset || el.scrollLeft, - win.pageYOffset || el.scrollTop); -}; - - -/** - * Gets the document scroll element. - * @return {!Element} Scrolling element. - */ -goog.dom.getDocumentScrollElement = function() { - return goog.dom.getDocumentScrollElement_(document); -}; - - -/** - * Helper for {@code getDocumentScrollElement}. - * @param {!Document} doc The document to get the scroll element for. - * @return {!Element} Scrolling element. - * @private - */ -goog.dom.getDocumentScrollElement_ = function(doc) { - // WebKit needs body.scrollLeft in both quirks mode and strict mode. We also - // default to the documentElement if the document does not have a body (e.g. - // a SVG document). - if (!goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc)) { - return doc.documentElement; - } - return doc.body || doc.documentElement; -}; - - -/** - * Gets the window object associated with the given document. - * - * @param {Document=} opt_doc Document object to get window for. - * @return {!Window} The window associated with the given document. - */ -goog.dom.getWindow = function(opt_doc) { - // TODO(arv): This should not take an argument. - return opt_doc ? goog.dom.getWindow_(opt_doc) : window; -}; - - -/** - * Helper for {@code getWindow}. - * - * @param {!Document} doc Document object to get window for. - * @return {!Window} The window associated with the given document. - * @private - */ -goog.dom.getWindow_ = function(doc) { - return doc.parentWindow || doc.defaultView; -}; - - -/** - * Returns a dom node with a set of attributes. This function accepts varargs - * for subsequent nodes to be added. Subsequent nodes will be added to the - * first node as childNodes. - * - * So: - * <code>createDom('div', null, createDom('p'), createDom('p'));</code> - * would return a div with two child paragraphs - * - * @param {string} tagName Tag to create. - * @param {(Object|Array<string>|string)=} opt_attributes If object, then a map - * of name-value pairs for attributes. If a string, then this is the - * className of the new element. If an array, the elements will be joined - * together as the className of the new element. - * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or - * strings for text nodes. If one of the var_args is an array or NodeList,i - * its elements will be added as childNodes instead. - * @return {!Element} Reference to a DOM node. - */ -goog.dom.createDom = function(tagName, opt_attributes, var_args) { - return goog.dom.createDom_(document, arguments); -}; - - -/** - * Helper for {@code createDom}. - * @param {!Document} doc The document to create the DOM in. - * @param {!Arguments} args Argument object passed from the callers. See - * {@code goog.dom.createDom} for details. - * @return {!Element} Reference to a DOM node. - * @private - */ -goog.dom.createDom_ = function(doc, args) { - var tagName = args[0]; - var attributes = args[1]; - - // Internet Explorer is dumb: http://msdn.microsoft.com/workshop/author/ - // dhtml/reference/properties/name_2.asp - // Also does not allow setting of 'type' attribute on 'input' or 'button'. - if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes && - (attributes.name || attributes.type)) { - var tagNameArr = ['<', tagName]; - if (attributes.name) { - tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name), - '"'); - } - if (attributes.type) { - tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type), - '"'); - - // Clone attributes map to remove 'type' without mutating the input. - var clone = {}; - goog.object.extend(clone, attributes); - - // JSCompiler can't see how goog.object.extend added this property, - // because it was essentially added by reflection. - // So it needs to be quoted. - delete clone['type']; - - attributes = clone; - } - tagNameArr.push('>'); - tagName = tagNameArr.join(''); - } - - var element = doc.createElement(tagName); - - if (attributes) { - if (goog.isString(attributes)) { - element.className = attributes; - } else if (goog.isArray(attributes)) { - element.className = attributes.join(' '); - } else { - goog.dom.setProperties(element, attributes); - } - } - - if (args.length > 2) { - goog.dom.append_(doc, element, args, 2); - } - - return element; -}; - - -/** - * Appends a node with text or other nodes. - * @param {!Document} doc The document to create new nodes in. - * @param {!Node} parent The node to append nodes to. - * @param {!Arguments} args The values to add. See {@code goog.dom.append}. - * @param {number} startIndex The index of the array to start from. - * @private - */ -goog.dom.append_ = function(doc, parent, args, startIndex) { - function childHandler(child) { - // TODO(user): More coercion, ala MochiKit? - if (child) { - parent.appendChild(goog.isString(child) ? - doc.createTextNode(child) : child); - } - } - - for (var i = startIndex; i < args.length; i++) { - var arg = args[i]; - // TODO(attila): Fix isArrayLike to return false for a text node. - if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) { - // If the argument is a node list, not a real array, use a clone, - // because forEach can't be used to mutate a NodeList. - goog.array.forEach(goog.dom.isNodeList(arg) ? - goog.array.toArray(arg) : arg, - childHandler); - } else { - childHandler(arg); - } - } -}; - - -/** - * Alias for {@code createDom}. - * @param {string} tagName Tag to create. - * @param {(string|Object)=} opt_attributes If object, then a map of name-value - * pairs for attributes. If a string, then this is the className of the new - * element. - * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or - * strings for text nodes. If one of the var_args is an array, its - * children will be added as childNodes instead. - * @return {!Element} Reference to a DOM node. - * @deprecated Use {@link goog.dom.createDom} instead. - */ -goog.dom.$dom = goog.dom.createDom; - - -/** - * Creates a new element. - * @param {string} name Tag name. - * @return {!Element} The new element. - */ -goog.dom.createElement = function(name) { - return document.createElement(name); -}; - - -/** - * Creates a new text node. - * @param {number|string} content Content. - * @return {!Text} The new text node. - */ -goog.dom.createTextNode = function(content) { - return document.createTextNode(String(content)); -}; - - -/** - * Create a table. - * @param {number} rows The number of rows in the table. Must be >= 1. - * @param {number} columns The number of columns in the table. Must be >= 1. - * @param {boolean=} opt_fillWithNbsp If true, fills table entries with - * {@code goog.string.Unicode.NBSP} characters. - * @return {!Element} The created table. - */ -goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) { - // TODO(user): Return HTMLTableElement, also in prototype function. - // Callers need to be updated to e.g. not assign numbers to table.cellSpacing. - return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp); -}; - - -/** - * Create a table. - * @param {!Document} doc Document object to use to create the table. - * @param {number} rows The number of rows in the table. Must be >= 1. - * @param {number} columns The number of columns in the table. Must be >= 1. - * @param {boolean} fillWithNbsp If true, fills table entries with - * {@code goog.string.Unicode.NBSP} characters. - * @return {!HTMLTableElement} The created table. - * @private - */ -goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) { - var table = /** @type {!HTMLTableElement} */ - (doc.createElement(goog.dom.TagName.TABLE)); - var tbody = table.appendChild(doc.createElement(goog.dom.TagName.TBODY)); - for (var i = 0; i < rows; i++) { - var tr = doc.createElement(goog.dom.TagName.TR); - for (var j = 0; j < columns; j++) { - var td = doc.createElement(goog.dom.TagName.TD); - // IE <= 9 will create a text node if we set text content to the empty - // string, so we avoid doing it unless necessary. This ensures that the - // same DOM tree is returned on all browsers. - if (fillWithNbsp) { - goog.dom.setTextContent(td, goog.string.Unicode.NBSP); - } - tr.appendChild(td); - } - tbody.appendChild(tr); - } - return table; -}; - - -/** - * Converts HTML markup into a node. - * @param {!goog.html.SafeHtml} html The HTML markup to convert. - * @return {!Node} The resulting node. - */ -goog.dom.safeHtmlToNode = function(html) { - return goog.dom.safeHtmlToNode_(document, html); -}; - - -/** - * Helper for {@code safeHtmlToNode}. - * @param {!Document} doc The document. - * @param {!goog.html.SafeHtml} html The HTML markup to convert. - * @return {!Node} The resulting node. - * @private - */ -goog.dom.safeHtmlToNode_ = function(doc, html) { - var tempDiv = doc.createElement('div'); - if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) { - goog.dom.safe.setInnerHtml(tempDiv, - goog.html.SafeHtml.concat(goog.html.SafeHtml.create('br'), html)); - tempDiv.removeChild(tempDiv.firstChild); - } else { - goog.dom.safe.setInnerHtml(tempDiv, html); - } - return goog.dom.childrenToNode_(doc, tempDiv); -}; - - -/** - * Converts an HTML string into a document fragment. The string must be - * sanitized in order to avoid cross-site scripting. For example - * {@code goog.dom.htmlToDocumentFragment('<img src=x onerror=alert(0)>')} - * triggers an alert in all browsers, even if the returned document fragment - * is thrown away immediately. - * - * @param {string} htmlString The HTML string to convert. - * @return {!Node} The resulting document fragment. - */ -goog.dom.htmlToDocumentFragment = function(htmlString) { - return goog.dom.htmlToDocumentFragment_(document, htmlString); -}; - - -// TODO(jakubvrana): Merge with {@code safeHtmlToNode_}. -/** - * Helper for {@code htmlToDocumentFragment}. - * - * @param {!Document} doc The document. - * @param {string} htmlString The HTML string to convert. - * @return {!Node} The resulting document fragment. - * @private - */ -goog.dom.htmlToDocumentFragment_ = function(doc, htmlString) { - var tempDiv = doc.createElement('div'); - if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) { - tempDiv.innerHTML = '<br>' + htmlString; - tempDiv.removeChild(tempDiv.firstChild); - } else { - tempDiv.innerHTML = htmlString; - } - return goog.dom.childrenToNode_(doc, tempDiv); -}; - - -/** - * Helper for {@code htmlToDocumentFragment_}. - * @param {!Document} doc The document. - * @param {!Node} tempDiv The input node. - * @return {!Node} The resulting node. - * @private - */ -goog.dom.childrenToNode_ = function(doc, tempDiv) { - if (tempDiv.childNodes.length == 1) { - return tempDiv.removeChild(tempDiv.firstChild); - } else { - var fragment = doc.createDocumentFragment(); - while (tempDiv.firstChild) { - fragment.appendChild(tempDiv.firstChild); - } - return fragment; - } -}; - - -/** - * Returns true if the browser is in "CSS1-compatible" (standards-compliant) - * mode, false otherwise. - * @return {boolean} True if in CSS1-compatible mode. - */ -goog.dom.isCss1CompatMode = function() { - return goog.dom.isCss1CompatMode_(document); -}; - - -/** - * Returns true if the browser is in "CSS1-compatible" (standards-compliant) - * mode, false otherwise. - * @param {!Document} doc The document to check. - * @return {boolean} True if in CSS1-compatible mode. - * @private - */ -goog.dom.isCss1CompatMode_ = function(doc) { - if (goog.dom.COMPAT_MODE_KNOWN_) { - return goog.dom.ASSUME_STANDARDS_MODE; - } - - return doc.compatMode == 'CSS1Compat'; -}; - - -/** - * Determines if the given node can contain children, intended to be used for - * HTML generation. - * - * IE natively supports node.canHaveChildren but has inconsistent behavior. - * Prior to IE8 the base tag allows children and in IE9 all nodes return true - * for canHaveChildren. - * - * In practice all non-IE browsers allow you to add children to any node, but - * the behavior is inconsistent: - * - * <pre> - * var a = document.createElement('br'); - * a.appendChild(document.createTextNode('foo')); - * a.appendChild(document.createTextNode('bar')); - * console.log(a.childNodes.length); // 2 - * console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar" - * </pre> - * - * For more information, see: - * http://dev.w3.org/html5/markup/syntax.html#syntax-elements - * - * TODO(user): Rename shouldAllowChildren() ? - * - * @param {Node} node The node to check. - * @return {boolean} Whether the node can contain children. - */ -goog.dom.canHaveChildren = function(node) { - if (node.nodeType != goog.dom.NodeType.ELEMENT) { - return false; - } - switch (node.tagName) { - case goog.dom.TagName.APPLET: - case goog.dom.TagName.AREA: - case goog.dom.TagName.BASE: - case goog.dom.TagName.BR: - case goog.dom.TagName.COL: - case goog.dom.TagName.COMMAND: - case goog.dom.TagName.EMBED: - case goog.dom.TagName.FRAME: - case goog.dom.TagName.HR: - case goog.dom.TagName.IMG: - case goog.dom.TagName.INPUT: - case goog.dom.TagName.IFRAME: - case goog.dom.TagName.ISINDEX: - case goog.dom.TagName.KEYGEN: - case goog.dom.TagName.LINK: - case goog.dom.TagName.NOFRAMES: - case goog.dom.TagName.NOSCRIPT: - case goog.dom.TagName.META: - case goog.dom.TagName.OBJECT: - case goog.dom.TagName.PARAM: - case goog.dom.TagName.SCRIPT: - case goog.dom.TagName.SOURCE: - case goog.dom.TagName.STYLE: - case goog.dom.TagName.TRACK: - case goog.dom.TagName.WBR: - return false; - } - return true; -}; - - -/** - * Appends a child to a node. - * @param {Node} parent Parent. - * @param {Node} child Child. - */ -goog.dom.appendChild = function(parent, child) { - parent.appendChild(child); -}; - - -/** - * Appends a node with text or other nodes. - * @param {!Node} parent The node to append nodes to. - * @param {...goog.dom.Appendable} var_args The things to append to the node. - * If this is a Node it is appended as is. - * If this is a string then a text node is appended. - * If this is an array like object then fields 0 to length - 1 are appended. - */ -goog.dom.append = function(parent, var_args) { - goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1); -}; - - -/** - * Removes all the child nodes on a DOM node. - * @param {Node} node Node to remove children from. - */ -goog.dom.removeChildren = function(node) { - // Note: Iterations over live collections can be slow, this is the fastest - // we could find. The double parenthesis are used to prevent JsCompiler and - // strict warnings. - var child; - while ((child = node.firstChild)) { - node.removeChild(child); - } -}; - - -/** - * Inserts a new node before an existing reference node (i.e. as the previous - * sibling). If the reference node has no parent, then does nothing. - * @param {Node} newNode Node to insert. - * @param {Node} refNode Reference node to insert before. - */ -goog.dom.insertSiblingBefore = function(newNode, refNode) { - if (refNode.parentNode) { - refNode.parentNode.insertBefore(newNode, refNode); - } -}; - - -/** - * Inserts a new node after an existing reference node (i.e. as the next - * sibling). If the reference node has no parent, then does nothing. - * @param {Node} newNode Node to insert. - * @param {Node} refNode Reference node to insert after. - */ -goog.dom.insertSiblingAfter = function(newNode, refNode) { - if (refNode.parentNode) { - refNode.parentNode.insertBefore(newNode, refNode.nextSibling); - } -}; - - -/** - * Insert a child at a given index. If index is larger than the number of child - * nodes that the parent currently has, the node is inserted as the last child - * node. - * @param {Element} parent The element into which to insert the child. - * @param {Node} child The element to insert. - * @param {number} index The index at which to insert the new child node. Must - * not be negative. - */ -goog.dom.insertChildAt = function(parent, child, index) { - // Note that if the second argument is null, insertBefore - // will append the child at the end of the list of children. - parent.insertBefore(child, parent.childNodes[index] || null); -}; - - -/** - * Removes a node from its parent. - * @param {Node} node The node to remove. - * @return {Node} The node removed if removed; else, null. - */ -goog.dom.removeNode = function(node) { - return node && node.parentNode ? node.parentNode.removeChild(node) : null; -}; - - -/** - * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no - * parent. - * @param {Node} newNode Node to insert. - * @param {Node} oldNode Node to replace. - */ -goog.dom.replaceNode = function(newNode, oldNode) { - var parent = oldNode.parentNode; - if (parent) { - parent.replaceChild(newNode, oldNode); - } -}; - - -/** - * Flattens an element. That is, removes it and replace it with its children. - * Does nothing if the element is not in the document. - * @param {Element} element The element to flatten. - * @return {Element|undefined} The original element, detached from the document - * tree, sans children; or undefined, if the element was not in the document - * to begin with. - */ -goog.dom.flattenElement = function(element) { - var child, parent = element.parentNode; - if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) { - // Use IE DOM method (supported by Opera too) if available - if (element.removeNode) { - return /** @type {Element} */ (element.removeNode(false)); - } else { - // Move all children of the original node up one level. - while ((child = element.firstChild)) { - parent.insertBefore(child, element); - } - - // Detach the original element. - return /** @type {Element} */ (goog.dom.removeNode(element)); - } - } -}; - - -/** - * Returns an array containing just the element children of the given element. - * @param {Element} element The element whose element children we want. - * @return {!(Array|NodeList)} An array or array-like list of just the element - * children of the given element. - */ -goog.dom.getChildren = function(element) { - // We check if the children attribute is supported for child elements - // since IE8 misuses the attribute by also including comments. - if (goog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE && - element.children != undefined) { - return element.children; - } - // Fall back to manually filtering the element's child nodes. - return goog.array.filter(element.childNodes, function(node) { - return node.nodeType == goog.dom.NodeType.ELEMENT; - }); -}; - - -/** - * Returns the first child node that is an element. - * @param {Node} node The node to get the first child element of. - * @return {Element} The first child node of {@code node} that is an element. - */ -goog.dom.getFirstElementChild = function(node) { - if (node.firstElementChild != undefined) { - return /** @type {!Element} */(node).firstElementChild; - } - return goog.dom.getNextElementNode_(node.firstChild, true); -}; - - -/** - * Returns the last child node that is an element. - * @param {Node} node The node to get the last child element of. - * @return {Element} The last child node of {@code node} that is an element. - */ -goog.dom.getLastElementChild = function(node) { - if (node.lastElementChild != undefined) { - return /** @type {!Element} */(node).lastElementChild; - } - return goog.dom.getNextElementNode_(node.lastChild, false); -}; - - -/** - * Returns the first next sibling that is an element. - * @param {Node} node The node to get the next sibling element of. - * @return {Element} The next sibling of {@code node} that is an element. - */ -goog.dom.getNextElementSibling = function(node) { - if (node.nextElementSibling != undefined) { - return /** @type {!Element} */(node).nextElementSibling; - } - return goog.dom.getNextElementNode_(node.nextSibling, true); -}; - - -/** - * Returns the first previous sibling that is an element. - * @param {Node} node The node to get the previous sibling element of. - * @return {Element} The first previous sibling of {@code node} that is - * an element. - */ -goog.dom.getPreviousElementSibling = function(node) { - if (node.previousElementSibling != undefined) { - return /** @type {!Element} */(node).previousElementSibling; - } - return goog.dom.getNextElementNode_(node.previousSibling, false); -}; - - -/** - * Returns the first node that is an element in the specified direction, - * starting with {@code node}. - * @param {Node} node The node to get the next element from. - * @param {boolean} forward Whether to look forwards or backwards. - * @return {Element} The first element. - * @private - */ -goog.dom.getNextElementNode_ = function(node, forward) { - while (node && node.nodeType != goog.dom.NodeType.ELEMENT) { - node = forward ? node.nextSibling : node.previousSibling; - } - - return /** @type {Element} */ (node); -}; - - -/** - * Returns the next node in source order from the given node. - * @param {Node} node The node. - * @return {Node} The next node in the DOM tree, or null if this was the last - * node. - */ -goog.dom.getNextNode = function(node) { - if (!node) { - return null; - } - - if (node.firstChild) { - return node.firstChild; - } - - while (node && !node.nextSibling) { - node = node.parentNode; - } - - return node ? node.nextSibling : null; -}; - - -/** - * Returns the previous node in source order from the given node. - * @param {Node} node The node. - * @return {Node} The previous node in the DOM tree, or null if this was the - * first node. - */ -goog.dom.getPreviousNode = function(node) { - if (!node) { - return null; - } - - if (!node.previousSibling) { - return node.parentNode; - } - - node = node.previousSibling; - while (node && node.lastChild) { - node = node.lastChild; - } - - return node; -}; - - -/** - * Whether the object looks like a DOM node. - * @param {?} obj The object being tested for node likeness. - * @return {boolean} Whether the object looks like a DOM node. - */ -goog.dom.isNodeLike = function(obj) { - return goog.isObject(obj) && obj.nodeType > 0; -}; - - -/** - * Whether the object looks like an Element. - * @param {?} obj The object being tested for Element likeness. - * @return {boolean} Whether the object looks like an Element. - */ -goog.dom.isElement = function(obj) { - return goog.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT; -}; - - -/** - * Returns true if the specified value is a Window object. This includes the - * global window for HTML pages, and iframe windows. - * @param {?} obj Variable to test. - * @return {boolean} Whether the variable is a window. - */ -goog.dom.isWindow = function(obj) { - return goog.isObject(obj) && obj['window'] == obj; -}; - - -/** - * Returns an element's parent, if it's an Element. - * @param {Element} element The DOM element. - * @return {Element} The parent, or null if not an Element. - */ -goog.dom.getParentElement = function(element) { - var parent; - if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) { - var isIe9 = goog.userAgent.IE && - goog.userAgent.isVersionOrHigher('9') && - !goog.userAgent.isVersionOrHigher('10'); - // SVG elements in IE9 can't use the parentElement property. - // goog.global['SVGElement'] is not defined in IE9 quirks mode. - if (!(isIe9 && goog.global['SVGElement'] && - element instanceof goog.global['SVGElement'])) { - parent = element.parentElement; - if (parent) { - return parent; - } - } - } - parent = element.parentNode; - return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null; -}; - - -/** - * Whether a node contains another node. - * @param {Node} parent The node that should contain the other node. - * @param {Node} descendant The node to test presence of. - * @return {boolean} Whether the parent node contains the descendent node. - */ -goog.dom.contains = function(parent, descendant) { - // We use browser specific methods for this if available since it is faster - // that way. - - // IE DOM - if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) { - return parent == descendant || parent.contains(descendant); - } - - // W3C DOM Level 3 - if (typeof parent.compareDocumentPosition != 'undefined') { - return parent == descendant || - Boolean(parent.compareDocumentPosition(descendant) & 16); - } - - // W3C DOM Level 1 - while (descendant && parent != descendant) { - descendant = descendant.parentNode; - } - return descendant == parent; -}; - - -/** - * Compares the document order of two nodes, returning 0 if they are the same - * node, a negative number if node1 is before node2, and a positive number if - * node2 is before node1. Note that we compare the order the tags appear in the - * document so in the tree <b><i>text</i></b> the B node is considered to be - * before the I node. - * - * @param {Node} node1 The first node to compare. - * @param {Node} node2 The second node to compare. - * @return {number} 0 if the nodes are the same node, a negative number if node1 - * is before node2, and a positive number if node2 is before node1. - */ -goog.dom.compareNodeOrder = function(node1, node2) { - // Fall out quickly for equality. - if (node1 == node2) { - return 0; - } - - // Use compareDocumentPosition where available - if (node1.compareDocumentPosition) { - // 4 is the bitmask for FOLLOWS. - return node1.compareDocumentPosition(node2) & 2 ? 1 : -1; - } - - // Special case for document nodes on IE 7 and 8. - if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) { - if (node1.nodeType == goog.dom.NodeType.DOCUMENT) { - return -1; - } - if (node2.nodeType == goog.dom.NodeType.DOCUMENT) { - return 1; - } - } - - // Process in IE using sourceIndex - we check to see if the first node has - // a source index or if its parent has one. - if ('sourceIndex' in node1 || - (node1.parentNode && 'sourceIndex' in node1.parentNode)) { - var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT; - var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT; - - if (isElement1 && isElement2) { - return node1.sourceIndex - node2.sourceIndex; - } else { - var parent1 = node1.parentNode; - var parent2 = node2.parentNode; - - if (parent1 == parent2) { - return goog.dom.compareSiblingOrder_(node1, node2); - } - - if (!isElement1 && goog.dom.contains(parent1, node2)) { - return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2); - } - - - if (!isElement2 && goog.dom.contains(parent2, node1)) { - return goog.dom.compareParentsDescendantNodeIe_(node2, node1); - } - - return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) - - (isElement2 ? node2.sourceIndex : parent2.sourceIndex); - } - } - - // For Safari, we compare ranges. - var doc = goog.dom.getOwnerDocument(node1); - - var range1, range2; - range1 = doc.createRange(); - range1.selectNode(node1); - range1.collapse(true); - - range2 = doc.createRange(); - range2.selectNode(node2); - range2.collapse(true); - - return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END, - range2); -}; - - -/** - * Utility function to compare the position of two nodes, when - * {@code textNode}'s parent is an ancestor of {@code node}. If this entry - * condition is not met, this function will attempt to reference a null object. - * @param {!Node} textNode The textNode to compare. - * @param {Node} node The node to compare. - * @return {number} -1 if node is before textNode, +1 otherwise. - * @private - */ -goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) { - var parent = textNode.parentNode; - if (parent == node) { - // If textNode is a child of node, then node comes first. - return -1; - } - var sibling = node; - while (sibling.parentNode != parent) { - sibling = sibling.parentNode; - } - return goog.dom.compareSiblingOrder_(sibling, textNode); -}; - - -/** - * Utility function to compare the position of two nodes known to be non-equal - * siblings. - * @param {Node} node1 The first node to compare. - * @param {!Node} node2 The second node to compare. - * @return {number} -1 if node1 is before node2, +1 otherwise. - * @private - */ -goog.dom.compareSiblingOrder_ = function(node1, node2) { - var s = node2; - while ((s = s.previousSibling)) { - if (s == node1) { - // We just found node1 before node2. - return -1; - } - } - - // Since we didn't find it, node1 must be after node2. - return 1; -}; - - -/** - * Find the deepest common ancestor of the given nodes. - * @param {...Node} var_args The nodes to find a common ancestor of. - * @return {Node} The common ancestor of the nodes, or null if there is none. - * null will only be returned if two or more of the nodes are from different - * documents. - */ -goog.dom.findCommonAncestor = function(var_args) { - var i, count = arguments.length; - if (!count) { - return null; - } else if (count == 1) { - return arguments[0]; - } - - var paths = []; - var minLength = Infinity; - for (i = 0; i < count; i++) { - // Compute the list of ancestors. - var ancestors = []; - var node = arguments[i]; - while (node) { - ancestors.unshift(node); - node = node.parentNode; - } - - // Save the list for comparison. - paths.push(ancestors); - minLength = Math.min(minLength, ancestors.length); - } - var output = null; - for (i = 0; i < minLength; i++) { - var first = paths[0][i]; - for (var j = 1; j < count; j++) { - if (first != paths[j][i]) { - return output; - } - } - output = first; - } - return output; -}; - - -/** - * Returns the owner document for a node. - * @param {Node|Window} node The node to get the document for. - * @return {!Document} The document owning the node. - */ -goog.dom.getOwnerDocument = function(node) { - // TODO(nnaze): Update param signature to be non-nullable. - goog.asserts.assert(node, 'Node cannot be null or undefined.'); - return /** @type {!Document} */ ( - node.nodeType == goog.dom.NodeType.DOCUMENT ? node : - node.ownerDocument || node.document); -}; - - -/** - * Cross-browser function for getting the document element of a frame or iframe. - * @param {Element} frame Frame element. - * @return {!Document} The frame content document. - */ -goog.dom.getFrameContentDocument = function(frame) { - var doc = frame.contentDocument || frame.contentWindow.document; - return doc; -}; - - -/** - * Cross-browser function for getting the window of a frame or iframe. - * @param {Element} frame Frame element. - * @return {Window} The window associated with the given frame. - */ -goog.dom.getFrameContentWindow = function(frame) { - return frame.contentWindow || - goog.dom.getWindow(goog.dom.getFrameContentDocument(frame)); -}; - - -/** - * Sets the text content of a node, with cross-browser support. - * @param {Node} node The node to change the text content of. - * @param {string|number} text The value that should replace the node's content. - */ -goog.dom.setTextContent = function(node, text) { - goog.asserts.assert(node != null, - 'goog.dom.setTextContent expects a non-null value for node'); - - if ('textContent' in node) { - node.textContent = text; - } else if (node.nodeType == goog.dom.NodeType.TEXT) { - node.data = text; - } else if (node.firstChild && - node.firstChild.nodeType == goog.dom.NodeType.TEXT) { - // If the first child is a text node we just change its data and remove the - // rest of the children. - while (node.lastChild != node.firstChild) { - node.removeChild(node.lastChild); - } - node.firstChild.data = text; - } else { - goog.dom.removeChildren(node); - var doc = goog.dom.getOwnerDocument(node); - node.appendChild(doc.createTextNode(String(text))); - } -}; - - -/** - * Gets the outerHTML of a node, which islike innerHTML, except that it - * actually contains the HTML of the node itself. - * @param {Element} element The element to get the HTML of. - * @return {string} The outerHTML of the given element. - */ -goog.dom.getOuterHtml = function(element) { - // IE, Opera and WebKit all have outerHTML. - if ('outerHTML' in element) { - return element.outerHTML; - } else { - var doc = goog.dom.getOwnerDocument(element); - var div = doc.createElement('div'); - div.appendChild(element.cloneNode(true)); - return div.innerHTML; - } -}; - - -/** - * Finds the first descendant node that matches the filter function, using - * a depth first search. This function offers the most general purpose way - * of finding a matching element. You may also wish to consider - * {@code goog.dom.query} which can express many matching criteria using - * CSS selector expressions. These expressions often result in a more - * compact representation of the desired result. - * @see goog.dom.query - * - * @param {Node} root The root of the tree to search. - * @param {function(Node) : boolean} p The filter function. - * @return {Node|undefined} The found node or undefined if none is found. - */ -goog.dom.findNode = function(root, p) { - var rv = []; - var found = goog.dom.findNodes_(root, p, rv, true); - return found ? rv[0] : undefined; -}; - - -/** - * Finds all the descendant nodes that match the filter function, using a - * a depth first search. This function offers the most general-purpose way - * of finding a set of matching elements. You may also wish to consider - * {@code goog.dom.query} which can express many matching criteria using - * CSS selector expressions. These expressions often result in a more - * compact representation of the desired result. - - * @param {Node} root The root of the tree to search. - * @param {function(Node) : boolean} p The filter function. - * @return {!Array<!Node>} The found nodes or an empty array if none are found. - */ -goog.dom.findNodes = function(root, p) { - var rv = []; - goog.dom.findNodes_(root, p, rv, false); - return rv; -}; - - -/** - * Finds the first or all the descendant nodes that match the filter function, - * using a depth first search. - * @param {Node} root The root of the tree to search. - * @param {function(Node) : boolean} p The filter function. - * @param {!Array<!Node>} rv The found nodes are added to this array. - * @param {boolean} findOne If true we exit after the first found node. - * @return {boolean} Whether the search is complete or not. True in case findOne - * is true and the node is found. False otherwise. - * @private - */ -goog.dom.findNodes_ = function(root, p, rv, findOne) { - if (root != null) { - var child = root.firstChild; - while (child) { - if (p(child)) { - rv.push(child); - if (findOne) { - return true; - } - } - if (goog.dom.findNodes_(child, p, rv, findOne)) { - return true; - } - child = child.nextSibling; - } - } - return false; -}; - - -/** - * Map of tags whose content to ignore when calculating text length. - * @private {!Object<string, number>} - * @const - */ -goog.dom.TAGS_TO_IGNORE_ = { - 'SCRIPT': 1, - 'STYLE': 1, - 'HEAD': 1, - 'IFRAME': 1, - 'OBJECT': 1 -}; - - -/** - * Map of tags which have predefined values with regard to whitespace. - * @private {!Object<string, string>} - * @const - */ -goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'}; - - -/** - * Returns true if the element has a tab index that allows it to receive - * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements - * natively support keyboard focus, even if they have no tab index. - * @param {!Element} element Element to check. - * @return {boolean} Whether the element has a tab index that allows keyboard - * focus. - * @see http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - */ -goog.dom.isFocusableTabIndex = function(element) { - return goog.dom.hasSpecifiedTabIndex_(element) && - goog.dom.isTabIndexFocusable_(element); -}; - - -/** - * Enables or disables keyboard focus support on the element via its tab index. - * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true - * (or elements that natively support keyboard focus, like form elements) can - * receive keyboard focus. See http://go/tabindex for more info. - * @param {Element} element Element whose tab index is to be changed. - * @param {boolean} enable Whether to set or remove a tab index on the element - * that supports keyboard focus. - */ -goog.dom.setFocusableTabIndex = function(element, enable) { - if (enable) { - element.tabIndex = 0; - } else { - // Set tabIndex to -1 first, then remove it. This is a workaround for - // Safari (confirmed in version 4 on Windows). When removing the attribute - // without setting it to -1 first, the element remains keyboard focusable - // despite not having a tabIndex attribute anymore. - element.tabIndex = -1; - element.removeAttribute('tabIndex'); // Must be camelCase! - } -}; - - -/** - * Returns true if the element can be focused, i.e. it has a tab index that - * allows it to receive keyboard focus (tabIndex >= 0), or it is an element - * that natively supports keyboard focus. - * @param {!Element} element Element to check. - * @return {boolean} Whether the element allows keyboard focus. - */ -goog.dom.isFocusable = function(element) { - var focusable; - // Some elements can have unspecified tab index and still receive focus. - if (goog.dom.nativelySupportsFocus_(element)) { - // Make sure the element is not disabled ... - focusable = !element.disabled && - // ... and if a tab index is specified, it allows focus. - (!goog.dom.hasSpecifiedTabIndex_(element) || - goog.dom.isTabIndexFocusable_(element)); - } else { - focusable = goog.dom.isFocusableTabIndex(element); - } - - // IE requires elements to be visible in order to focus them. - return focusable && goog.userAgent.IE ? - goog.dom.hasNonZeroBoundingRect_(element) : focusable; -}; - - -/** - * Returns true if the element has a specified tab index. - * @param {!Element} element Element to check. - * @return {boolean} Whether the element has a specified tab index. - * @private - */ -goog.dom.hasSpecifiedTabIndex_ = function(element) { - // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(), - // which returns an object with a 'specified' property if tabIndex is - // specified. This works on other browsers, too. - var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase! - return goog.isDefAndNotNull(attrNode) && attrNode.specified; -}; - - -/** - * Returns true if the element's tab index allows the element to be focused. - * @param {!Element} element Element to check. - * @return {boolean} Whether the element's tab index allows focus. - * @private - */ -goog.dom.isTabIndexFocusable_ = function(element) { - var index = element.tabIndex; - // NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534. - return goog.isNumber(index) && index >= 0 && index < 32768; -}; - - -/** - * Returns true if the element is focusable even when tabIndex is not set. - * @param {!Element} element Element to check. - * @return {boolean} Whether the element natively supports focus. - * @private - */ -goog.dom.nativelySupportsFocus_ = function(element) { - return element.tagName == goog.dom.TagName.A || - element.tagName == goog.dom.TagName.INPUT || - element.tagName == goog.dom.TagName.TEXTAREA || - element.tagName == goog.dom.TagName.SELECT || - element.tagName == goog.dom.TagName.BUTTON; -}; - - -/** - * Returns true if the element has a bounding rectangle that would be visible - * (i.e. its width and height are greater than zero). - * @param {!Element} element Element to check. - * @return {boolean} Whether the element has a non-zero bounding rectangle. - * @private - */ -goog.dom.hasNonZeroBoundingRect_ = function(element) { - var rect = goog.isFunction(element['getBoundingClientRect']) ? - element.getBoundingClientRect() : - {'height': element.offsetHeight, 'width': element.offsetWidth}; - return goog.isDefAndNotNull(rect) && rect.height > 0 && rect.width > 0; -}; - - -/** - * Returns the text content of the current node, without markup and invisible - * symbols. New lines are stripped and whitespace is collapsed, - * such that each character would be visible. - * - * In browsers that support it, innerText is used. Other browsers attempt to - * simulate it via node traversal. Line breaks are canonicalized in IE. - * - * @param {Node} node The node from which we are getting content. - * @return {string} The text content. - */ -goog.dom.getTextContent = function(node) { - var textContent; - // Note(arv): IE9, Opera, and Safari 3 support innerText but they include - // text nodes in script tags. So we revert to use a user agent test here. - if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && ('innerText' in node)) { - textContent = goog.string.canonicalizeNewlines(node.innerText); - // Unfortunately .innerText() returns text with ­ symbols - // We need to filter it out and then remove duplicate whitespaces - } else { - var buf = []; - goog.dom.getTextContent_(node, buf, true); - textContent = buf.join(''); - } - - // Strip ­ entities. goog.format.insertWordBreaks inserts them in Opera. - textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, ''); - // Strip ​ entities. goog.format.insertWordBreaks inserts them in IE8. - textContent = textContent.replace(/\u200B/g, ''); - - // Skip this replacement on old browsers with working innerText, which - // automatically turns into ' ' and / +/ into ' ' when reading - // innerText. - if (!goog.dom.BrowserFeature.CAN_USE_INNER_TEXT) { - textContent = textContent.replace(/ +/g, ' '); - } - if (textContent != ' ') { - textContent = textContent.replace(/^\s*/, ''); - } - - return textContent; -}; - - -/** - * Returns the text content of the current node, without markup. - * - * Unlike {@code getTextContent} this method does not collapse whitespaces - * or normalize lines breaks. - * - * @param {Node} node The node from which we are getting content. - * @return {string} The raw text content. - */ -goog.dom.getRawTextContent = function(node) { - var buf = []; - goog.dom.getTextContent_(node, buf, false); - - return buf.join(''); -}; - - -/** - * Recursive support function for text content retrieval. - * - * @param {Node} node The node from which we are getting content. - * @param {Array<string>} buf string buffer. - * @param {boolean} normalizeWhitespace Whether to normalize whitespace. - * @private - */ -goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) { - if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) { - // ignore certain tags - } else if (node.nodeType == goog.dom.NodeType.TEXT) { - if (normalizeWhitespace) { - buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, '')); - } else { - buf.push(node.nodeValue); - } - } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) { - buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]); - } else { - var child = node.firstChild; - while (child) { - goog.dom.getTextContent_(child, buf, normalizeWhitespace); - child = child.nextSibling; - } - } -}; - - -/** - * Returns the text length of the text contained in a node, without markup. This - * is equivalent to the selection length if the node was selected, or the number - * of cursor movements to traverse the node. Images & BRs take one space. New - * lines are ignored. - * - * @param {Node} node The node whose text content length is being calculated. - * @return {number} The length of {@code node}'s text content. - */ -goog.dom.getNodeTextLength = function(node) { - return goog.dom.getTextContent(node).length; -}; - - -/** - * Returns the text offset of a node relative to one of its ancestors. The text - * length is the same as the length calculated by goog.dom.getNodeTextLength. - * - * @param {Node} node The node whose offset is being calculated. - * @param {Node=} opt_offsetParent The node relative to which the offset will - * be calculated. Defaults to the node's owner document's body. - * @return {number} The text offset. - */ -goog.dom.getNodeTextOffset = function(node, opt_offsetParent) { - var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body; - var buf = []; - while (node && node != root) { - var cur = node; - while ((cur = cur.previousSibling)) { - buf.unshift(goog.dom.getTextContent(cur)); - } - node = node.parentNode; - } - // Trim left to deal with FF cases when there might be line breaks and empty - // nodes at the front of the text - return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length; -}; - - -/** - * Returns the node at a given offset in a parent node. If an object is - * provided for the optional third parameter, the node and the remainder of the - * offset will stored as properties of this object. - * @param {Node} parent The parent node. - * @param {number} offset The offset into the parent node. - * @param {Object=} opt_result Object to be used to store the return value. The - * return value will be stored in the form {node: Node, remainder: number} - * if this object is provided. - * @return {Node} The node at the given offset. - */ -goog.dom.getNodeAtOffset = function(parent, offset, opt_result) { - var stack = [parent], pos = 0, cur = null; - while (stack.length > 0 && pos < offset) { - cur = stack.pop(); - if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) { - // ignore certain tags - } else if (cur.nodeType == goog.dom.NodeType.TEXT) { - var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' '); - pos += text.length; - } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) { - pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length; - } else { - for (var i = cur.childNodes.length - 1; i >= 0; i--) { - stack.push(cur.childNodes[i]); - } - } - } - if (goog.isObject(opt_result)) { - opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0; - opt_result.node = cur; - } - - return cur; -}; - - -/** - * Returns true if the object is a {@code NodeList}. To qualify as a NodeList, - * the object must have a numeric length property and an item function (which - * has type 'string' on IE for some reason). - * @param {Object} val Object to test. - * @return {boolean} Whether the object is a NodeList. - */ -goog.dom.isNodeList = function(val) { - // TODO(attila): Now the isNodeList is part of goog.dom we can use - // goog.userAgent to make this simpler. - // A NodeList must have a length property of type 'number' on all platforms. - if (val && typeof val.length == 'number') { - // A NodeList is an object everywhere except Safari, where it's a function. - if (goog.isObject(val)) { - // A NodeList must have an item function (on non-IE platforms) or an item - // property of type 'string' (on IE). - return typeof val.item == 'function' || typeof val.item == 'string'; - } else if (goog.isFunction(val)) { - // On Safari, a NodeList is a function with an item property that is also - // a function. - return typeof val.item == 'function'; - } - } - - // Not a NodeList. - return false; -}; - - -/** - * Walks up the DOM hierarchy returning the first ancestor that has the passed - * tag name and/or class name. If the passed element matches the specified - * criteria, the element itself is returned. - * @param {Node} element The DOM node to start with. - * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or - * null/undefined to match only based on class name). - * @param {?string=} opt_class The class name to match (or null/undefined to - * match only based on tag name). - * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the - * dom. - * @return {Element} The first ancestor that matches the passed criteria, or - * null if no match is found. - */ -goog.dom.getAncestorByTagNameAndClass = function(element, opt_tag, opt_class, - opt_maxSearchSteps) { - if (!opt_tag && !opt_class) { - return null; - } - var tagName = opt_tag ? opt_tag.toUpperCase() : null; - return /** @type {Element} */ (goog.dom.getAncestor(element, - function(node) { - return (!tagName || node.nodeName == tagName) && - (!opt_class || goog.isString(node.className) && - goog.array.contains(node.className.split(/\s+/), opt_class)); - }, true, opt_maxSearchSteps)); -}; - - -/** - * Walks up the DOM hierarchy returning the first ancestor that has the passed - * class name. If the passed element matches the specified criteria, the - * element itself is returned. - * @param {Node} element The DOM node to start with. - * @param {string} className The class name to match. - * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the - * dom. - * @return {Element} The first ancestor that matches the passed criteria, or - * null if none match. - */ -goog.dom.getAncestorByClass = function(element, className, opt_maxSearchSteps) { - return goog.dom.getAncestorByTagNameAndClass(element, null, className, - opt_maxSearchSteps); -}; - - -/** - * Walks up the DOM hierarchy returning the first ancestor that passes the - * matcher function. - * @param {Node} element The DOM node to start with. - * @param {function(Node) : boolean} matcher A function that returns true if the - * passed node matches the desired criteria. - * @param {boolean=} opt_includeNode If true, the node itself is included in - * the search (the first call to the matcher will pass startElement as - * the node to test). - * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the - * dom. - * @return {Node} DOM node that matched the matcher, or null if there was - * no match. - */ -goog.dom.getAncestor = function( - element, matcher, opt_includeNode, opt_maxSearchSteps) { - if (!opt_includeNode) { - element = element.parentNode; - } - var ignoreSearchSteps = opt_maxSearchSteps == null; - var steps = 0; - while (element && (ignoreSearchSteps || steps <= opt_maxSearchSteps)) { - if (matcher(element)) { - return element; - } - element = element.parentNode; - steps++; - } - // Reached the root of the DOM without a match - return null; -}; - - -/** - * Determines the active element in the given document. - * @param {Document} doc The document to look in. - * @return {Element} The active element. - */ -goog.dom.getActiveElement = function(doc) { - try { - return doc && doc.activeElement; - } catch (e) { - // NOTE(nicksantos): Sometimes, evaluating document.activeElement in IE - // throws an exception. I'm not 100% sure why, but I suspect it chokes - // on document.activeElement if the activeElement has been recently - // removed from the DOM by a JS operation. - // - // We assume that an exception here simply means - // "there is no active element." - } - - return null; -}; - - -/** - * Gives the current devicePixelRatio. - * - * By default, this is the value of window.devicePixelRatio (which should be - * preferred if present). - * - * If window.devicePixelRatio is not present, the ratio is calculated with - * window.matchMedia, if present. Otherwise, gives 1.0. - * - * Some browsers (including Chrome) consider the browser zoom level in the pixel - * ratio, so the value may change across multiple calls. - * - * @return {number} The number of actual pixels per virtual pixel. - */ -goog.dom.getPixelRatio = function() { - var win = goog.dom.getWindow(); - - // devicePixelRatio does not work on Mobile firefox. - // TODO(user): Enable this check on a known working mobile Gecko version. - // Filed a bug: https://bugzilla.mozilla.org/show_bug.cgi?id=896804 - var isFirefoxMobile = goog.userAgent.GECKO && goog.userAgent.MOBILE; - - if (goog.isDef(win.devicePixelRatio) && !isFirefoxMobile) { - return win.devicePixelRatio; - } else if (win.matchMedia) { - return goog.dom.matchesPixelRatio_(.75) || - goog.dom.matchesPixelRatio_(1.5) || - goog.dom.matchesPixelRatio_(2) || - goog.dom.matchesPixelRatio_(3) || 1; - } - return 1; -}; - - -/** - * Calculates a mediaQuery to check if the current device supports the - * given actual to virtual pixel ratio. - * @param {number} pixelRatio The ratio of actual pixels to virtual pixels. - * @return {number} pixelRatio if applicable, otherwise 0. - * @private - */ -goog.dom.matchesPixelRatio_ = function(pixelRatio) { - var win = goog.dom.getWindow(); - var query = ('(-webkit-min-device-pixel-ratio: ' + pixelRatio + '),' + - '(min--moz-device-pixel-ratio: ' + pixelRatio + '),' + - '(min-resolution: ' + pixelRatio + 'dppx)'); - return win.matchMedia(query).matches ? pixelRatio : 0; -}; - - - -/** - * Create an instance of a DOM helper with a new document object. - * @param {Document=} opt_document Document object to associate with this - * DOM helper. - * @constructor - */ -goog.dom.DomHelper = function(opt_document) { - /** - * Reference to the document object to use - * @type {!Document} - * @private - */ - this.document_ = opt_document || goog.global.document || document; -}; - - -/** - * Gets the dom helper object for the document where the element resides. - * @param {Node=} opt_node If present, gets the DomHelper for this node. - * @return {!goog.dom.DomHelper} The DomHelper. - */ -goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper; - - -/** - * Sets the document object. - * @param {!Document} document Document object. - */ -goog.dom.DomHelper.prototype.setDocument = function(document) { - this.document_ = document; -}; - - -/** - * Gets the document object being used by the dom library. - * @return {!Document} Document object. - */ -goog.dom.DomHelper.prototype.getDocument = function() { - return this.document_; -}; - - -/** - * Alias for {@code getElementById}. If a DOM node is passed in then we just - * return that. - * @param {string|Element} element Element ID or a DOM node. - * @return {Element} The element with the given ID, or the node passed in. - */ -goog.dom.DomHelper.prototype.getElement = function(element) { - return goog.dom.getElementHelper_(this.document_, element); -}; - - -/** - * Gets an element by id, asserting that the element is found. - * - * This is used when an element is expected to exist, and should fail with - * an assertion error if it does not (if assertions are enabled). - * - * @param {string} id Element ID. - * @return {!Element} The element with the given ID, if it exists. - */ -goog.dom.DomHelper.prototype.getRequiredElement = function(id) { - return goog.dom.getRequiredElementHelper_(this.document_, id); -}; - - -/** - * Alias for {@code getElement}. - * @param {string|Element} element Element ID or a DOM node. - * @return {Element} The element with the given ID, or the node passed in. - * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead. - */ -goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement; - - -/** - * Looks up elements by both tag and class name, using browser native functions - * ({@code querySelectorAll}, {@code getElementsByTagName} or - * {@code getElementsByClassName}) where possible. The returned array is a live - * NodeList or a static list depending on the code path taken. - * - * @see goog.dom.query - * - * @param {?string=} opt_tag Element tag name or * for all tags. - * @param {?string=} opt_class Optional class name. - * @param {(Document|Element)=} opt_el Optional element to look in. - * @return { {length: number} } Array-like list of elements (only a length - * property and numerical indices are guaranteed to exist). - */ -goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag, - opt_class, - opt_el) { - return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag, - opt_class, opt_el); -}; - - -/** - * Returns an array of all the elements with the provided className. - * @see {goog.dom.query} - * @param {string} className the name of the class to look for. - * @param {Element|Document=} opt_el Optional element to look in. - * @return { {length: number} } The items found with the class name provided. - */ -goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) { - var doc = opt_el || this.document_; - return goog.dom.getElementsByClass(className, doc); -}; - - -/** - * Returns the first element we find matching the provided class name. - * @see {goog.dom.query} - * @param {string} className the name of the class to look for. - * @param {(Element|Document)=} opt_el Optional element to look in. - * @return {Element} The first item found with the class name provided. - */ -goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) { - var doc = opt_el || this.document_; - return goog.dom.getElementByClass(className, doc); -}; - - -/** - * Ensures an element with the given className exists, and then returns the - * first element with the provided className. - * @see {goog.dom.query} - * @param {string} className the name of the class to look for. - * @param {(!Element|!Document)=} opt_root Optional element or document to look - * in. - * @return {!Element|null} The first item found with the class name provided. - * @throws {goog.asserts.AssertionError} Thrown if no element is found. - */ -goog.dom.DomHelper.prototype.getRequiredElementByClass = function(className, - opt_root) { - var root = opt_root || this.document_; - return goog.dom.getRequiredElementByClass(className, root); -}; - - -/** - * Alias for {@code getElementsByTagNameAndClass}. - * @deprecated Use DomHelper getElementsByTagNameAndClass. - * @see goog.dom.query - * - * @param {?string=} opt_tag Element tag name. - * @param {?string=} opt_class Optional class name. - * @param {Element=} opt_el Optional element to look in. - * @return { {length: number} } Array-like list of elements (only a length - * property and numerical indices are guaranteed to exist). - */ -goog.dom.DomHelper.prototype.$$ = - goog.dom.DomHelper.prototype.getElementsByTagNameAndClass; - - -/** - * Sets a number of properties on a node. - * @param {Element} element DOM node to set properties on. - * @param {Object} properties Hash of property:value pairs. - */ -goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties; - - -/** - * Gets the dimensions of the viewport. - * @param {Window=} opt_window Optional window element to test. Defaults to - * the window of the Dom Helper. - * @return {!goog.math.Size} Object with values 'width' and 'height'. - */ -goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) { - // TODO(arv): This should not take an argument. That breaks the rule of a - // a DomHelper representing a single frame/window/document. - return goog.dom.getViewportSize(opt_window || this.getWindow()); -}; - - -/** - * Calculates the height of the document. - * - * @return {number} The height of the document. - */ -goog.dom.DomHelper.prototype.getDocumentHeight = function() { - return goog.dom.getDocumentHeight_(this.getWindow()); -}; - - -/** - * Typedef for use with goog.dom.createDom and goog.dom.append. - * @typedef {Object|string|Array|NodeList} - */ -goog.dom.Appendable; - - -/** - * Returns a dom node with a set of attributes. This function accepts varargs - * for subsequent nodes to be added. Subsequent nodes will be added to the - * first node as childNodes. - * - * So: - * <code>createDom('div', null, createDom('p'), createDom('p'));</code> - * would return a div with two child paragraphs - * - * An easy way to move all child nodes of an existing element to a new parent - * element is: - * <code>createDom('div', null, oldElement.childNodes);</code> - * which will remove all child nodes from the old element and add them as - * child nodes of the new DIV. - * - * @param {string} tagName Tag to create. - * @param {Object|string=} opt_attributes If object, then a map of name-value - * pairs for attributes. If a string, then this is the className of the new - * element. - * @param {...goog.dom.Appendable} var_args Further DOM nodes or - * strings for text nodes. If one of the var_args is an array or - * NodeList, its elements will be added as childNodes instead. - * @return {!Element} Reference to a DOM node. - */ -goog.dom.DomHelper.prototype.createDom = function(tagName, - opt_attributes, - var_args) { - return goog.dom.createDom_(this.document_, arguments); -}; - - -/** - * Alias for {@code createDom}. - * @param {string} tagName Tag to create. - * @param {(Object|string)=} opt_attributes If object, then a map of name-value - * pairs for attributes. If a string, then this is the className of the new - * element. - * @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for - * text nodes. If one of the var_args is an array, its children will be - * added as childNodes instead. - * @return {!Element} Reference to a DOM node. - * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead. - */ -goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom; - - -/** - * Creates a new element. - * @param {string} name Tag name. - * @return {!Element} The new element. - */ -goog.dom.DomHelper.prototype.createElement = function(name) { - return this.document_.createElement(name); -}; - - -/** - * Creates a new text node. - * @param {number|string} content Content. - * @return {!Text} The new text node. - */ -goog.dom.DomHelper.prototype.createTextNode = function(content) { - return this.document_.createTextNode(String(content)); -}; - - -/** - * Create a table. - * @param {number} rows The number of rows in the table. Must be >= 1. - * @param {number} columns The number of columns in the table. Must be >= 1. - * @param {boolean=} opt_fillWithNbsp If true, fills table entries with - * {@code goog.string.Unicode.NBSP} characters. - * @return {!HTMLElement} The created table. - */ -goog.dom.DomHelper.prototype.createTable = function(rows, columns, - opt_fillWithNbsp) { - return goog.dom.createTable_(this.document_, rows, columns, - !!opt_fillWithNbsp); -}; - - -/** - * Converts an HTML into a node or a document fragment. A single Node is used if - * {@code html} only generates a single node. If {@code html} generates multiple - * nodes then these are put inside a {@code DocumentFragment}. - * @param {!goog.html.SafeHtml} html The HTML markup to convert. - * @return {!Node} The resulting node. - */ -goog.dom.DomHelper.prototype.safeHtmlToNode = function(html) { - return goog.dom.safeHtmlToNode_(this.document_, html); -}; - - -/** - * Converts an HTML string into a node or a document fragment. A single Node - * is used if the {@code htmlString} only generates a single node. If the - * {@code htmlString} generates multiple nodes then these are put inside a - * {@code DocumentFragment}. - * - * @param {string} htmlString The HTML string to convert. - * @return {!Node} The resulting node. - */ -goog.dom.DomHelper.prototype.htmlToDocumentFragment = function(htmlString) { - return goog.dom.htmlToDocumentFragment_(this.document_, htmlString); -}; - - -/** - * Returns true if the browser is in "CSS1-compatible" (standards-compliant) - * mode, false otherwise. - * @return {boolean} True if in CSS1-compatible mode. - */ -goog.dom.DomHelper.prototype.isCss1CompatMode = function() { - return goog.dom.isCss1CompatMode_(this.document_); -}; - - -/** - * Gets the window object associated with the document. - * @return {!Window} The window associated with the given document. - */ -goog.dom.DomHelper.prototype.getWindow = function() { - return goog.dom.getWindow_(this.document_); -}; - - -/** - * Gets the document scroll element. - * @return {!Element} Scrolling element. - */ -goog.dom.DomHelper.prototype.getDocumentScrollElement = function() { - return goog.dom.getDocumentScrollElement_(this.document_); -}; - - -/** - * Gets the document scroll distance as a coordinate object. - * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'. - */ -goog.dom.DomHelper.prototype.getDocumentScroll = function() { - return goog.dom.getDocumentScroll_(this.document_); -}; - - -/** - * Determines the active element in the given document. - * @param {Document=} opt_doc The document to look in. - * @return {Element} The active element. - */ -goog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) { - return goog.dom.getActiveElement(opt_doc || this.document_); -}; - - -/** - * Appends a child to a node. - * @param {Node} parent Parent. - * @param {Node} child Child. - */ -goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild; - - -/** - * Appends a node with text or other nodes. - * @param {!Node} parent The node to append nodes to. - * @param {...goog.dom.Appendable} var_args The things to append to the node. - * If this is a Node it is appended as is. - * If this is a string then a text node is appended. - * If this is an array like object then fields 0 to length - 1 are appended. - */ -goog.dom.DomHelper.prototype.append = goog.dom.append; - - -/** - * Determines if the given node can contain children, intended to be used for - * HTML generation. - * - * @param {Node} node The node to check. - * @return {boolean} Whether the node can contain children. - */ -goog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren; - - -/** - * Removes all the child nodes on a DOM node. - * @param {Node} node Node to remove children from. - */ -goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren; - - -/** - * Inserts a new node before an existing reference node (i.e., as the previous - * sibling). If the reference node has no parent, then does nothing. - * @param {Node} newNode Node to insert. - * @param {Node} refNode Reference node to insert before. - */ -goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore; - - -/** - * Inserts a new node after an existing reference node (i.e., as the next - * sibling). If the reference node has no parent, then does nothing. - * @param {Node} newNode Node to insert. - * @param {Node} refNode Reference node to insert after. - */ -goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter; - - -/** - * Insert a child at a given index. If index is larger than the number of child - * nodes that the parent currently has, the node is inserted as the last child - * node. - * @param {Element} parent The element into which to insert the child. - * @param {Node} child The element to insert. - * @param {number} index The index at which to insert the new child node. Must - * not be negative. - */ -goog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt; - - -/** - * Removes a node from its parent. - * @param {Node} node The node to remove. - * @return {Node} The node removed if removed; else, null. - */ -goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode; - - -/** - * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no - * parent. - * @param {Node} newNode Node to insert. - * @param {Node} oldNode Node to replace. - */ -goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode; - - -/** - * Flattens an element. That is, removes it and replace it with its children. - * @param {Element} element The element to flatten. - * @return {Element|undefined} The original element, detached from the document - * tree, sans children, or undefined if the element was already not in the - * document. - */ -goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement; - - -/** - * Returns an array containing just the element children of the given element. - * @param {Element} element The element whose element children we want. - * @return {!(Array|NodeList)} An array or array-like list of just the element - * children of the given element. - */ -goog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren; - - -/** - * Returns the first child node that is an element. - * @param {Node} node The node to get the first child element of. - * @return {Element} The first child node of {@code node} that is an element. - */ -goog.dom.DomHelper.prototype.getFirstElementChild = - goog.dom.getFirstElementChild; - - -/** - * Returns the last child node that is an element. - * @param {Node} node The node to get the last child element of. - * @return {Element} The last child node of {@code node} that is an element. - */ -goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild; - - -/** - * Returns the first next sibling that is an element. - * @param {Node} node The node to get the next sibling element of. - * @return {Element} The next sibling of {@code node} that is an element. - */ -goog.dom.DomHelper.prototype.getNextElementSibling = - goog.dom.getNextElementSibling; - - -/** - * Returns the first previous sibling that is an element. - * @param {Node} node The node to get the previous sibling element of. - * @return {Element} The first previous sibling of {@code node} that is - * an element. - */ -goog.dom.DomHelper.prototype.getPreviousElementSibling = - goog.dom.getPreviousElementSibling; - - -/** - * Returns the next node in source order from the given node. - * @param {Node} node The node. - * @return {Node} The next node in the DOM tree, or null if this was the last - * node. - */ -goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode; - - -/** - * Returns the previous node in source order from the given node. - * @param {Node} node The node. - * @return {Node} The previous node in the DOM tree, or null if this was the - * first node. - */ -goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode; - - -/** - * Whether the object looks like a DOM node. - * @param {?} obj The object being tested for node likeness. - * @return {boolean} Whether the object looks like a DOM node. - */ -goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike; - - -/** - * Whether the object looks like an Element. - * @param {?} obj The object being tested for Element likeness. - * @return {boolean} Whether the object looks like an Element. - */ -goog.dom.DomHelper.prototype.isElement = goog.dom.isElement; - - -/** - * Returns true if the specified value is a Window object. This includes the - * global window for HTML pages, and iframe windows. - * @param {?} obj Variable to test. - * @return {boolean} Whether the variable is a window. - */ -goog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow; - - -/** - * Returns an element's parent, if it's an Element. - * @param {Element} element The DOM element. - * @return {Element} The parent, or null if not an Element. - */ -goog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement; - - -/** - * Whether a node contains another node. - * @param {Node} parent The node that should contain the other node. - * @param {Node} descendant The node to test presence of. - * @return {boolean} Whether the parent node contains the descendent node. - */ -goog.dom.DomHelper.prototype.contains = goog.dom.contains; - - -/** - * Compares the document order of two nodes, returning 0 if they are the same - * node, a negative number if node1 is before node2, and a positive number if - * node2 is before node1. Note that we compare the order the tags appear in the - * document so in the tree <b><i>text</i></b> the B node is considered to be - * before the I node. - * - * @param {Node} node1 The first node to compare. - * @param {Node} node2 The second node to compare. - * @return {number} 0 if the nodes are the same node, a negative number if node1 - * is before node2, and a positive number if node2 is before node1. - */ -goog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder; - - -/** - * Find the deepest common ancestor of the given nodes. - * @param {...Node} var_args The nodes to find a common ancestor of. - * @return {Node} The common ancestor of the nodes, or null if there is none. - * null will only be returned if two or more of the nodes are from different - * documents. - */ -goog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor; - - -/** - * Returns the owner document for a node. - * @param {Node} node The node to get the document for. - * @return {!Document} The document owning the node. - */ -goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument; - - -/** - * Cross browser function for getting the document element of an iframe. - * @param {Element} iframe Iframe element. - * @return {!Document} The frame content document. - */ -goog.dom.DomHelper.prototype.getFrameContentDocument = - goog.dom.getFrameContentDocument; - - -/** - * Cross browser function for getting the window of a frame or iframe. - * @param {Element} frame Frame element. - * @return {Window} The window associated with the given frame. - */ -goog.dom.DomHelper.prototype.getFrameContentWindow = - goog.dom.getFrameContentWindow; - - -/** - * Sets the text content of a node, with cross-browser support. - * @param {Node} node The node to change the text content of. - * @param {string|number} text The value that should replace the node's content. - */ -goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent; - - -/** - * Gets the outerHTML of a node, which islike innerHTML, except that it - * actually contains the HTML of the node itself. - * @param {Element} element The element to get the HTML of. - * @return {string} The outerHTML of the given element. - */ -goog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml; - - -/** - * Finds the first descendant node that matches the filter function. This does - * a depth first search. - * @param {Node} root The root of the tree to search. - * @param {function(Node) : boolean} p The filter function. - * @return {Node|undefined} The found node or undefined if none is found. - */ -goog.dom.DomHelper.prototype.findNode = goog.dom.findNode; - - -/** - * Finds all the descendant nodes that matches the filter function. This does a - * depth first search. - * @param {Node} root The root of the tree to search. - * @param {function(Node) : boolean} p The filter function. - * @return {Array<Node>} The found nodes or an empty array if none are found. - */ -goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes; - - -/** - * Returns true if the element has a tab index that allows it to receive - * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements - * natively support keyboard focus, even if they have no tab index. - * @param {!Element} element Element to check. - * @return {boolean} Whether the element has a tab index that allows keyboard - * focus. - */ -goog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex; - - -/** - * Enables or disables keyboard focus support on the element via its tab index. - * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true - * (or elements that natively support keyboard focus, like form elements) can - * receive keyboard focus. See http://go/tabindex for more info. - * @param {Element} element Element whose tab index is to be changed. - * @param {boolean} enable Whether to set or remove a tab index on the element - * that supports keyboard focus. - */ -goog.dom.DomHelper.prototype.setFocusableTabIndex = - goog.dom.setFocusableTabIndex; - - -/** - * Returns true if the element can be focused, i.e. it has a tab index that - * allows it to receive keyboard focus (tabIndex >= 0), or it is an element - * that natively supports keyboard focus. - * @param {!Element} element Element to check. - * @return {boolean} Whether the element allows keyboard focus. - */ -goog.dom.DomHelper.prototype.isFocusable = goog.dom.isFocusable; - - -/** - * Returns the text contents of the current node, without markup. New lines are - * stripped and whitespace is collapsed, such that each character would be - * visible. - * - * In browsers that support it, innerText is used. Other browsers attempt to - * simulate it via node traversal. Line breaks are canonicalized in IE. - * - * @param {Node} node The node from which we are getting content. - * @return {string} The text content. - */ -goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent; - - -/** - * Returns the text length of the text contained in a node, without markup. This - * is equivalent to the selection length if the node was selected, or the number - * of cursor movements to traverse the node. Images & BRs take one space. New - * lines are ignored. - * - * @param {Node} node The node whose text content length is being calculated. - * @return {number} The length of {@code node}'s text content. - */ -goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength; - - -/** - * Returns the text offset of a node relative to one of its ancestors. The text - * length is the same as the length calculated by - * {@code goog.dom.getNodeTextLength}. - * - * @param {Node} node The node whose offset is being calculated. - * @param {Node=} opt_offsetParent Defaults to the node's owner document's body. - * @return {number} The text offset. - */ -goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset; - - -/** - * Returns the node at a given offset in a parent node. If an object is - * provided for the optional third parameter, the node and the remainder of the - * offset will stored as properties of this object. - * @param {Node} parent The parent node. - * @param {number} offset The offset into the parent node. - * @param {Object=} opt_result Object to be used to store the return value. The - * return value will be stored in the form {node: Node, remainder: number} - * if this object is provided. - * @return {Node} The node at the given offset. - */ -goog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset; - - -/** - * Returns true if the object is a {@code NodeList}. To qualify as a NodeList, - * the object must have a numeric length property and an item function (which - * has type 'string' on IE for some reason). - * @param {Object} val Object to test. - * @return {boolean} Whether the object is a NodeList. - */ -goog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList; - - -/** - * Walks up the DOM hierarchy returning the first ancestor that has the passed - * tag name and/or class name. If the passed element matches the specified - * criteria, the element itself is returned. - * @param {Node} element The DOM node to start with. - * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or - * null/undefined to match only based on class name). - * @param {?string=} opt_class The class name to match (or null/undefined to - * match only based on tag name). - * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the - * dom. - * @return {Element} The first ancestor that matches the passed criteria, or - * null if no match is found. - */ -goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass = - goog.dom.getAncestorByTagNameAndClass; - - -/** - * Walks up the DOM hierarchy returning the first ancestor that has the passed - * class name. If the passed element matches the specified criteria, the - * element itself is returned. - * @param {Node} element The DOM node to start with. - * @param {string} class The class name to match. - * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the - * dom. - * @return {Element} The first ancestor that matches the passed criteria, or - * null if none match. - */ -goog.dom.DomHelper.prototype.getAncestorByClass = - goog.dom.getAncestorByClass; - - -/** - * Walks up the DOM hierarchy returning the first ancestor that passes the - * matcher function. - * @param {Node} element The DOM node to start with. - * @param {function(Node) : boolean} matcher A function that returns true if the - * passed node matches the desired criteria. - * @param {boolean=} opt_includeNode If true, the node itself is included in - * the search (the first call to the matcher will pass startElement as - * the node to test). - * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the - * dom. - * @return {Node} DOM node that matched the matcher, or null if there was - * no match. - */ -goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/nodetype.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/nodetype.js deleted file mode 100644 index cccb470..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/nodetype.js +++ /dev/null @@ -1,48 +0,0 @@ -// 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 Definition of goog.dom.NodeType. - */ - -goog.provide('goog.dom.NodeType'); - - -/** - * Constants for the nodeType attribute in the Node interface. - * - * These constants match those specified in the Node interface. These are - * usually present on the Node object in recent browsers, but not in older - * browsers (specifically, early IEs) and thus are given here. - * - * In some browsers (early IEs), these are not defined on the Node object, - * so they are provided here. - * - * See http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247 - * @enum {number} - */ -goog.dom.NodeType = { - ELEMENT: 1, - ATTRIBUTE: 2, - TEXT: 3, - CDATA_SECTION: 4, - ENTITY_REFERENCE: 5, - ENTITY: 6, - PROCESSING_INSTRUCTION: 7, - COMMENT: 8, - DOCUMENT: 9, - DOCUMENT_TYPE: 10, - DOCUMENT_FRAGMENT: 11, - NOTATION: 12 -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/safe.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/safe.js deleted file mode 100644 index 0d236bd..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/safe.js +++ /dev/null @@ -1,135 +0,0 @@ -// 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 Type-safe wrappers for unsafe DOM APIs. - * - * This file provides type-safe wrappers for DOM APIs that can result in - * cross-site scripting (XSS) vulnerabilities, if the API is supplied with - * untrusted (attacker-controlled) input. Instead of plain strings, the type - * safe wrappers consume values of types from the goog.html package whose - * contract promises that values are safe to use in the corresponding context. - * - * Hence, a program that exclusively uses the wrappers in this file (i.e., whose - * only reference to security-sensitive raw DOM APIs are in this file) is - * guaranteed to be free of XSS due to incorrect use of such DOM APIs (modulo - * correctness of code that produces values of the respective goog.html types, - * and absent code that violates type safety). - * - * For example, assigning to an element's .innerHTML property a string that is - * derived (even partially) from untrusted input typically results in an XSS - * vulnerability. The type-safe wrapper goog.html.setInnerHtml consumes a value - * of type goog.html.SafeHtml, whose contract states that using its values in a - * HTML context will not result in XSS. Hence a program that is free of direct - * assignments to any element's innerHTML property (with the exception of the - * assignment to .innerHTML in this file) is guaranteed to be free of XSS due to - * assignment of untrusted strings to the innerHTML property. - */ - -goog.provide('goog.dom.safe'); - -goog.require('goog.html.SafeHtml'); -goog.require('goog.html.SafeUrl'); - - -/** - * Assigns known-safe HTML to an element's innerHTML property. - * @param {!Element} elem The element whose innerHTML is to be assigned to. - * @param {!goog.html.SafeHtml} html The known-safe HTML to assign. - */ -goog.dom.safe.setInnerHtml = function(elem, html) { - elem.innerHTML = goog.html.SafeHtml.unwrap(html); -}; - - -/** - * Assigns known-safe HTML to an element's outerHTML property. - * @param {!Element} elem The element whose outerHTML is to be assigned to. - * @param {!goog.html.SafeHtml} html The known-safe HTML to assign. - */ -goog.dom.safe.setOuterHtml = function(elem, html) { - elem.outerHTML = goog.html.SafeHtml.unwrap(html); -}; - - -/** - * Writes known-safe HTML to a document. - * @param {!Document} doc The document to be written to. - * @param {!goog.html.SafeHtml} html The known-safe HTML to assign. - */ -goog.dom.safe.documentWrite = function(doc, html) { - doc.write(goog.html.SafeHtml.unwrap(html)); -}; - - -/** - * Safely assigns a URL to an anchor element's href property. - * - * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to - * anchor's href property. If url is of type string however, it is first - * sanitized using goog.html.SafeUrl.sanitize. - * - * Example usage: - * goog.dom.safe.setAnchorHref(anchorEl, url); - * which is a safe alternative to - * anchorEl.href = url; - * The latter can result in XSS vulnerabilities if url is a - * user-/attacker-controlled value. - * - * @param {!HTMLAnchorElement} anchor The anchor element whose href property - * is to be assigned to. - * @param {string|!goog.html.SafeUrl} url The URL to assign. - * @see goog.html.SafeUrl#sanitize - */ -goog.dom.safe.setAnchorHref = function(anchor, url) { - /** @type {!goog.html.SafeUrl} */ - var safeUrl; - if (url instanceof goog.html.SafeUrl) { - safeUrl = url; - } else { - safeUrl = goog.html.SafeUrl.sanitize(url); - } - anchor.href = goog.html.SafeUrl.unwrap(safeUrl); -}; - - -/** - * Safely assigns a URL to a Location object's href property. - * - * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to - * loc's href property. If url is of type string however, it is first sanitized - * using goog.html.SafeUrl.sanitize. - * - * Example usage: - * goog.dom.safe.setLocationHref(document.location, redirectUrl); - * which is a safe alternative to - * document.location.href = redirectUrl; - * The latter can result in XSS vulnerabilities if redirectUrl is a - * user-/attacker-controlled value. - * - * @param {!Location} loc The Location object whose href property is to be - * assigned to. - * @param {string|!goog.html.SafeUrl} url The URL to assign. - * @see goog.html.SafeUrl#sanitize - */ -goog.dom.safe.setLocationHref = function(loc, url) { - /** @type {!goog.html.SafeUrl} */ - var safeUrl; - if (url instanceof goog.html.SafeUrl) { - safeUrl = url; - } else { - safeUrl = goog.html.SafeUrl.sanitize(url); - } - loc.href = goog.html.SafeUrl.unwrap(safeUrl); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/tagname.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/tagname.js deleted file mode 100644 index 77a9b47..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/tagname.js +++ /dev/null @@ -1,159 +0,0 @@ -// 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 the goog.dom.TagName enum. This enumerates - * all HTML tag names specified in either the the W3C HTML 4.01 index of - * elements or the HTML5 draft specification. - * - * References: - * http://www.w3.org/TR/html401/index/elements.html - * http://dev.w3.org/html5/spec/section-index.html - * - */ -goog.provide('goog.dom.TagName'); - - -/** - * Enum of all html tag names specified by the W3C HTML4.01 and HTML5 - * specifications. - * @enum {string} - */ -goog.dom.TagName = { - A: 'A', - ABBR: 'ABBR', - ACRONYM: 'ACRONYM', - ADDRESS: 'ADDRESS', - APPLET: 'APPLET', - AREA: 'AREA', - ARTICLE: 'ARTICLE', - ASIDE: 'ASIDE', - AUDIO: 'AUDIO', - B: 'B', - BASE: 'BASE', - BASEFONT: 'BASEFONT', - BDI: 'BDI', - BDO: 'BDO', - BIG: 'BIG', - BLOCKQUOTE: 'BLOCKQUOTE', - BODY: 'BODY', - BR: 'BR', - BUTTON: 'BUTTON', - CANVAS: 'CANVAS', - CAPTION: 'CAPTION', - CENTER: 'CENTER', - CITE: 'CITE', - CODE: 'CODE', - COL: 'COL', - COLGROUP: 'COLGROUP', - COMMAND: 'COMMAND', - DATA: 'DATA', - DATALIST: 'DATALIST', - DD: 'DD', - DEL: 'DEL', - DETAILS: 'DETAILS', - DFN: 'DFN', - DIALOG: 'DIALOG', - DIR: 'DIR', - DIV: 'DIV', - DL: 'DL', - DT: 'DT', - EM: 'EM', - EMBED: 'EMBED', - FIELDSET: 'FIELDSET', - FIGCAPTION: 'FIGCAPTION', - FIGURE: 'FIGURE', - FONT: 'FONT', - FOOTER: 'FOOTER', - FORM: 'FORM', - FRAME: 'FRAME', - FRAMESET: 'FRAMESET', - H1: 'H1', - H2: 'H2', - H3: 'H3', - H4: 'H4', - H5: 'H5', - H6: 'H6', - HEAD: 'HEAD', - HEADER: 'HEADER', - HGROUP: 'HGROUP', - HR: 'HR', - HTML: 'HTML', - I: 'I', - IFRAME: 'IFRAME', - IMG: 'IMG', - INPUT: 'INPUT', - INS: 'INS', - ISINDEX: 'ISINDEX', - KBD: 'KBD', - KEYGEN: 'KEYGEN', - LABEL: 'LABEL', - LEGEND: 'LEGEND', - LI: 'LI', - LINK: 'LINK', - MAP: 'MAP', - MARK: 'MARK', - MATH: 'MATH', - MENU: 'MENU', - META: 'META', - METER: 'METER', - NAV: 'NAV', - NOFRAMES: 'NOFRAMES', - NOSCRIPT: 'NOSCRIPT', - OBJECT: 'OBJECT', - OL: 'OL', - OPTGROUP: 'OPTGROUP', - OPTION: 'OPTION', - OUTPUT: 'OUTPUT', - P: 'P', - PARAM: 'PARAM', - PRE: 'PRE', - PROGRESS: 'PROGRESS', - Q: 'Q', - RP: 'RP', - RT: 'RT', - RUBY: 'RUBY', - S: 'S', - SAMP: 'SAMP', - SCRIPT: 'SCRIPT', - SECTION: 'SECTION', - SELECT: 'SELECT', - SMALL: 'SMALL', - SOURCE: 'SOURCE', - SPAN: 'SPAN', - STRIKE: 'STRIKE', - STRONG: 'STRONG', - STYLE: 'STYLE', - SUB: 'SUB', - SUMMARY: 'SUMMARY', - SUP: 'SUP', - SVG: 'SVG', - TABLE: 'TABLE', - TBODY: 'TBODY', - TD: 'TD', - TEXTAREA: 'TEXTAREA', - TFOOT: 'TFOOT', - TH: 'TH', - THEAD: 'THEAD', - TIME: 'TIME', - TITLE: 'TITLE', - TR: 'TR', - TRACK: 'TRACK', - TT: 'TT', - U: 'U', - UL: 'UL', - VAR: 'VAR', - VIDEO: 'VIDEO', - WBR: 'WBR' -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/tags.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/tags.js deleted file mode 100644 index 159abe0..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/tags.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2014 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 for HTML element tag names. - */ -goog.provide('goog.dom.tags'); - -goog.require('goog.object'); - - -/** - * The void elements specified by - * http://www.w3.org/TR/html-markup/syntax.html#void-elements. - * @const - * @type {!Object} - * @private - */ -goog.dom.tags.VOID_TAGS_ = goog.object.createSet(('area,base,br,col,command,' + - 'embed,hr,img,input,keygen,link,meta,param,source,track,wbr').split(',')); - - -/** - * Checks whether the tag is void (with no contents allowed and no legal end - * tag), for example 'br'. - * @param {string} tagName The tag name in lower case. - * @return {boolean} - */ -goog.dom.tags.isVoidTag = function(tagName) { - return goog.dom.tags.VOID_TAGS_[tagName] === true; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/vendor.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/vendor.js deleted file mode 100644 index 7c1123e..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/dom/vendor.js +++ /dev/null @@ -1,96 +0,0 @@ -// 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 Vendor prefix getters. - */ - -goog.provide('goog.dom.vendor'); - -goog.require('goog.string'); -goog.require('goog.userAgent'); - - -/** - * Returns the JS vendor prefix used in CSS properties. Different vendors - * use different methods of changing the case of the property names. - * - * @return {?string} The JS vendor prefix or null if there is none. - */ -goog.dom.vendor.getVendorJsPrefix = function() { - if (goog.userAgent.WEBKIT) { - return 'Webkit'; - } else if (goog.userAgent.GECKO) { - return 'Moz'; - } else if (goog.userAgent.IE) { - return 'ms'; - } else if (goog.userAgent.OPERA) { - return 'O'; - } - - return null; -}; - - -/** - * Returns the vendor prefix used in CSS properties. - * - * @return {?string} The vendor prefix or null if there is none. - */ -goog.dom.vendor.getVendorPrefix = function() { - if (goog.userAgent.WEBKIT) { - return '-webkit'; - } else if (goog.userAgent.GECKO) { - return '-moz'; - } else if (goog.userAgent.IE) { - return '-ms'; - } else if (goog.userAgent.OPERA) { - return '-o'; - } - - return null; -}; - - -/** - * @param {string} propertyName A property name. - * @param {!Object=} opt_object If provided, we verify if the property exists in - * the object. - * @return {?string} A vendor prefixed property name, or null if it does not - * exist. - */ -goog.dom.vendor.getPrefixedPropertyName = function(propertyName, opt_object) { - // We first check for a non-prefixed property, if available. - if (opt_object && propertyName in opt_object) { - return propertyName; - } - var prefix = goog.dom.vendor.getVendorJsPrefix(); - if (prefix) { - prefix = prefix.toLowerCase(); - var prefixedPropertyName = prefix + goog.string.toTitleCase(propertyName); - return (!goog.isDef(opt_object) || prefixedPropertyName in opt_object) ? - prefixedPropertyName : null; - } - return null; -}; - - -/** - * @param {string} eventType An event type. - * @return {string} A lower-cased vendor prefixed event type. - */ -goog.dom.vendor.getPrefixedEventType = function(eventType) { - var prefix = goog.dom.vendor.getVendorJsPrefix() || ''; - return (prefix + eventType).toLowerCase(); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/browserevent.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/browserevent.js deleted file mode 100644 index 39c6131..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/browserevent.js +++ /dev/null @@ -1,405 +0,0 @@ -// 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' - * - 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> - * - * @author arv@google.com (Erik Arvidsson) - */ - -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) { - goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : ''); - - /** - * Target that fired the event. - * @override - * @type {Node} - */ - this.target = null; - - /** - * Node that had the listener attached. - * @override - * @type {Node|undefined} - */ - this.currentTarget = null; - - /** - * For mouseover and mouseout events, the related object for the event. - * @type {Node} - */ - this.relatedTarget = null; - - /** - * X-coordinate relative to target. - * @type {number} - */ - this.offsetX = 0; - - /** - * Y-coordinate relative to target. - * @type {number} - */ - this.offsetY = 0; - - /** - * X-coordinate relative to the window. - * @type {number} - */ - this.clientX = 0; - - /** - * Y-coordinate relative to the window. - * @type {number} - */ - this.clientY = 0; - - /** - * X-coordinate relative to the monitor. - * @type {number} - */ - this.screenX = 0; - - /** - * Y-coordinate relative to the monitor. - * @type {number} - */ - this.screenY = 0; - - /** - * Which mouse button was pressed. - * @type {number} - */ - this.button = 0; - - /** - * Keycode of key press. - * @type {number} - */ - this.keyCode = 0; - - /** - * Keycode of key press. - * @type {number} - */ - this.charCode = 0; - - /** - * Whether control was pressed at time of event. - * @type {boolean} - */ - this.ctrlKey = false; - - /** - * Whether alt was pressed at time of event. - * @type {boolean} - */ - this.altKey = false; - - /** - * Whether shift was pressed at time of event. - * @type {boolean} - */ - this.shiftKey = false; - - /** - * Whether the meta key was pressed at time of event. - * @type {boolean} - */ - this.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} - */ - this.state = null; - - /** - * 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} - */ - this.platformModifierKey = false; - - /** - * The browser event object. - * @private {Event} - */ - this.event_ = null; - - 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 -]; - - -/** - * 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; - - /** @type {Touch} */ - var relevantTouch = null; - if (type == goog.events.EventType.TOUCHSTART || - type == goog.events.EventType.TOUCHMOVE) { - relevantTouch = e.targetTouches[0]; - } else if (type == goog.events.EventType.TOUCHEND || - type == goog.events.EventType.TOUCHCANCEL) { - relevantTouch = e.changedTouches[0]; - } - - // TODO(nicksantos): Change this.target to type EventTarget. - this.target = goog.isNull(relevantTouch) ? - /** @type {Node} */ (e.target) || e.srcElement : relevantTouch.target; - - // 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; - - if (!goog.isNull(relevantTouch)) { - this.clientX = relevantTouch.clientX !== undefined ? - relevantTouch.clientX : relevantTouch.pageX; - this.clientY = relevantTouch.clientY !== undefined ? - relevantTouch.clientY : relevantTouch.pageY; - this.screenX = relevantTouch.screenX || 0; - this.screenY = relevantTouch.screenY || 0; - } else { - // 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(); - } -}; - - -/** - * 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_; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/browserfeature.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/browserfeature.js deleted file mode 100644 index 61b9d60..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/browserfeature.js +++ /dev/null @@ -1,85 +0,0 @@ -// 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 Browser capability checks for the events package. - * - */ - - -goog.provide('goog.events.BrowserFeature'); - -goog.require('goog.userAgent'); - - -/** - * Enum of browser capabilities. - * @enum {boolean} - */ -goog.events.BrowserFeature = { - /** - * Whether the button attribute of the event is W3C compliant. False in - * Internet Explorer prior to version 9; document-version dependent. - */ - HAS_W3C_BUTTON: !goog.userAgent.IE || - goog.userAgent.isDocumentModeOrHigher(9), - - /** - * Whether the browser supports full W3C event model. - */ - HAS_W3C_EVENT_SUPPORT: !goog.userAgent.IE || - goog.userAgent.isDocumentModeOrHigher(9), - - /** - * To prevent default in IE7-8 for certain keydown events we need set the - * keyCode to -1. - */ - SET_KEY_CODE_TO_PREVENT_DEFAULT: goog.userAgent.IE && - !goog.userAgent.isVersionOrHigher('9'), - - /** - * Whether the {@code navigator.onLine} property is supported. - */ - HAS_NAVIGATOR_ONLINE_PROPERTY: !goog.userAgent.WEBKIT || - goog.userAgent.isVersionOrHigher('528'), - - /** - * Whether HTML5 network online/offline events are supported. - */ - HAS_HTML5_NETWORK_EVENT_SUPPORT: - goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9b') || - goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8') || - goog.userAgent.OPERA && goog.userAgent.isVersionOrHigher('9.5') || - goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('528'), - - /** - * Whether HTML5 network events fire on document.body, or otherwise the - * window. - */ - HTML5_NETWORK_EVENTS_FIRE_ON_BODY: - goog.userAgent.GECKO && !goog.userAgent.isVersionOrHigher('8') || - goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'), - - /** - * Whether touch is enabled in the browser. - */ - TOUCH_ENABLED: - ('ontouchstart' in goog.global || - !!(goog.global['document'] && - document.documentElement && - 'ontouchstart' in document.documentElement) || - // IE10 uses non-standard touch events, so it has a different check. - !!(goog.global['navigator'] && - goog.global['navigator']['msMaxTouchPoints'])) -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/event.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/event.js deleted file mode 100644 index b671289..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/event.js +++ /dev/null @@ -1,143 +0,0 @@ -// 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. - * @suppress {extraRequire} - */ -goog.require('goog.Disposable'); -goog.require('goog.events.EventId'); - - -/** - * 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.EventId} - */ -goog.events.EventLike; - - - -/** - * A base class for event objects, so that they can support preventDefault and - * stopPropagation. - * - * @param {string|!goog.events.EventId} 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 instanceof goog.events.EventId ? String(type) : type; - - /** - * TODO(tbreisacher): The type should probably be - * EventTarget|goog.events.EventTarget. - * - * Target of the event. - * @type {Object|undefined} - */ - this.target = opt_target; - - /** - * Object that had the listener attached. - * @type {Object|undefined} - */ - this.currentTarget = this.target; - - /** - * Whether to cancel the event in internal capture/bubble processing for IE. - * @type {boolean} - * @public - * @suppress {underscore|visibility} Technically public, but referencing this - * outside this package is strongly discouraged. - */ - this.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} - */ - this.defaultPrevented = false; - - /** - * Return value for in internal capture/bubble processing for IE. - * @type {boolean} - * @public - * @suppress {underscore|visibility} Technically public, but referencing this - * outside this package is strongly discouraged. - */ - this.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(); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventhandler.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventhandler.js deleted file mode 100644 index 3551d10..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventhandler.js +++ /dev/null @@ -1,459 +0,0 @@ -// 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 Class to create objects which want to handle multiple events - * and have their listeners easily cleaned up via a dispose method. - * - * Example: - * <pre> - * function Something() { - * Something.base(this); - * - * ... set up object ... - * - * // Add event listeners - * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar); - * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand); - * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse); - * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover); - * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover); - * } - * goog.inherits(Something, goog.events.EventHandler); - * - * Something.prototype.disposeInternal = function() { - * Something.base(this, 'disposeInternal'); - * goog.dom.removeNode(this.container); - * }; - * - * - * // Then elsewhere: - * - * var activeSomething = null; - * function openSomething() { - * activeSomething = new Something(); - * } - * - * function closeSomething() { - * if (activeSomething) { - * activeSomething.dispose(); // Remove event listeners - * activeSomething = null; - * } - * } - * </pre> - * - */ - -goog.provide('goog.events.EventHandler'); - -goog.require('goog.Disposable'); -goog.require('goog.events'); -goog.require('goog.object'); - -goog.require('goog.events.EventWrapper'); - - - -/** - * Super class for objects that want to easily manage a number of event - * listeners. It allows a short cut to listen and also provides a quick way - * to remove all events listeners belonging to this object. - * @param {SCOPE=} opt_scope Object in whose scope to call the listeners. - * @constructor - * @extends {goog.Disposable} - * @template SCOPE - */ -goog.events.EventHandler = function(opt_scope) { - goog.Disposable.call(this); - // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3 - // that access this private variable. :( - this.handler_ = opt_scope; - - /** - * Keys for events that are being listened to. - * @type {!Object<!goog.events.Key>} - * @private - */ - this.keys_ = {}; -}; -goog.inherits(goog.events.EventHandler, goog.Disposable); - - -/** - * Utility array used to unify the cases of listening for an array of types - * and listening for a single event, without using recursion or allocating - * an array each time. - * @type {!Array<string>} - * @const - * @private - */ -goog.events.EventHandler.typeArray_ = []; - - -/** - * Listen to an event on a Listenable. If the function is omitted then the - * EventHandler's handleEvent method will be used. - * @param {goog.events.ListenableType} src Event source. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type to listen for or array of event types. - * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=} - * opt_fn Optional callback function to be used as the listener or an object - * with handleEvent function. - * @param {boolean=} opt_capture Optional whether to use capture phase. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @template EVENTOBJ - */ -goog.events.EventHandler.prototype.listen = function( - src, type, opt_fn, opt_capture) { - return this.listen_(src, type, opt_fn, opt_capture); -}; - - -/** - * Listen to an event on a Listenable. If the function is omitted then the - * EventHandler's handleEvent method will be used. - * @param {goog.events.ListenableType} src Event source. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type to listen for or array of event types. - * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}| - * null|undefined} fn Optional callback function to be used as the - * listener or an object with handleEvent function. - * @param {boolean|undefined} capture Optional whether to use capture phase. - * @param {T} scope Object in whose scope to call the listener. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @template T,EVENTOBJ - */ -goog.events.EventHandler.prototype.listenWithScope = function( - src, type, fn, capture, scope) { - // TODO(mknichel): Deprecate this function. - return this.listen_(src, type, fn, capture, scope); -}; - - -/** - * Listen to an event on a Listenable. If the function is omitted then the - * EventHandler's handleEvent method will be used. - * @param {goog.events.ListenableType} src Event source. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type to listen for or array of event types. - * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn - * Optional callback function to be used as the listener or an object with - * handleEvent function. - * @param {boolean=} opt_capture Optional whether to use capture phase. - * @param {Object=} opt_scope Object in whose scope to call the listener. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @template EVENTOBJ - * @private - */ -goog.events.EventHandler.prototype.listen_ = function(src, type, opt_fn, - opt_capture, - opt_scope) { - if (!goog.isArray(type)) { - if (type) { - goog.events.EventHandler.typeArray_[0] = type.toString(); - } - type = goog.events.EventHandler.typeArray_; - } - for (var i = 0; i < type.length; i++) { - var listenerObj = goog.events.listen( - src, type[i], opt_fn || this.handleEvent, - opt_capture || false, - opt_scope || this.handler_ || this); - - if (!listenerObj) { - // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT - // (goog.events.CaptureSimulationMode) in IE8-, it will return null - // value. - return this; - } - - var key = listenerObj.key; - this.keys_[key] = listenerObj; - } - - return this; -}; - - -/** - * Listen to an event on a Listenable. If the function is omitted, then the - * EventHandler's handleEvent method will be used. After the event has fired the - * event listener is removed from the target. If an array of event types is - * provided, each event type will be listened to once. - * @param {goog.events.ListenableType} src Event source. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type to listen for or array of event types. - * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn - * Optional callback function to be used as the listener or an object with - * handleEvent function. - * @param {boolean=} opt_capture Optional whether to use capture phase. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @template EVENTOBJ - */ -goog.events.EventHandler.prototype.listenOnce = function( - src, type, opt_fn, opt_capture) { - return this.listenOnce_(src, type, opt_fn, opt_capture); -}; - - -/** - * Listen to an event on a Listenable. If the function is omitted, then the - * EventHandler's handleEvent method will be used. After the event has fired the - * event listener is removed from the target. If an array of event types is - * provided, each event type will be listened to once. - * @param {goog.events.ListenableType} src Event source. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type to listen for or array of event types. - * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}| - * null|undefined} fn Optional callback function to be used as the - * listener or an object with handleEvent function. - * @param {boolean|undefined} capture Optional whether to use capture phase. - * @param {T} scope Object in whose scope to call the listener. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @template T,EVENTOBJ - */ -goog.events.EventHandler.prototype.listenOnceWithScope = function( - src, type, fn, capture, scope) { - // TODO(mknichel): Deprecate this function. - return this.listenOnce_(src, type, fn, capture, scope); -}; - - -/** - * Listen to an event on a Listenable. If the function is omitted, then the - * EventHandler's handleEvent method will be used. After the event has fired - * the event listener is removed from the target. If an array of event types is - * provided, each event type will be listened to once. - * @param {goog.events.ListenableType} src Event source. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type to listen for or array of event types. - * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn - * Optional callback function to be used as the listener or an object with - * handleEvent function. - * @param {boolean=} opt_capture Optional whether to use capture phase. - * @param {Object=} opt_scope Object in whose scope to call the listener. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @template EVENTOBJ - * @private - */ -goog.events.EventHandler.prototype.listenOnce_ = function( - src, type, opt_fn, opt_capture, opt_scope) { - if (goog.isArray(type)) { - for (var i = 0; i < type.length; i++) { - this.listenOnce_(src, type[i], opt_fn, opt_capture, opt_scope); - } - } else { - var listenerObj = goog.events.listenOnce( - src, type, opt_fn || this.handleEvent, opt_capture, - opt_scope || this.handler_ || this); - if (!listenerObj) { - // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT - // (goog.events.CaptureSimulationMode) in IE8-, it will return null - // value. - return this; - } - - var key = listenerObj.key; - this.keys_[key] = listenerObj; - } - - return this; -}; - - -/** - * Adds an event listener with a specific event 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 {goog.events.EventWrapper} wrapper Event wrapper to use. - * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener - * Callback method, or an object with a handleEvent function. - * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to - * false). - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - */ -goog.events.EventHandler.prototype.listenWithWrapper = function( - src, wrapper, listener, opt_capt) { - // TODO(mknichel): Remove the opt_scope from this function and then - // templatize it. - return this.listenWithWrapper_(src, wrapper, listener, opt_capt); -}; - - -/** - * Adds an event listener with a specific event 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 {goog.events.EventWrapper} wrapper Event wrapper to use. - * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null} - * listener Optional callback function to be used as the - * listener or an object with handleEvent function. - * @param {boolean|undefined} capture Optional whether to use capture phase. - * @param {T} scope Object in whose scope to call the listener. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @template T - */ -goog.events.EventHandler.prototype.listenWithWrapperAndScope = function( - src, wrapper, listener, capture, scope) { - // TODO(mknichel): Deprecate this function. - return this.listenWithWrapper_(src, wrapper, listener, capture, scope); -}; - - -/** - * Adds an event listener with a specific event 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 {goog.events.EventWrapper} wrapper Event wrapper to use. - * @param {function(?):?|{handleEvent:function(?):?}|null} 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. - * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for - * chaining of calls. - * @private - */ -goog.events.EventHandler.prototype.listenWithWrapper_ = function( - src, wrapper, listener, opt_capt, opt_scope) { - wrapper.listen(src, listener, opt_capt, opt_scope || this.handler_ || this, - this); - return this; -}; - - -/** - * @return {number} Number of listeners registered by this handler. - */ -goog.events.EventHandler.prototype.getListenerCount = function() { - var count = 0; - for (var key in this.keys_) { - if (Object.prototype.hasOwnProperty.call(this.keys_, key)) { - count++; - } - } - return count; -}; - - -/** - * Unlistens on an event. - * @param {goog.events.ListenableType} src Event source. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type or array of event types to unlisten to. - * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn - * Optional callback function to be used as the listener or an object with - * handleEvent function. - * @param {boolean=} opt_capture Optional whether to use capture phase. - * @param {Object=} opt_scope Object in whose scope to call the listener. - * @return {!goog.events.EventHandler} This object, allowing for chaining of - * calls. - * @template EVENTOBJ - */ -goog.events.EventHandler.prototype.unlisten = function(src, type, opt_fn, - opt_capture, - opt_scope) { - if (goog.isArray(type)) { - for (var i = 0; i < type.length; i++) { - this.unlisten(src, type[i], opt_fn, opt_capture, opt_scope); - } - } else { - var listener = goog.events.getListener(src, type, - opt_fn || this.handleEvent, - opt_capture, opt_scope || this.handler_ || this); - - if (listener) { - goog.events.unlistenByKey(listener); - delete this.keys_[listener.key]; - } - } - - return this; -}; - - -/** - * Removes an event listener which was added with listenWithWrapper(). - * - * @param {EventTarget|goog.events.EventTarget} src The target to stop - * listening to events on. - * @param {goog.events.EventWrapper} wrapper Event wrapper to use. - * @param {function(?):?|{handleEvent:function(?):?}|null} listener The - * listener function to remove. - * @param {boolean=} opt_capt In DOM-compliant browsers, this determines - * whether the listener is fired during the capture or bubble phase of the - * event. - * @param {Object=} opt_scope Element in whose scope to call the listener. - * @return {!goog.events.EventHandler} This object, allowing for chaining of - * calls. - */ -goog.events.EventHandler.prototype.unlistenWithWrapper = function(src, wrapper, - listener, opt_capt, opt_scope) { - wrapper.unlisten(src, listener, opt_capt, - opt_scope || this.handler_ || this, this); - return this; -}; - - -/** - * Unlistens to all events. - */ -goog.events.EventHandler.prototype.removeAll = function() { - goog.object.forEach(this.keys_, goog.events.unlistenByKey); - this.keys_ = {}; -}; - - -/** - * Disposes of this EventHandler and removes all listeners that it registered. - * @override - * @protected - */ -goog.events.EventHandler.prototype.disposeInternal = function() { - goog.events.EventHandler.superClass_.disposeInternal.call(this); - this.removeAll(); -}; - - -/** - * Default event handler - * @param {goog.events.Event} e Event object. - */ -goog.events.EventHandler.prototype.handleEvent = function(e) { - throw Error('EventHandler.handleEvent not implemented'); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventid.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventid.js deleted file mode 100644 index 9a4822e..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventid.js +++ /dev/null @@ -1,47 +0,0 @@ -// 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. - -goog.provide('goog.events.EventId'); - - - -/** - * A templated class that is used when registering for events. Typical usage: - * <code> - * /** @type {goog.events.EventId<MyEventObj>} - * var myEventId = new goog.events.EventId( - * goog.events.getUniqueId(('someEvent')); - * - * // No need to cast or declare here since the compiler knows the correct - * // type of 'evt' (MyEventObj). - * something.listen(myEventId, function(evt) {}); - * </code> - * - * @param {string} eventId - * @template T - * @constructor - * @struct - * @final - */ -goog.events.EventId = function(eventId) { - /** @const */ this.id = eventId; -}; - - -/** - * @override - */ -goog.events.EventId.prototype.toString = function() { - return this.id; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/events.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/events.js deleted file mode 100644 index 7687b5c..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/events.js +++ /dev/null @@ -1,983 +0,0 @@ -// 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 An event manager for both native browser event - * targets and custom JavaScript event targets - * ({@code goog.events.Listenable}). This provides an abstraction - * over browsers' event systems. - * - * It also provides a simulation of W3C event model's capture phase in - * Internet Explorer (IE 8 and below). Caveat: the simulation does not - * interact well with listeners registered directly on the elements - * (bypassing goog.events) or even with listeners registered via - * goog.events in a separate JS binary. In these cases, we provide - * no ordering guarantees. - * - * The listeners will receive a "patched" event object. Such event object - * contains normalized values for certain event properties that differs in - * different browsers. - * - * Example usage: - * <pre> - * goog.events.listen(myNode, 'click', function(e) { alert('woo') }); - * goog.events.listen(myNode, 'mouseover', mouseHandler, true); - * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true); - * goog.events.removeAll(myNode); - * </pre> - * - * in IE and event object patching] - * @author arv@google.com (Erik Arvidsson) - * - * @see ../demos/events.html - * @see ../demos/event-propagation.html - * @see ../demos/stopevent.html - */ - -// IMPLEMENTATION NOTES: -// goog.events stores an auxiliary data structure on each EventTarget -// source being listened on. This allows us to take advantage of GC, -// having the data structure GC'd when the EventTarget is GC'd. This -// GC behavior is equivalent to using W3C DOM Events directly. - -goog.provide('goog.events'); -goog.provide('goog.events.CaptureSimulationMode'); -goog.provide('goog.events.Key'); -goog.provide('goog.events.ListenableType'); - -goog.require('goog.asserts'); -goog.require('goog.debug.entryPointRegistry'); -goog.require('goog.events.BrowserEvent'); -goog.require('goog.events.BrowserFeature'); -goog.require('goog.events.Listenable'); -goog.require('goog.events.ListenerMap'); - -goog.require('goog.debug.ErrorHandler'); -goog.require('goog.events.EventWrapper'); - - -/** - * @typedef {number|goog.events.ListenableKey} - */ -goog.events.Key; - - -/** - * @typedef {EventTarget|goog.events.Listenable} - */ -goog.events.ListenableType; - - -/** - * Property name on a native event target for the listener map - * associated with the event target. - * @private @const {string} - */ -goog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0); - - -/** - * String used to prepend to IE event types. - * @const - * @private - */ -goog.events.onString_ = 'on'; - - -/** - * Map of computed "on<eventname>" strings for IE event types. Caching - * this removes an extra object allocation in goog.events.listen which - * improves IE6 performance. - * @const - * @dict - * @private - */ -goog.events.onStringMap_ = {}; - - -/** - * @enum {number} Different capture simulation mode for IE8-. - */ -goog.events.CaptureSimulationMode = { - /** - * Does not perform capture simulation. Will asserts in IE8- when you - * add capture listeners. - */ - OFF_AND_FAIL: 0, - - /** - * Does not perform capture simulation, silently ignore capture - * listeners. - */ - OFF_AND_SILENT: 1, - - /** - * Performs capture simulation. - */ - ON: 2 -}; - - -/** - * @define {number} The capture simulation mode for IE8-. By default, - * this is ON. - */ -goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2); - - -/** - * Estimated count of total native listeners. - * @private {number} - */ -goog.events.listenerCountEstimate_ = 0; - - -/** - * Adds an event listener for a specific event on a native event - * target (such as a DOM element) or an object that has implemented - * {@link goog.events.Listenable}. 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 {EventTarget|goog.events.Listenable} src The node to listen - * to events on. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type or array of event types. - * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null} - * listener Callback method, or an object with a handleEvent function. - * WARNING: passing an Object is now softly deprecated. - * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to - * false). - * @param {T=} opt_handler Element in whose scope to call the listener. - * @return {goog.events.Key} Unique key for the listener. - * @template T,EVENTOBJ - */ -goog.events.listen = function(src, type, listener, opt_capt, opt_handler) { - if (goog.isArray(type)) { - for (var i = 0; i < type.length; i++) { - goog.events.listen(src, type[i], listener, opt_capt, opt_handler); - } - return null; - } - - listener = goog.events.wrapListener(listener); - if (goog.events.Listenable.isImplementedBy(src)) { - return src.listen( - /** @type {string|!goog.events.EventId} */ (type), - listener, opt_capt, opt_handler); - } else { - return goog.events.listen_( - /** @type {!EventTarget} */ (src), - /** @type {string|!goog.events.EventId} */ (type), - listener, /* callOnce */ false, opt_capt, opt_handler); - } -}; - - -/** - * Adds an event listener for a specific event on a native event - * target. 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 {EventTarget} src The node to listen to events on. - * @param {string|!goog.events.EventId} type Event type. - * @param {!Function} listener Callback function. - * @param {boolean} callOnce Whether the listener is a one-off - * listener or otherwise. - * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to - * false). - * @param {Object=} opt_handler Element in whose scope to call the listener. - * @return {goog.events.ListenableKey} Unique key for the listener. - * @private - */ -goog.events.listen_ = function( - src, type, listener, callOnce, opt_capt, opt_handler) { - if (!type) { - throw Error('Invalid event type'); - } - - var capture = !!opt_capt; - if (capture && !goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) { - if (goog.events.CAPTURE_SIMULATION_MODE == - goog.events.CaptureSimulationMode.OFF_AND_FAIL) { - goog.asserts.fail('Can not register capture listener in IE8-.'); - return null; - } else if (goog.events.CAPTURE_SIMULATION_MODE == - goog.events.CaptureSimulationMode.OFF_AND_SILENT) { - return null; - } - } - - var listenerMap = goog.events.getListenerMap_(src); - if (!listenerMap) { - src[goog.events.LISTENER_MAP_PROP_] = listenerMap = - new goog.events.ListenerMap(src); - } - - var listenerObj = listenerMap.add( - type, listener, callOnce, opt_capt, opt_handler); - - // If the listenerObj already has a proxy, it has been set up - // previously. We simply return. - if (listenerObj.proxy) { - return listenerObj; - } - - var proxy = goog.events.getProxy(); - listenerObj.proxy = proxy; - - proxy.src = src; - proxy.listener = listenerObj; - - // Attach the proxy through the browser's API - if (src.addEventListener) { - src.addEventListener(type.toString(), proxy, capture); - } else { - // The else above used to be else if (src.attachEvent) and then there was - // another else statement that threw an exception warning the developer - // they made a mistake. This resulted in an extra object allocation in IE6 - // due to a wrapper object that had to be implemented around the element - // and so was removed. - src.attachEvent(goog.events.getOnString_(type.toString()), proxy); - } - - goog.events.listenerCountEstimate_++; - return listenerObj; -}; - - -/** - * Helper function for returning a proxy function. - * @return {!Function} A new or reused function object. - */ -goog.events.getProxy = function() { - var proxyCallbackFunction = goog.events.handleBrowserEvent_; - // Use a local var f to prevent one allocation. - var f = goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT ? - function(eventObject) { - return proxyCallbackFunction.call(f.src, f.listener, eventObject); - } : - function(eventObject) { - var v = proxyCallbackFunction.call(f.src, f.listener, eventObject); - // NOTE(chrishenry): In IE, we hack in a capture phase. However, if - // there is inline event handler which tries to prevent default (for - // example <a href="..." onclick="return false">...</a>) in a - // descendant element, the prevent default will be overridden - // by this listener if this listener were to return true. Hence, we - // return undefined. - if (!v) return v; - }; - return f; -}; - - -/** - * Adds an event listener for a specific event on a native event - * target (such as a DOM element) or an object that has implemented - * {@link goog.events.Listenable}. After the event has fired the event - * listener is removed from the target. - * - * 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 {EventTarget|goog.events.Listenable} src The node to listen - * to events on. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type or array of event types. - * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null} - * listener Callback method. - * @param {boolean=} opt_capt Fire in capture phase?. - * @param {T=} opt_handler Element in whose scope to call the listener. - * @return {goog.events.Key} Unique key for the listener. - * @template T,EVENTOBJ - */ -goog.events.listenOnce = function(src, type, listener, opt_capt, opt_handler) { - if (goog.isArray(type)) { - for (var i = 0; i < type.length; i++) { - goog.events.listenOnce(src, type[i], listener, opt_capt, opt_handler); - } - return null; - } - - listener = goog.events.wrapListener(listener); - if (goog.events.Listenable.isImplementedBy(src)) { - return src.listenOnce( - /** @type {string|!goog.events.EventId} */ (type), - listener, opt_capt, opt_handler); - } else { - return goog.events.listen_( - /** @type {!EventTarget} */ (src), - /** @type {string|!goog.events.EventId} */ (type), - listener, /* callOnce */ true, opt_capt, opt_handler); - } -}; - - -/** - * Adds an event listener with a specific event wrapper on a DOM Node or an - * object that has implemented {@link goog.events.Listenable}. A listener can - * only be added once to an object. - * - * @param {EventTarget|goog.events.Listenable} src The target to - * listen to events on. - * @param {goog.events.EventWrapper} wrapper Event wrapper to use. - * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener - * Callback method, or an object with a handleEvent function. - * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to - * false). - * @param {T=} opt_handler Element in whose scope to call the listener. - * @template T - */ -goog.events.listenWithWrapper = function(src, wrapper, listener, opt_capt, - opt_handler) { - wrapper.listen(src, listener, opt_capt, opt_handler); -}; - - -/** - * Removes an event listener which was added with listen(). - * - * @param {EventTarget|goog.events.Listenable} src The target to stop - * listening to events on. - * @param {string|Array<string>| - * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>} - * type Event type or array of event types to unlisten to. - * @param {function(?):?|{handleEvent:function(?):?}|null} listener The - * listener function to remove. - * @param {boolean=} opt_capt In DOM-compliant browsers, this determines - * whether the listener is fired during the capture or bubble phase of the - * event. - * @param {Object=} opt_handler Element in whose scope to call the listener. - * @return {?boolean} indicating whether the listener was there to remove. - * @template EVENTOBJ - */ -goog.events.unlisten = function(src, type, listener, opt_capt, opt_handler) { - if (goog.isArray(type)) { - for (var i = 0; i < type.length; i++) { - goog.events.unlisten(src, type[i], listener, opt_capt, opt_handler); - } - return null; - } - - listener = goog.events.wrapListener(listener); - if (goog.events.Listenable.isImplementedBy(src)) { - return src.unlisten( - /** @type {string|!goog.events.EventId} */ (type), - listener, opt_capt, opt_handler); - } - - if (!src) { - // TODO(chrishenry): We should tighten the API to only accept - // non-null objects, or add an assertion here. - return false; - } - - var capture = !!opt_capt; - var listenerMap = goog.events.getListenerMap_( - /** @type {!EventTarget} */ (src)); - if (listenerMap) { - var listenerObj = listenerMap.getListener( - /** @type {string|!goog.events.EventId} */ (type), - listener, capture, opt_handler); - if (listenerObj) { - return goog.events.unlistenByKey(listenerObj); - } - } - - return false; -}; - - -/** - * Removes an event listener which was added with listen() by the key - * returned by listen(). - * - * @param {goog.events.Key} key The key returned by listen() for this - * event listener. - * @return {boolean} indicating whether the listener was there to remove. - */ -goog.events.unlistenByKey = function(key) { - // TODO(chrishenry): Remove this check when tests that rely on this - // are fixed. - if (goog.isNumber(key)) { - return false; - } - - var listener = /** @type {goog.events.ListenableKey} */ (key); - if (!listener || listener.removed) { - return false; - } - - var src = listener.src; - if (goog.events.Listenable.isImplementedBy(src)) { - return src.unlistenByKey(listener); - } - - var type = listener.type; - var proxy = listener.proxy; - if (src.removeEventListener) { - src.removeEventListener(type, proxy, listener.capture); - } else if (src.detachEvent) { - src.detachEvent(goog.events.getOnString_(type), proxy); - } - goog.events.listenerCountEstimate_--; - - var listenerMap = goog.events.getListenerMap_( - /** @type {!EventTarget} */ (src)); - // TODO(chrishenry): Try to remove this conditional and execute the - // first branch always. This should be safe. - if (listenerMap) { - listenerMap.removeByKey(listener); - if (listenerMap.getTypeCount() == 0) { - // Null the src, just because this is simple to do (and useful - // for IE <= 7). - listenerMap.src = null; - // We don't use delete here because IE does not allow delete - // on a window object. - src[goog.events.LISTENER_MAP_PROP_] = null; - } - } else { - listener.markAsRemoved(); - } - - return true; -}; - - -/** - * Removes an event listener which was added with listenWithWrapper(). - * - * @param {EventTarget|goog.events.Listenable} src The target to stop - * listening to events on. - * @param {goog.events.EventWrapper} wrapper Event wrapper to use. - * @param {function(?):?|{handleEvent:function(?):?}|null} listener The - * listener function to remove. - * @param {boolean=} opt_capt In DOM-compliant browsers, this determines - * whether the listener is fired during the capture or bubble phase of the - * event. - * @param {Object=} opt_handler Element in whose scope to call the listener. - */ -goog.events.unlistenWithWrapper = function(src, wrapper, listener, opt_capt, - opt_handler) { - wrapper.unlisten(src, listener, opt_capt, opt_handler); -}; - - -/** - * Removes all listeners from an object. You can also optionally - * remove listeners of a particular type. - * - * @param {Object|undefined} obj Object to remove listeners from. Must be an - * EventTarget or a goog.events.Listenable. - * @param {string|!goog.events.EventId=} opt_type Type of event to remove. - * Default is all types. - * @return {number} Number of listeners removed. - */ -goog.events.removeAll = function(obj, opt_type) { - // TODO(chrishenry): Change the type of obj to - // (!EventTarget|!goog.events.Listenable). - - if (!obj) { - return 0; - } - - if (goog.events.Listenable.isImplementedBy(obj)) { - return obj.removeAllListeners(opt_type); - } - - var listenerMap = goog.events.getListenerMap_( - /** @type {!EventTarget} */ (obj)); - if (!listenerMap) { - return 0; - } - - var count = 0; - var typeStr = opt_type && opt_type.toString(); - for (var type in listenerMap.listeners) { - if (!typeStr || type == typeStr) { - // Clone so that we don't need to worry about unlistenByKey - // changing the content of the ListenerMap. - var listeners = listenerMap.listeners[type].concat(); - for (var i = 0; i < listeners.length; ++i) { - if (goog.events.unlistenByKey(listeners[i])) { - ++count; - } - } - } - } - return count; -}; - - -/** - * Gets the listeners for a given object, type and capture phase. - * - * @param {Object} obj Object to get listeners for. - * @param {string|!goog.events.EventId} type Event type. - * @param {boolean} capture Capture phase?. - * @return {Array<goog.events.Listener>} Array of listener objects. - */ -goog.events.getListeners = function(obj, type, capture) { - if (goog.events.Listenable.isImplementedBy(obj)) { - return obj.getListeners(type, capture); - } else { - if (!obj) { - // TODO(chrishenry): We should tighten the API to accept - // !EventTarget|goog.events.Listenable, and add an assertion here. - return []; - } - - var listenerMap = goog.events.getListenerMap_( - /** @type {!EventTarget} */ (obj)); - return listenerMap ? listenerMap.getListeners(type, capture) : []; - } -}; - - -/** - * Gets the goog.events.Listener for the event or null if no such listener is - * in use. - * - * @param {EventTarget|goog.events.Listenable} src The target from - * which to get listeners. - * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event. - * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The - * listener function to get. - * @param {boolean=} opt_capt In DOM-compliant browsers, this determines - * whether the listener is fired during the - * capture or bubble phase of the event. - * @param {Object=} opt_handler Element in whose scope to call the listener. - * @return {goog.events.ListenableKey} the found listener or null if not found. - * @template EVENTOBJ - */ -goog.events.getListener = function(src, type, listener, opt_capt, opt_handler) { - // TODO(chrishenry): Change type from ?string to string, or add assertion. - type = /** @type {string} */ (type); - listener = goog.events.wrapListener(listener); - var capture = !!opt_capt; - if (goog.events.Listenable.isImplementedBy(src)) { - return src.getListener(type, listener, capture, opt_handler); - } - - if (!src) { - // TODO(chrishenry): We should tighten the API to only accept - // non-null objects, or add an assertion here. - return null; - } - - var listenerMap = goog.events.getListenerMap_( - /** @type {!EventTarget} */ (src)); - if (listenerMap) { - return listenerMap.getListener(type, listener, capture, opt_handler); - } - return null; -}; - - -/** - * Returns whether an event target has 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 {EventTarget|goog.events.Listenable} obj Target to get - * listeners for. - * @param {string|!goog.events.EventId=} opt_type Event type. - * @param {boolean=} opt_capture Whether to check for capture or bubble-phase - * listeners. - * @return {boolean} Whether an event target has one or more listeners matching - * the requested type and/or capture phase. - */ -goog.events.hasListener = function(obj, opt_type, opt_capture) { - if (goog.events.Listenable.isImplementedBy(obj)) { - return obj.hasListener(opt_type, opt_capture); - } - - var listenerMap = goog.events.getListenerMap_( - /** @type {!EventTarget} */ (obj)); - return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture); -}; - - -/** - * Provides a nice string showing the normalized event objects public members - * @param {Object} e Event Object. - * @return {string} String of the public members of the normalized event object. - */ -goog.events.expose = function(e) { - var str = []; - for (var key in e) { - if (e[key] && e[key].id) { - str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')'); - } else { - str.push(key + ' = ' + e[key]); - } - } - return str.join('\n'); -}; - - -/** - * Returns a string with on prepended to the specified type. This is used for IE - * which expects "on" to be prepended. This function caches the string in order - * to avoid extra allocations in steady state. - * @param {string} type Event type. - * @return {string} The type string with 'on' prepended. - * @private - */ -goog.events.getOnString_ = function(type) { - if (type in goog.events.onStringMap_) { - return goog.events.onStringMap_[type]; - } - return goog.events.onStringMap_[type] = goog.events.onString_ + type; -}; - - -/** - * Fires an object's listeners of a particular type and phase - * - * @param {Object} obj Object whose listeners to call. - * @param {string|!goog.events.EventId} type Event type. - * @param {boolean} capture Which event phase. - * @param {Object} eventObject Event object to be passed to listener. - * @return {boolean} True if all listeners returned true else false. - */ -goog.events.fireListeners = function(obj, type, capture, eventObject) { - if (goog.events.Listenable.isImplementedBy(obj)) { - return obj.fireListeners(type, capture, eventObject); - } - - return goog.events.fireListeners_(obj, type, capture, eventObject); -}; - - -/** - * Fires an object's listeners of a particular type and phase. - * @param {Object} obj Object whose listeners to call. - * @param {string|!goog.events.EventId} type Event type. - * @param {boolean} capture Which event phase. - * @param {Object} eventObject Event object to be passed to listener. - * @return {boolean} True if all listeners returned true else false. - * @private - */ -goog.events.fireListeners_ = function(obj, type, capture, eventObject) { - /** @type {boolean} */ - var retval = true; - - var listenerMap = goog.events.getListenerMap_( - /** @type {EventTarget} */ (obj)); - if (listenerMap) { - // TODO(chrishenry): Original code avoids array creation when there - // is no listener, so we do the same. If this optimization turns - // out to be not required, we can replace this with - // listenerMap.getListeners(type, capture) instead, which is simpler. - var listenerArray = listenerMap.listeners[type.toString()]; - if (listenerArray) { - listenerArray = listenerArray.concat(); - 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.capture == capture && !listener.removed) { - var result = goog.events.fireListener(listener, eventObject); - retval = retval && (result !== false); - } - } - } - } - return retval; -}; - - -/** - * Fires a listener with a set of arguments - * - * @param {goog.events.Listener} listener The listener object to call. - * @param {Object} eventObject The event object to pass to the listener. - * @return {boolean} Result of listener. - */ -goog.events.fireListener = function(listener, eventObject) { - var listenerFn = listener.listener; - var listenerHandler = listener.handler || listener.src; - - if (listener.callOnce) { - goog.events.unlistenByKey(listener); - } - return listenerFn.call(listenerHandler, eventObject); -}; - - -/** - * Gets the total number of listeners currently in the system. - * @return {number} Number of listeners. - * @deprecated This returns estimated count, now that Closure no longer - * stores a central listener registry. We still return an estimation - * to keep existing listener-related tests passing. In the near future, - * this function will be removed. - */ -goog.events.getTotalListenerCount = function() { - return goog.events.listenerCountEstimate_; -}; - - -/** - * 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.Listenable} src The event target. - * @param {goog.events.EventLike} e Event object. - * @return {boolean} If anyone called preventDefault on the event object (or - * if any of the handlers returns false) this will also return false. - * If there are no handlers, or if all handlers return true, this returns - * true. - */ -goog.events.dispatchEvent = function(src, e) { - goog.asserts.assert( - goog.events.Listenable.isImplementedBy(src), - 'Can not use goog.events.dispatchEvent with ' + - 'non-goog.events.Listenable instance.'); - return src.dispatchEvent(e); -}; - - -/** - * Installs exception protection for the browser event entry point using the - * given error handler. - * - * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to - * protect the entry point. - */ -goog.events.protectBrowserEventEntryPoint = function(errorHandler) { - goog.events.handleBrowserEvent_ = errorHandler.protectEntryPoint( - goog.events.handleBrowserEvent_); -}; - - -/** - * Handles an event and dispatches it to the correct listeners. This - * function is a proxy for the real listener the user specified. - * - * @param {goog.events.Listener} listener The listener object. - * @param {Event=} opt_evt Optional event object that gets passed in via the - * native event handlers. - * @return {boolean} Result of the event handler. - * @this {EventTarget} The object or Element that fired the event. - * @private - */ -goog.events.handleBrowserEvent_ = function(listener, opt_evt) { - if (listener.removed) { - return true; - } - - // Synthesize event propagation if the browser does not support W3C - // event model. - if (!goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) { - var ieEvent = opt_evt || - /** @type {Event} */ (goog.getObjectByName('window.event')); - var evt = new goog.events.BrowserEvent(ieEvent, this); - /** @type {boolean} */ - var retval = true; - - if (goog.events.CAPTURE_SIMULATION_MODE == - goog.events.CaptureSimulationMode.ON) { - // If we have not marked this event yet, we should perform capture - // simulation. - if (!goog.events.isMarkedIeEvent_(ieEvent)) { - goog.events.markIeEvent_(ieEvent); - - var ancestors = []; - for (var parent = evt.currentTarget; parent; - parent = parent.parentNode) { - ancestors.push(parent); - } - - // Fire capture listeners. - var type = listener.type; - for (var i = ancestors.length - 1; !evt.propagationStopped_ && i >= 0; - i--) { - evt.currentTarget = ancestors[i]; - var result = goog.events.fireListeners_(ancestors[i], type, true, evt); - retval = retval && result; - } - - // Fire bubble listeners. - // - // We can technically rely on IE to perform bubble event - // propagation. However, it turns out that IE fires events in - // opposite order of attachEvent registration, which broke - // some code and tests that rely on the order. (While W3C DOM - // Level 2 Events TR leaves the event ordering unspecified, - // modern browsers and W3C DOM Level 3 Events Working Draft - // actually specify the order as the registration order.) - for (var i = 0; !evt.propagationStopped_ && i < ancestors.length; i++) { - evt.currentTarget = ancestors[i]; - var result = goog.events.fireListeners_(ancestors[i], type, false, evt); - retval = retval && result; - } - } - } else { - retval = goog.events.fireListener(listener, evt); - } - return retval; - } - - // Otherwise, simply fire the listener. - return goog.events.fireListener( - listener, new goog.events.BrowserEvent(opt_evt, this)); -}; - - -/** - * This is used to mark the IE event object so we do not do the Closure pass - * twice for a bubbling event. - * @param {Event} e The IE browser event. - * @private - */ -goog.events.markIeEvent_ = function(e) { - // Only the keyCode and the returnValue can be changed. We use keyCode for - // non keyboard events. - // event.returnValue is a bit more tricky. It is undefined by default. A - // boolean false prevents the default action. In a window.onbeforeunload and - // the returnValue is non undefined it will be alerted. However, we will only - // modify the returnValue for keyboard events. We can get a problem if non - // closure events sets the keyCode or the returnValue - - var useReturnValue = false; - - if (e.keyCode == 0) { - // We cannot change the keyCode in case that srcElement is input[type=file]. - // We could test that that is the case but that would allocate 3 objects. - // If we use try/catch we will only allocate extra objects in the case of a - // failure. - /** @preserveTry */ - try { - e.keyCode = -1; - return; - } catch (ex) { - useReturnValue = true; - } - } - - if (useReturnValue || - /** @type {boolean|undefined} */ (e.returnValue) == undefined) { - e.returnValue = true; - } -}; - - -/** - * This is used to check if an IE event has already been handled by the Closure - * system so we do not do the Closure pass twice for a bubbling event. - * @param {Event} e The IE browser event. - * @return {boolean} True if the event object has been marked. - * @private - */ -goog.events.isMarkedIeEvent_ = function(e) { - return e.keyCode < 0 || e.returnValue != undefined; -}; - - -/** - * Counter to create unique event ids. - * @private {number} - */ -goog.events.uniqueIdCounter_ = 0; - - -/** - * Creates a unique event id. - * - * @param {string} identifier The identifier. - * @return {string} A unique identifier. - * @idGenerator - */ -goog.events.getUniqueId = function(identifier) { - return identifier + '_' + goog.events.uniqueIdCounter_++; -}; - - -/** - * @param {EventTarget} src The source object. - * @return {goog.events.ListenerMap} A listener map for the given - * source object, or null if none exists. - * @private - */ -goog.events.getListenerMap_ = function(src) { - var listenerMap = src[goog.events.LISTENER_MAP_PROP_]; - // IE serializes the property as well (e.g. when serializing outer - // HTML). So we must check that the value is of the correct type. - return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null; -}; - - -/** - * Expando property for listener function wrapper for Object with - * handleEvent. - * @private @const {string} - */ -goog.events.LISTENER_WRAPPER_PROP_ = '__closure_events_fn_' + - ((Math.random() * 1e9) >>> 0); - - -/** - * @param {Object|Function} listener The listener function or an - * object that contains handleEvent method. - * @return {!Function} Either the original function or a function that - * calls obj.handleEvent. If the same listener is passed to this - * function more than once, the same function is guaranteed to be - * returned. - */ -goog.events.wrapListener = function(listener) { - goog.asserts.assert(listener, 'Listener can not be null.'); - - if (goog.isFunction(listener)) { - return listener; - } - - goog.asserts.assert( - listener.handleEvent, 'An object listener must have handleEvent method.'); - if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) { - listener[goog.events.LISTENER_WRAPPER_PROP_] = - function(e) { return listener.handleEvent(e); }; - } - return listener[goog.events.LISTENER_WRAPPER_PROP_]; -}; - - -// Register the browser event handler as an entry point, so that -// it can be monitored for exception handling, etc. -goog.debug.entryPointRegistry.register( - /** - * @param {function(!Function): !Function} transformer The transforming - * function. - */ - function(transformer) { - goog.events.handleBrowserEvent_ = transformer( - goog.events.handleBrowserEvent_); - }); diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventtarget.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventtarget.js deleted file mode 100644 index 7408c7e..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventtarget.js +++ /dev/null @@ -1,394 +0,0 @@ -// 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 disposable implementation of a custom - * listenable/event target. See also: documentation for - * {@code goog.events.Listenable}. - * - * @author arv@google.com (Erik Arvidsson) [Original implementation] - * @see ../demos/eventtarget.html - * @see goog.events.Listenable - */ - -goog.provide('goog.events.EventTarget'); - -goog.require('goog.Disposable'); -goog.require('goog.asserts'); -goog.require('goog.events'); -goog.require('goog.events.Event'); -goog.require('goog.events.Listenable'); -goog.require('goog.events.ListenerMap'); -goog.require('goog.object'); - - - -/** - * An implementation of {@code goog.events.Listenable} with full W3C - * EventTarget-like support (capture/bubble mechanism, stopping event - * propagation, preventing default actions). - * - * You may subclass this class to turn your class into a Listenable. - * - * Unless propagation is stopped, an event dispatched by an - * EventTarget will bubble to the parent returned by - * {@code getParentEventTarget}. To set the parent, call - * {@code setParentEventTarget}. Subclasses that don't support - * changing the parent can override the setter to throw an error. - * - * Example usage: - * <pre> - * var source = new goog.events.EventTarget(); - * function handleEvent(e) { - * alert('Type: ' + e.type + '; Target: ' + e.target); - * } - * source.listen('foo', handleEvent); - * // Or: goog.events.listen(source, 'foo', handleEvent); - * ... - * source.dispatchEvent('foo'); // will call handleEvent - * ... - * source.unlisten('foo', handleEvent); - * // Or: goog.events.unlisten(source, 'foo', handleEvent); - * </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. - * @private {!goog.events.ListenerMap} - */ - this.eventTargetListeners_ = new goog.events.ListenerMap(this); - - /** - * The object to use for event.target. Useful when mixing in an - * EventTarget to another object. - * @private {!Object} - */ - this.actualEventTarget_ = this; - - /** - * Parent event target, used during event bubbling. - * - * TODO(chrishenry): Change this to goog.events.Listenable. This - * currently breaks people who expect getParentEventTarget to return - * goog.events.EventTarget. - * - * @private {goog.events.EventTarget} - */ - this.parentEventTarget_ = null; -}; -goog.inherits(goog.events.EventTarget, goog.Disposable); -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; - - -/** - * 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. - * @override - */ -goog.events.EventTarget.prototype.getParentEventTarget = function() { - return this.parentEventTarget_; -}; - - -/** - * Sets the parent of this event target to use for capture/bubble - * mechanism. - * @param {goog.events.EventTarget} parent Parent listenable (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. - * - * @param {string} type The type of the event to listen for. - * @param {function(?):?|{handleEvent:function(?):?}|null} 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. - * @deprecated Use {@code #listen} instead, when possible. Otherwise, use - * {@code goog.events.listen} if you are passing Object - * (instead of Function) as handler. - */ -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(?):?|{handleEvent:function(?):?}|null} 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. - * @deprecated Use {@code #unlisten} instead, when possible. Otherwise, use - * {@code goog.events.unlisten} if you are passing Object - * (instead of Function) as handler. - */ -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) { - 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); -}; - - -/** - * Removes 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. - * @override - */ -goog.events.EventTarget.prototype.disposeInternal = function() { - goog.events.EventTarget.superClass_.disposeInternal.call(this); - - this.removeAllListeners(); - this.parentEventTarget_ = null; -}; - - -/** @override */ -goog.events.EventTarget.prototype.listen = function( - type, listener, opt_useCapture, opt_listenerScope) { - this.assertInitialized_(); - return this.eventTargetListeners_.add( - String(type), listener, false /* callOnce */, opt_useCapture, - opt_listenerScope); -}; - - -/** @override */ -goog.events.EventTarget.prototype.listenOnce = function( - type, listener, opt_useCapture, opt_listenerScope) { - return this.eventTargetListeners_.add( - String(type), listener, true /* callOnce */, opt_useCapture, - opt_listenerScope); -}; - - -/** @override */ -goog.events.EventTarget.prototype.unlisten = function( - type, listener, opt_useCapture, opt_listenerScope) { - return this.eventTargetListeners_.remove( - String(type), listener, opt_useCapture, opt_listenerScope); -}; - - -/** @override */ -goog.events.EventTarget.prototype.unlistenByKey = function(key) { - return this.eventTargetListeners_.removeByKey(key); -}; - - -/** @override */ -goog.events.EventTarget.prototype.removeAllListeners = function(opt_type) { - // TODO(chrishenry): Previously, removeAllListeners can be called on - // uninitialized EventTarget, so we preserve that behavior. We - // should remove this when usages that rely on that fact are purged. - if (!this.eventTargetListeners_) { - return 0; - } - return this.eventTargetListeners_.removeAll(opt_type); -}; - - -/** @override */ -goog.events.EventTarget.prototype.fireListeners = function( - type, capture, eventObject) { - // TODO(chrishenry): Original code avoids array creation when there - // is no listener, so we do the same. If this optimization turns - // out to be not required, we can replace this with - // getListeners(type, capture) instead, which is simpler. - var listenerArray = this.eventTargetListeners_.listeners[String(type)]; - if (!listenerArray) { - return true; - } - listenerArray = listenerArray.concat(); - - var rv = true; - 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) { - var listenerFn = listener.listener; - var listenerHandler = listener.handler || listener.src; - - if (listener.callOnce) { - this.unlistenByKey(listener); - } - rv = listenerFn.call(listenerHandler, eventObject) !== false && rv; - } - } - - return rv && eventObject.returnValue_ != false; -}; - - -/** @override */ -goog.events.EventTarget.prototype.getListeners = function(type, capture) { - return this.eventTargetListeners_.getListeners(String(type), capture); -}; - - -/** @override */ -goog.events.EventTarget.prototype.getListener = function( - type, listener, capture, opt_listenerScope) { - return this.eventTargetListeners_.getListener( - String(type), listener, capture, opt_listenerScope); -}; - - -/** @override */ -goog.events.EventTarget.prototype.hasListener = function( - opt_type, opt_capture) { - var id = goog.isDef(opt_type) ? String(opt_type) : undefined; - return this.eventTargetListeners_.hasListener(id, opt_capture); -}; - - -/** - * 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; -}; - - -/** - * Asserts that the event target instance is initialized properly. - * @private - */ -goog.events.EventTarget.prototype.assertInitialized_ = function() { - goog.asserts.assert( - this.eventTargetListeners_, - 'Event target is not initialized. Did you call the superclass ' + - '(goog.events.EventTarget) constructor?'); -}; - - -/** - * Dispatches the given event on the ancestorsTree. - * - * @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; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventtype.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventtype.js deleted file mode 100644 index 67c1da6..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventtype.js +++ /dev/null @@ -1,232 +0,0 @@ -// 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 Event Types. - * - * @author arv@google.com (Erik Arvidsson) - */ - - -goog.provide('goog.events.EventType'); - -goog.require('goog.userAgent'); - - -/** - * Returns a prefixed event name for the current browser. - * @param {string} eventName The name of the event. - * @return {string} The prefixed event name. - * @suppress {missingRequire|missingProvide} - * @private - */ -goog.events.getVendorPrefixedName_ = function(eventName) { - return goog.userAgent.WEBKIT ? 'webkit' + eventName : - (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() : - eventName.toLowerCase()); -}; - - -/** - * Constants for event names. - * @enum {string} - */ -goog.events.EventType = { - // Mouse events - CLICK: 'click', - RIGHTCLICK: 'rightclick', - DBLCLICK: 'dblclick', - MOUSEDOWN: 'mousedown', - MOUSEUP: 'mouseup', - MOUSEOVER: 'mouseover', - MOUSEOUT: 'mouseout', - MOUSEMOVE: 'mousemove', - MOUSEENTER: 'mouseenter', - MOUSELEAVE: 'mouseleave', - // Select start is non-standard. - // See http://msdn.microsoft.com/en-us/library/ie/ms536969(v=vs.85).aspx. - SELECTSTART: 'selectstart', // IE, Safari, Chrome - - // Wheel events - // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents - WHEEL: 'wheel', - - // Key events - KEYPRESS: 'keypress', - KEYDOWN: 'keydown', - KEYUP: 'keyup', - - // Focus - BLUR: 'blur', - FOCUS: 'focus', - DEACTIVATE: 'deactivate', // IE only - // NOTE: The following two events are not stable in cross-browser usage. - // WebKit and Opera implement DOMFocusIn/Out. - // IE implements focusin/out. - // Gecko implements neither see bug at - // https://bugzilla.mozilla.org/show_bug.cgi?id=396927. - // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin: - // http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html - // You can use FOCUS in Capture phase until implementations converge. - FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn', - FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut', - - // Forms - CHANGE: 'change', - SELECT: 'select', - SUBMIT: 'submit', - INPUT: 'input', - PROPERTYCHANGE: 'propertychange', // IE only - - // Drag and drop - DRAGSTART: 'dragstart', - DRAG: 'drag', - DRAGENTER: 'dragenter', - DRAGOVER: 'dragover', - DRAGLEAVE: 'dragleave', - DROP: 'drop', - DRAGEND: 'dragend', - - // Touch events - // Note that other touch events exist, but we should follow the W3C list here. - // http://www.w3.org/TR/touch-events/#list-of-touchevent-types - TOUCHSTART: 'touchstart', - TOUCHMOVE: 'touchmove', - TOUCHEND: 'touchend', - TOUCHCANCEL: 'touchcancel', - - // Misc - BEFOREUNLOAD: 'beforeunload', - CONSOLEMESSAGE: 'consolemessage', - CONTEXTMENU: 'contextmenu', - DOMCONTENTLOADED: 'DOMContentLoaded', - ERROR: 'error', - HELP: 'help', - LOAD: 'load', - LOSECAPTURE: 'losecapture', - ORIENTATIONCHANGE: 'orientationchange', - READYSTATECHANGE: 'readystatechange', - RESIZE: 'resize', - SCROLL: 'scroll', - UNLOAD: 'unload', - - // HTML 5 History events - // See http://www.w3.org/TR/html5/history.html#event-definitions - HASHCHANGE: 'hashchange', - PAGEHIDE: 'pagehide', - PAGESHOW: 'pageshow', - POPSTATE: 'popstate', - - // Copy and Paste - // Support is limited. Make sure it works on your favorite browser - // before using. - // http://www.quirksmode.org/dom/events/cutcopypaste.html - COPY: 'copy', - PASTE: 'paste', - CUT: 'cut', - BEFORECOPY: 'beforecopy', - BEFORECUT: 'beforecut', - BEFOREPASTE: 'beforepaste', - - // HTML5 online/offline events. - // http://www.w3.org/TR/offline-webapps/#related - ONLINE: 'online', - OFFLINE: 'offline', - - // HTML 5 worker events - MESSAGE: 'message', - CONNECT: 'connect', - - // CSS animation events. - /** @suppress {missingRequire} */ - ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'), - /** @suppress {missingRequire} */ - ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'), - /** @suppress {missingRequire} */ - ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'), - - // CSS transition events. Based on the browser support described at: - // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility - /** @suppress {missingRequire} */ - TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'), - - // W3C Pointer Events - // http://www.w3.org/TR/pointerevents/ - POINTERDOWN: 'pointerdown', - POINTERUP: 'pointerup', - POINTERCANCEL: 'pointercancel', - POINTERMOVE: 'pointermove', - POINTEROVER: 'pointerover', - POINTEROUT: 'pointerout', - POINTERENTER: 'pointerenter', - POINTERLEAVE: 'pointerleave', - GOTPOINTERCAPTURE: 'gotpointercapture', - LOSTPOINTERCAPTURE: 'lostpointercapture', - - // IE specific events. - // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx - // Note: these events will be supplanted in IE11. - MSGESTURECHANGE: 'MSGestureChange', - MSGESTUREEND: 'MSGestureEnd', - MSGESTUREHOLD: 'MSGestureHold', - MSGESTURESTART: 'MSGestureStart', - MSGESTURETAP: 'MSGestureTap', - MSGOTPOINTERCAPTURE: 'MSGotPointerCapture', - MSINERTIASTART: 'MSInertiaStart', - MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture', - MSPOINTERCANCEL: 'MSPointerCancel', - MSPOINTERDOWN: 'MSPointerDown', - MSPOINTERENTER: 'MSPointerEnter', - MSPOINTERHOVER: 'MSPointerHover', - MSPOINTERLEAVE: 'MSPointerLeave', - MSPOINTERMOVE: 'MSPointerMove', - MSPOINTEROUT: 'MSPointerOut', - MSPOINTEROVER: 'MSPointerOver', - MSPOINTERUP: 'MSPointerUp', - - // Native IMEs/input tools events. - TEXT: 'text', - TEXTINPUT: 'textInput', - COMPOSITIONSTART: 'compositionstart', - COMPOSITIONUPDATE: 'compositionupdate', - COMPOSITIONEND: 'compositionend', - - // Webview tag events - // See http://developer.chrome.com/dev/apps/webview_tag.html - EXIT: 'exit', - LOADABORT: 'loadabort', - LOADCOMMIT: 'loadcommit', - LOADREDIRECT: 'loadredirect', - LOADSTART: 'loadstart', - LOADSTOP: 'loadstop', - RESPONSIVE: 'responsive', - SIZECHANGED: 'sizechanged', - UNRESPONSIVE: 'unresponsive', - - // HTML5 Page Visibility API. See details at - // {@code goog.labs.dom.PageVisibilityMonitor}. - VISIBILITYCHANGE: 'visibilitychange', - - // LocalStorage event. - STORAGE: 'storage', - - // DOM Level 2 mutation events (deprecated). - DOMSUBTREEMODIFIED: 'DOMSubtreeModified', - DOMNODEINSERTED: 'DOMNodeInserted', - DOMNODEREMOVED: 'DOMNodeRemoved', - DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument', - DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument', - DOMATTRMODIFIED: 'DOMAttrModified', - DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified' -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventwrapper.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventwrapper.js deleted file mode 100644 index 1581774..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/eventwrapper.js +++ /dev/null @@ -1,66 +0,0 @@ -// 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 {goog.events.ListenableType} src The node to listen to events on. - * @param {function(?):?|{handleEvent:function(?):?}|null} 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 {goog.events.ListenableType} src The node to remove listener from. - * @param {function(?):?|{handleEvent:function(?):?}|null} 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) { -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listenable.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listenable.js deleted file mode 100644 index a05b348..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listenable.js +++ /dev/null @@ -1,335 +0,0 @@ -// 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. - * @author chrishenry@google.com (Chris Henry) - */ - -goog.provide('goog.events.Listenable'); -goog.provide('goog.events.ListenableKey'); - -/** @suppress {extraRequire} */ -goog.require('goog.events.EventId'); - - - -/** - * A listenable interface. A listenable is an object with the ability - * to dispatch/broadcast events to "event listeners" registered via - * listen/listenOnce. - * - * The interface allows for an event propagation mechanism similar - * to one offered by native browser event targets, such as - * capture/bubble mechanism, stopping propagation, and preventing - * default actions. Capture/bubble mechanism depends on the ancestor - * tree constructed via {@code #getParentEventTarget}; this tree - * must be directed acyclic graph. The meaning of default action(s) - * in preventDefault is specific to a particular use case. - * - * Implementations that do not support capture/bubble or can not have - * a parent listenable can simply not implement any ability to set the - * parent listenable (and have {@code #getParentEventTarget} return - * null). - * - * Implementation of this class can be used with or independently from - * goog.events. - * - * Implementation must call {@code #addImplementation(implClass)}. - * - * @interface - * @see goog.events - * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html - */ -goog.events.Listenable = function() {}; - - -/** - * An expando property to indicate that an object implements - * goog.events.Listenable. - * - * See addImplementation/isImplementedBy. - * - * @type {string} - * @const - */ -goog.events.Listenable.IMPLEMENTED_BY_PROP = - 'closure_listenable_' + ((Math.random() * 1e6) | 0); - - -/** - * 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|!goog.events.EventId<EVENTOBJ>} type The event type id. - * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback - * method. - * @param {boolean=} opt_useCapture Whether to fire in capture phase - * (defaults to false). - * @param {SCOPE=} opt_listenerScope Object in whose scope to call the - * listener. - * @return {goog.events.ListenableKey} Unique key for the listener. - * @template SCOPE,EVENTOBJ - */ -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|!goog.events.EventId<EVENTOBJ>} type The event type id. - * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback - * method. - * @param {boolean=} opt_useCapture Whether to fire in capture phase - * (defaults to false). - * @param {SCOPE=} opt_listenerScope Object in whose scope to call the - * listener. - * @return {goog.events.ListenableKey} Unique key for the listener. - * @template SCOPE,EVENTOBJ - */ -goog.events.Listenable.prototype.listenOnce; - - -/** - * Removes an event listener which was added with listen() or listenOnce(). - * - * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id. - * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback - * method. - * @param {boolean=} opt_useCapture Whether to fire in capture phase - * (defaults to false). - * @param {SCOPE=} opt_listenerScope Object in whose scope to call - * the listener. - * @return {boolean} Whether any listener was removed. - * @template SCOPE,EVENTOBJ - */ -goog.events.Listenable.prototype.unlisten; - - -/** - * Removes an event listener which was added with listen() by the key - * returned by listen(). - * - * @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. - * - * @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; - - -/** - * Returns the parent of this event target to use for capture/bubble - * mechanism. - * - * NOTE(chrishenry): The name reflects the original implementation of - * custom event target ({@code goog.events.EventTarget}). We decided - * that changing the name is not worth it. - * - * @return {goog.events.Listenable} The parent EventTarget or null if - * there is no parent. - */ -goog.events.Listenable.prototype.getParentEventTarget; - - -/** - * 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|!goog.events.EventId<EVENTOBJ>} type The type of the - * listeners to fire. - * @param {boolean} capture The capture mode of the listeners to fire. - * @param {EVENTOBJ} 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. - * @template EVENTOBJ - */ -goog.events.Listenable.prototype.fireListeners; - - -/** - * Gets all listeners in this listenable for the given type and - * capture mode. - * - * @param {string|!goog.events.EventId} 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. - * @template EVENTOBJ - */ -goog.events.Listenable.prototype.getListeners; - - -/** - * Gets the goog.events.ListenableKey for the event or null if no such - * listener is in use. - * - * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event - * without the 'on' prefix. - * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The - * listener function to get. - * @param {boolean} capture Whether the listener is a capturing listener. - * @param {SCOPE=} opt_listenerScope Object in whose scope to call the - * listener. - * @return {goog.events.ListenableKey} the found listener or null if not found. - * @template SCOPE,EVENTOBJ - */ -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|!goog.events.EventId<EVENTOBJ>=} 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. - * @template EVENTOBJ - */ -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. - * @type {function(?):?|{handleEvent:function(?):?}|null} - */ -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; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listener.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listener.js deleted file mode 100644 index 60c7370..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listener.js +++ /dev/null @@ -1,131 +0,0 @@ -// 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 Listener object. - * @see ../demos/events.html - */ - -goog.provide('goog.events.Listener'); - -goog.require('goog.events.ListenableKey'); - - - -/** - * Simple class that stores information about a listener - * @param {!Function} listener Callback function. - * @param {Function} proxy Wrapper for the listener that patches the event. - * @param {EventTarget|goog.events.Listenable} src Source object for - * the event. - * @param {string} type Event type. - * @param {boolean} capture Whether in capture or bubble phase. - * @param {Object=} opt_handler Object in whose context to execute the callback. - * @implements {goog.events.ListenableKey} - * @constructor - */ -goog.events.Listener = function( - listener, proxy, src, type, capture, opt_handler) { - if (goog.events.Listener.ENABLE_MONITORING) { - this.creationStack = new Error().stack; - } - - /** - * Callback function. - * @type {Function} - */ - this.listener = listener; - - /** - * A wrapper over the original listener. This is used solely to - * handle native browser events (it is used to simulate the capture - * phase and to patch the event object). - * @type {Function} - */ - this.proxy = proxy; - - /** - * Object or node that callback is listening to - * @type {EventTarget|goog.events.Listenable} - */ - this.src = src; - - /** - * The event type. - * @const {string} - */ - this.type = type; - - /** - * Whether the listener is being called in the capture or bubble phase - * @const {boolean} - */ - this.capture = !!capture; - - /** - * Optional object whose context to execute the listener in - * @type {Object|undefined} - */ - this.handler = opt_handler; - - /** - * The key of the listener. - * @const {number} - * @override - */ - this.key = goog.events.ListenableKey.reserveKey(); - - /** - * Whether to remove the listener after it has been called. - * @type {boolean} - */ - this.callOnce = false; - - /** - * Whether the listener has been removed. - * @type {boolean} - */ - this.removed = false; -}; - - -/** - * @define {boolean} Whether to enable the monitoring of the - * goog.events.Listener instances. Switching on the monitoring is only - * recommended for debugging because it has a significant impact on - * performance and memory usage. If switched off, the monitoring code - * compiles down to 0 bytes. - */ -goog.define('goog.events.Listener.ENABLE_MONITORING', false); - - -/** - * If monitoring the goog.events.Listener instances is enabled, stores the - * creation stack trace of the Disposable instance. - * @type {string} - */ -goog.events.Listener.prototype.creationStack; - - -/** - * Marks this listener as removed. This also remove references held by - * this listener object (such as listener and event source). - */ -goog.events.Listener.prototype.markAsRemoved = function() { - this.removed = true; - this.listener = null; - this.proxy = null; - this.src = null; - this.handler = null; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listenermap.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listenermap.js deleted file mode 100644 index c20cdb9..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/events/listenermap.js +++ /dev/null @@ -1,308 +0,0 @@ -// 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 A map of listeners that provides utility functions to - * deal with listeners on an event target. Used by - * {@code goog.events.EventTarget}. - * - * WARNING: Do not use this class from outside goog.events package. - * - * @visibility {//closure/goog/bin/sizetests:__pkg__} - * @visibility {//closure/goog/events:__pkg__} - * @visibility {//closure/goog/labs/events:__pkg__} - */ - -goog.provide('goog.events.ListenerMap'); - -goog.require('goog.array'); -goog.require('goog.events.Listener'); -goog.require('goog.object'); - - - -/** - * Creates a new listener map. - * @param {EventTarget|goog.events.Listenable} src The src object. - * @constructor - * @final - */ -goog.events.ListenerMap = function(src) { - /** @type {EventTarget|goog.events.Listenable} */ - this.src = src; - - /** - * Maps of event type to an array of listeners. - * @type {Object<string, !Array<!goog.events.Listener>>} - */ - this.listeners = {}; - - /** - * The count of types in this map that have registered listeners. - * @private {number} - */ - this.typeCount_ = 0; -}; - - -/** - * @return {number} The count of event types in this map that actually - * have registered listeners. - */ -goog.events.ListenerMap.prototype.getTypeCount = function() { - return this.typeCount_; -}; - - -/** - * @return {number} Total number of registered listeners. - */ -goog.events.ListenerMap.prototype.getListenerCount = function() { - var count = 0; - for (var type in this.listeners) { - count += this.listeners[type].length; - } - return count; -}; - - -/** - * 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|!goog.events.EventId} type The listener event type. - * @param {!Function} listener This listener callback method. - * @param {boolean} callOnce Whether the listener is a one-off - * listener. - * @param {boolean=} opt_useCapture The capture mode of the listener. - * @param {Object=} opt_listenerScope Object in whose scope to call the - * listener. - * @return {goog.events.ListenableKey} Unique key for the listener. - */ -goog.events.ListenerMap.prototype.add = function( - type, listener, callOnce, opt_useCapture, opt_listenerScope) { - var typeStr = type.toString(); - var listenerArray = this.listeners[typeStr]; - if (!listenerArray) { - listenerArray = this.listeners[typeStr] = []; - this.typeCount_++; - } - - var listenerObj; - var index = goog.events.ListenerMap.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; - } - } else { - listenerObj = new goog.events.Listener( - listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope); - listenerObj.callOnce = callOnce; - listenerArray.push(listenerObj); - } - return listenerObj; -}; - - -/** - * Removes a matching listener. - * @param {string|!goog.events.EventId} type The listener event type. - * @param {!Function} listener This listener callback method. - * @param {boolean=} opt_useCapture The capture mode of the listener. - * @param {Object=} opt_listenerScope Object in whose scope to call the - * listener. - * @return {boolean} Whether any listener was removed. - */ -goog.events.ListenerMap.prototype.remove = function( - type, listener, opt_useCapture, opt_listenerScope) { - var typeStr = type.toString(); - if (!(typeStr in this.listeners)) { - return false; - } - - var listenerArray = this.listeners[typeStr]; - var index = goog.events.ListenerMap.findListenerIndex_( - listenerArray, listener, opt_useCapture, opt_listenerScope); - if (index > -1) { - var listenerObj = listenerArray[index]; - listenerObj.markAsRemoved(); - goog.array.removeAt(listenerArray, index); - if (listenerArray.length == 0) { - delete this.listeners[typeStr]; - this.typeCount_--; - } - return true; - } - return false; -}; - - -/** - * Removes the given listener object. - * @param {goog.events.ListenableKey} listener The listener to remove. - * @return {boolean} Whether the listener is removed. - */ -goog.events.ListenerMap.prototype.removeByKey = function(listener) { - var type = listener.type; - if (!(type in this.listeners)) { - return false; - } - - var removed = goog.array.remove(this.listeners[type], listener); - if (removed) { - listener.markAsRemoved(); - if (this.listeners[type].length == 0) { - delete this.listeners[type]; - this.typeCount_--; - } - } - return removed; -}; - - -/** - * Removes all listeners from this map. If opt_type is provided, only - * listeners that match the given type are removed. - * @param {string|!goog.events.EventId=} opt_type Type of event to remove. - * @return {number} Number of listeners removed. - */ -goog.events.ListenerMap.prototype.removeAll = function(opt_type) { - var typeStr = opt_type && opt_type.toString(); - var count = 0; - for (var type in this.listeners) { - if (!typeStr || type == typeStr) { - var listenerArray = this.listeners[type]; - for (var i = 0; i < listenerArray.length; i++) { - ++count; - listenerArray[i].markAsRemoved(); - } - delete this.listeners[type]; - this.typeCount_--; - } - } - return count; -}; - - -/** - * Gets all listeners that match the given type and capture mode. The - * returned array is a copy (but the listener objects are not). - * @param {string|!goog.events.EventId} type The type of the listeners - * to retrieve. - * @param {boolean} capture The capture mode of the listeners to retrieve. - * @return {!Array<goog.events.ListenableKey>} An array of matching - * listeners. - */ -goog.events.ListenerMap.prototype.getListeners = function(type, capture) { - var listenerArray = this.listeners[type.toString()]; - 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; -}; - - -/** - * Gets the goog.events.ListenableKey for the event or null if no such - * listener is in use. - * - * @param {string|!goog.events.EventId} type The type of the listener - * to retrieve. - * @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.ListenerMap.prototype.getListener = function( - type, listener, capture, opt_listenerScope) { - var listenerArray = this.listeners[type.toString()]; - var i = -1; - if (listenerArray) { - i = goog.events.ListenerMap.findListenerIndex_( - listenerArray, listener, capture, opt_listenerScope); - } - return i > -1 ? listenerArray[i] : null; -}; - - -/** - * Whether there is a matching listener. If either the type or capture - * parameters are unspecified, the function will match on the - * remaining criteria. - * - * @param {string|!goog.events.EventId=} opt_type The type of the listener. - * @param {boolean=} opt_capture The capture mode of the listener. - * @return {boolean} Whether there is an active listener matching - * the requested type and/or capture phase. - */ -goog.events.ListenerMap.prototype.hasListener = function( - opt_type, opt_capture) { - var hasType = goog.isDef(opt_type); - var typeStr = hasType ? opt_type.toString() : ''; - var hasCapture = goog.isDef(opt_capture); - - return goog.object.some( - this.listeners, function(listenerArray, type) { - for (var i = 0; i < listenerArray.length; ++i) { - if ((!hasType || listenerArray[i].type == typeStr) && - (!hasCapture || listenerArray[i].capture == opt_capture)) { - return true; - } - } - - return false; - }); -}; - - -/** - * 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.ListenerMap.findListenerIndex_ = function( - listenerArray, listener, opt_useCapture, opt_listenerScope) { - for (var i = 0; i < listenerArray.length; ++i) { - var listenerObj = listenerArray[i]; - if (!listenerObj.removed && - listenerObj.listener == listener && - listenerObj.capture == !!opt_useCapture && - listenerObj.handler == opt_listenerScope) { - return i; - } - } - return -1; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/fs/url.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/fs/url.js deleted file mode 100644 index 083c066..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/fs/url.js +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2015 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 Wrapper for URL and its createObjectUrl and revokeObjectUrl - * methods that are part of the HTML5 File API. - */ - -goog.provide('goog.fs.url'); - - -/** - * Creates a blob URL for a blob object. - * Throws an error if the browser does not support Object Urls. - * - * @param {!Blob} blob The object for which to create the URL. - * @return {string} The URL for the object. - */ -goog.fs.url.createObjectUrl = function(blob) { - return goog.fs.url.getUrlObject_().createObjectURL(blob); -}; - - -/** - * Revokes a URL created by {@link goog.fs.url.createObjectUrl}. - * Throws an error if the browser does not support Object Urls. - * - * @param {string} url The URL to revoke. - */ -goog.fs.url.revokeObjectUrl = function(url) { - goog.fs.url.getUrlObject_().revokeObjectURL(url); -}; - - -/** - * @typedef {{createObjectURL: (function(!Blob): string), - * revokeObjectURL: function(string): void}} - */ -goog.fs.url.UrlObject_; - - -/** - * Get the object that has the createObjectURL and revokeObjectURL functions for - * this browser. - * - * @return {goog.fs.url.UrlObject_} The object for this browser. - * @private - */ -goog.fs.url.getUrlObject_ = function() { - var urlObject = goog.fs.url.findUrlObject_(); - if (urlObject != null) { - return urlObject; - } else { - throw Error('This browser doesn\'t seem to support blob URLs'); - } -}; - - -/** - * Finds the object that has the createObjectURL and revokeObjectURL functions - * for this browser. - * - * @return {?goog.fs.url.UrlObject_} The object for this browser or null if the - * browser does not support Object Urls. - * @private - */ -goog.fs.url.findUrlObject_ = 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.url.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.url.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.url.UrlObject_} */ (goog.global); - } else { - return null; - } -}; - - -/** - * Checks whether this browser supports Object Urls. If not, calls to - * createObjectUrl and revokeObjectUrl will result in an error. - * - * @return {boolean} True if this browser supports Object Urls. - */ -goog.fs.url.browserSupportsObjectUrls = function() { - return goog.fs.url.findUrlObject_() != null; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/functions/functions.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/functions/functions.js deleted file mode 100644 index d7ccf40..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/functions/functions.js +++ /dev/null @@ -1,332 +0,0 @@ -// 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 for creating functions. Loosely inspired by the - * java classes: http://goo.gl/GM0Hmu and http://goo.gl/6k7nI8. - * - * @author nicksantos@google.com (Nick Santos) - */ - - -goog.provide('goog.functions'); - - -/** - * Creates a function that always returns the same value. - * @param {T} retValue The value to return. - * @return {function():T} The new function. - * @template T - */ -goog.functions.constant = function(retValue) { - return function() { - return retValue; - }; -}; - - -/** - * Always returns false. - * @type {function(...): boolean} - */ -goog.functions.FALSE = goog.functions.constant(false); - - -/** - * Always returns true. - * @type {function(...): boolean} - */ -goog.functions.TRUE = goog.functions.constant(true); - - -/** - * Always returns NULL. - * @type {function(...): null} - */ -goog.functions.NULL = goog.functions.constant(null); - - -/** - * A simple function that returns the first argument of whatever is passed - * into it. - * @param {T=} opt_returnValue The single value that will be returned. - * @param {...*} var_args Optional trailing arguments. These are ignored. - * @return {T} The first argument passed in, or undefined if nothing was passed. - * @template T - */ -goog.functions.identity = function(opt_returnValue, var_args) { - return opt_returnValue; -}; - - -/** - * Creates a function that always throws an error with the given message. - * @param {string} message The error message. - * @return {!Function} The error-throwing function. - */ -goog.functions.error = function(message) { - return function() { - throw Error(message); - }; -}; - - -/** - * Creates a function that throws the given object. - * @param {*} err An object to be thrown. - * @return {!Function} The error-throwing function. - */ -goog.functions.fail = function(err) { - return function() { - throw err; - } -}; - - -/** - * Given a function, create a function that keeps opt_numArgs arguments and - * silently discards all additional arguments. - * @param {Function} f The original function. - * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0. - * @return {!Function} A version of f that only keeps the first opt_numArgs - * arguments. - */ -goog.functions.lock = function(f, opt_numArgs) { - opt_numArgs = opt_numArgs || 0; - return function() { - return f.apply(this, Array.prototype.slice.call(arguments, 0, opt_numArgs)); - }; -}; - - -/** - * Creates a function that returns its nth argument. - * @param {number} n The position of the return argument. - * @return {!Function} A new function. - */ -goog.functions.nth = function(n) { - return function() { - return arguments[n]; - }; -}; - - -/** - * Given a function, create a new function that swallows its return value - * and replaces it with a new one. - * @param {Function} f A function. - * @param {T} retValue A new return value. - * @return {function(...?):T} A new function. - * @template T - */ -goog.functions.withReturnValue = function(f, retValue) { - return goog.functions.sequence(f, goog.functions.constant(retValue)); -}; - - -/** - * Creates a function that returns whether its arguement equals the given value. - * - * Example: - * var key = goog.object.findKey(obj, goog.functions.equalTo('needle')); - * - * @param {*} value The value to compare to. - * @param {boolean=} opt_useLooseComparison Whether to use a loose (==) - * comparison rather than a strict (===) one. Defaults to false. - * @return {function(*):boolean} The new function. - */ -goog.functions.equalTo = function(value, opt_useLooseComparison) { - return function(other) { - return opt_useLooseComparison ? (value == other) : (value === other); - }; -}; - - -/** - * Creates the composition of the functions passed in. - * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)). - * @param {function(...?):T} fn The final function. - * @param {...Function} var_args A list of functions. - * @return {function(...?):T} The composition of all inputs. - * @template T - */ -goog.functions.compose = function(fn, var_args) { - var functions = arguments; - var length = functions.length; - return function() { - var result; - if (length) { - result = functions[length - 1].apply(this, arguments); - } - - for (var i = length - 2; i >= 0; i--) { - result = functions[i].call(this, result); - } - return result; - }; -}; - - -/** - * Creates a function that calls the functions passed in in sequence, and - * returns the value of the last function. For example, - * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x). - * @param {...Function} var_args A list of functions. - * @return {!Function} A function that calls all inputs in sequence. - */ -goog.functions.sequence = function(var_args) { - var functions = arguments; - var length = functions.length; - return function() { - var result; - for (var i = 0; i < length; i++) { - result = functions[i].apply(this, arguments); - } - return result; - }; -}; - - -/** - * Creates a function that returns true if each of its components evaluates - * to true. The components are evaluated in order, and the evaluation will be - * short-circuited as soon as a function returns false. - * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x). - * @param {...Function} var_args A list of functions. - * @return {function(...?):boolean} A function that ANDs its component - * functions. - */ -goog.functions.and = function(var_args) { - var functions = arguments; - var length = functions.length; - return function() { - for (var i = 0; i < length; i++) { - if (!functions[i].apply(this, arguments)) { - return false; - } - } - return true; - }; -}; - - -/** - * Creates a function that returns true if any of its components evaluates - * to true. The components are evaluated in order, and the evaluation will be - * short-circuited as soon as a function returns true. - * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x). - * @param {...Function} var_args A list of functions. - * @return {function(...?):boolean} A function that ORs its component - * functions. - */ -goog.functions.or = function(var_args) { - var functions = arguments; - var length = functions.length; - return function() { - for (var i = 0; i < length; i++) { - if (functions[i].apply(this, arguments)) { - return true; - } - } - return false; - }; -}; - - -/** - * Creates a function that returns the Boolean opposite of a provided function. - * For example, (goog.functions.not(f))(x) is equivalent to !f(x). - * @param {!Function} f The original function. - * @return {function(...?):boolean} A function that delegates to f and returns - * opposite. - */ -goog.functions.not = function(f) { - return function() { - return !f.apply(this, arguments); - }; -}; - - -/** - * Generic factory function to construct an object given the constructor - * and the arguments. Intended to be bound to create object factories. - * - * Example: - * - * var factory = goog.partial(goog.functions.create, Class); - * - * @param {function(new:T, ...)} constructor The constructor for the Object. - * @param {...*} var_args The arguments to be passed to the constructor. - * @return {T} A new instance of the class given in {@code constructor}. - * @template T - */ -goog.functions.create = function(constructor, var_args) { - /** - * @constructor - * @final - */ - var temp = function() {}; - temp.prototype = constructor.prototype; - - // obj will have constructor's prototype in its chain and - // 'obj instanceof constructor' will be true. - var obj = new temp(); - - // obj is initialized by constructor. - // arguments is only array-like so lacks shift(), but can be used with - // the Array prototype function. - constructor.apply(obj, Array.prototype.slice.call(arguments, 1)); - return obj; -}; - - -/** - * @define {boolean} Whether the return value cache should be used. - * This should only be used to disable caches when testing. - */ -goog.define('goog.functions.CACHE_RETURN_VALUE', true); - - -/** - * Gives a wrapper function that caches the return value of a parameterless - * function when first called. - * - * When called for the first time, the given function is called and its - * return value is cached (thus this is only appropriate for idempotent - * functions). Subsequent calls will return the cached return value. This - * allows the evaluation of expensive functions to be delayed until first used. - * - * To cache the return values of functions with parameters, see goog.memoize. - * - * @param {!function():T} fn A function to lazily evaluate. - * @return {!function():T} A wrapped version the function. - * @template T - */ -goog.functions.cacheReturnValue = function(fn) { - var called = false; - var value; - - return function() { - if (!goog.functions.CACHE_RETURN_VALUE) { - return fn(); - } - - if (!called) { - value = fn(); - called = true; - } - - return value; - } -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safehtml.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safehtml.js deleted file mode 100644 index 4a99af5..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safehtml.js +++ /dev/null @@ -1,744 +0,0 @@ -// 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 The SafeHtml type and its builders. - * - * TODO(user): Link to document stating type contract. - */ - -goog.provide('goog.html.SafeHtml'); - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.dom.tags'); -goog.require('goog.html.SafeStyle'); -goog.require('goog.html.SafeStyleSheet'); -goog.require('goog.html.SafeUrl'); -goog.require('goog.html.TrustedResourceUrl'); -goog.require('goog.i18n.bidi.Dir'); -goog.require('goog.i18n.bidi.DirectionalString'); -goog.require('goog.object'); -goog.require('goog.string'); -goog.require('goog.string.Const'); -goog.require('goog.string.TypedString'); - - - -/** - * A string that is safe to use in HTML context in DOM APIs and HTML documents. - * - * A SafeHtml is a string-like object that carries the security type contract - * that its value as a string will not cause untrusted script execution when - * evaluated as HTML in a browser. - * - * Values of this type are guaranteed to be safe to use in HTML contexts, - * such as, assignment to the innerHTML DOM property, or interpolation into - * a HTML template in HTML PC_DATA context, in the sense that the use will not - * result in a Cross-Site-Scripting vulnerability. - * - * Instances of this type must be created via the factory methods - * ({@code goog.html.SafeHtml.create}, {@code goog.html.SafeHtml.htmlEscape}), - * etc and not by invoking its constructor. The constructor intentionally - * takes no parameters and the type is immutable; hence only a default instance - * corresponding to the empty string can be obtained via constructor invocation. - * - * @see goog.html.SafeHtml#create - * @see goog.html.SafeHtml#htmlEscape - * @constructor - * @final - * @struct - * @implements {goog.i18n.bidi.DirectionalString} - * @implements {goog.string.TypedString} - */ -goog.html.SafeHtml = function() { - /** - * The contained value of this SafeHtml. The field has a purposely ugly - * name to make (non-compiled) code that attempts to directly access this - * field stand out. - * @private {string} - */ - this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = ''; - - /** - * A type marker used to implement additional run-time type checking. - * @see goog.html.SafeHtml#unwrap - * @const - * @private - */ - this.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = - goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; - - /** - * This SafeHtml's directionality, or null if unknown. - * @private {?goog.i18n.bidi.Dir} - */ - this.dir_ = null; -}; - - -/** - * @override - * @const - */ -goog.html.SafeHtml.prototype.implementsGoogI18nBidiDirectionalString = true; - - -/** @override */ -goog.html.SafeHtml.prototype.getDirection = function() { - return this.dir_; -}; - - -/** - * @override - * @const - */ -goog.html.SafeHtml.prototype.implementsGoogStringTypedString = true; - - -/** - * Returns this SafeHtml's value a string. - * - * IMPORTANT: In code where it is security relevant that an object's type is - * indeed {@code SafeHtml}, use {@code goog.html.SafeHtml.unwrap} instead of - * this method. If in doubt, assume that it's security relevant. In particular, - * note that goog.html functions which return a goog.html type do not guarantee - * that the returned instance is of the right type. For example: - * - * <pre> - * var fakeSafeHtml = new String('fake'); - * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; - * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); - * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by - * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml - * // instanceof goog.html.SafeHtml. - * </pre> - * - * @see goog.html.SafeHtml#unwrap - * @override - */ -goog.html.SafeHtml.prototype.getTypedStringValue = function() { - return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_; -}; - - -if (goog.DEBUG) { - /** - * Returns a debug string-representation of this value. - * - * To obtain the actual string value wrapped in a SafeHtml, use - * {@code goog.html.SafeHtml.unwrap}. - * - * @see goog.html.SafeHtml#unwrap - * @override - */ - goog.html.SafeHtml.prototype.toString = function() { - return 'SafeHtml{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ + - '}'; - }; -} - - -/** - * Performs a runtime check that the provided object is indeed a SafeHtml - * object, and returns its value. - * @param {!goog.html.SafeHtml} safeHtml The object to extract from. - * @return {string} The SafeHtml object's contained string, unless the run-time - * type check fails. In that case, {@code unwrap} returns an innocuous - * string, or, if assertions are enabled, throws - * {@code goog.asserts.AssertionError}. - */ -goog.html.SafeHtml.unwrap = function(safeHtml) { - // Perform additional run-time type-checking to ensure that safeHtml is indeed - // an instance of the expected type. This provides some additional protection - // against security bugs due to application code that disables type checks. - // Specifically, the following checks are performed: - // 1. The object is an instance of the expected type. - // 2. The object is not an instance of a subclass. - // 3. The object carries a type marker for the expected type. "Faking" an - // object requires a reference to the type marker, which has names intended - // to stand out in code reviews. - if (safeHtml instanceof goog.html.SafeHtml && - safeHtml.constructor === goog.html.SafeHtml && - safeHtml.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === - goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { - return safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_; - } else { - goog.asserts.fail('expected object of type SafeHtml, got \'' + - safeHtml + '\''); - return 'type_error:SafeHtml'; - } -}; - - -/** - * Shorthand for union of types that can sensibly be converted to strings - * or might already be SafeHtml (as SafeHtml is a goog.string.TypedString). - * @private - * @typedef {string|number|boolean|!goog.string.TypedString| - * !goog.i18n.bidi.DirectionalString} - */ -goog.html.SafeHtml.TextOrHtml_; - - -/** - * Returns HTML-escaped text as a SafeHtml object. - * - * If text is of a type that implements - * {@code goog.i18n.bidi.DirectionalString}, the directionality of the new - * {@code SafeHtml} object is set to {@code text}'s directionality, if known. - * Otherwise, the directionality of the resulting SafeHtml is unknown (i.e., - * {@code null}). - * - * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If - * the parameter is of type SafeHtml it is returned directly (no escaping - * is done). - * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. - */ -goog.html.SafeHtml.htmlEscape = function(textOrHtml) { - if (textOrHtml instanceof goog.html.SafeHtml) { - return textOrHtml; - } - var dir = null; - if (textOrHtml.implementsGoogI18nBidiDirectionalString) { - dir = textOrHtml.getDirection(); - } - var textAsString; - if (textOrHtml.implementsGoogStringTypedString) { - textAsString = textOrHtml.getTypedStringValue(); - } else { - textAsString = String(textOrHtml); - } - return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( - goog.string.htmlEscape(textAsString), dir); -}; - - -/** - * Returns HTML-escaped text as a SafeHtml object, with newlines changed to - * <br>. - * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If - * the parameter is of type SafeHtml it is returned directly (no escaping - * is done). - * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. - */ -goog.html.SafeHtml.htmlEscapePreservingNewlines = function(textOrHtml) { - if (textOrHtml instanceof goog.html.SafeHtml) { - return textOrHtml; - } - var html = goog.html.SafeHtml.htmlEscape(textOrHtml); - return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( - goog.string.newLineToBr(goog.html.SafeHtml.unwrap(html)), - html.getDirection()); -}; - - -/** - * Returns HTML-escaped text as a SafeHtml object, with newlines changed to - * <br> and escaping whitespace to preserve spatial formatting. Character - * entity #160 is used to make it safer for XML. - * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If - * the parameter is of type SafeHtml it is returned directly (no escaping - * is done). - * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. - */ -goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces = function( - textOrHtml) { - if (textOrHtml instanceof goog.html.SafeHtml) { - return textOrHtml; - } - var html = goog.html.SafeHtml.htmlEscape(textOrHtml); - return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( - goog.string.whitespaceEscape(goog.html.SafeHtml.unwrap(html)), - html.getDirection()); -}; - - -/** - * Coerces an arbitrary object into a SafeHtml object. - * - * If {@code textOrHtml} is already of type {@code goog.html.SafeHtml}, the same - * object is returned. Otherwise, {@code textOrHtml} is coerced to string, and - * HTML-escaped. If {@code textOrHtml} is of a type that implements - * {@code goog.i18n.bidi.DirectionalString}, its directionality, if known, is - * preserved. - * - * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text or SafeHtml to - * coerce. - * @return {!goog.html.SafeHtml} The resulting SafeHtml object. - * @deprecated Use goog.html.SafeHtml.htmlEscape. - */ -goog.html.SafeHtml.from = goog.html.SafeHtml.htmlEscape; - - -/** - * @const - * @private - */ -goog.html.SafeHtml.VALID_NAMES_IN_TAG_ = /^[a-zA-Z0-9-]+$/; - - -/** - * Set of attributes containing URL as defined at - * http://www.w3.org/TR/html5/index.html#attributes-1. - * @private @const {!Object<string,boolean>} - */ -goog.html.SafeHtml.URL_ATTRIBUTES_ = goog.object.createSet('action', 'cite', - 'data', 'formaction', 'href', 'manifest', 'poster', 'src'); - - -/** - * Tags which are unsupported via create(). They might be supported via a - * tag-specific create method. These are tags which might require a - * TrustedResourceUrl in one of their attributes or a restricted type for - * their content. - * @private @const {!Object<string,boolean>} - */ -goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_ = goog.object.createSet( - 'embed', 'iframe', 'link', 'object', 'script', 'style', 'template'); - - -/** - * @typedef {string|number|goog.string.TypedString| - * goog.html.SafeStyle.PropertyMap} - * @private - */ -goog.html.SafeHtml.AttributeValue_; - - -/** - * Creates a SafeHtml content consisting of a tag with optional attributes and - * optional content. - * - * For convenience tag names and attribute names are accepted as regular - * strings, instead of goog.string.Const. Nevertheless, you should not pass - * user-controlled values to these parameters. Note that these parameters are - * syntactically validated at runtime, and invalid values will result in - * an exception. - * - * Example usage: - * - * goog.html.SafeHtml.create('br'); - * goog.html.SafeHtml.create('div', {'class': 'a'}); - * goog.html.SafeHtml.create('p', {}, 'a'); - * goog.html.SafeHtml.create('p', {}, goog.html.SafeHtml.create('br')); - * - * goog.html.SafeHtml.create('span', { - * 'style': {'margin': '0'} - * }); - * - * To guarantee SafeHtml's type contract is upheld there are restrictions on - * attribute values and tag names. - * - * - For attributes which contain script code (on*), a goog.string.Const is - * required. - * - For attributes which contain style (style), a goog.html.SafeStyle or a - * goog.html.SafeStyle.PropertyMap is required. - * - For attributes which are interpreted as URLs (e.g. src, href) a - * goog.html.SafeUrl or goog.string.Const is required. - * - For tags which can load code, more specific goog.html.SafeHtml.create*() - * functions must be used. Tags which can load code and are not supported by - * this function are embed, iframe, link, object, script, style, and template. - * - * @param {string} tagName The name of the tag. Only tag names consisting of - * [a-zA-Z0-9-] are allowed. Tag names documented above are disallowed. - * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} - * opt_attributes Mapping from attribute names to their values. Only - * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or - * undefined causes the attribute to be omitted. - * @param {!goog.html.SafeHtml.TextOrHtml_| - * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to - * HTML-escape and put inside the tag. This must be empty for void tags - * like <br>. Array elements are concatenated. - * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. - * @throws {Error} If invalid tag name, attribute name, or attribute value is - * provided. - * @throws {goog.asserts.AssertionError} If content for void tag is provided. - */ -goog.html.SafeHtml.create = function(tagName, opt_attributes, opt_content) { - if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(tagName)) { - throw Error('Invalid tag name <' + tagName + '>.'); - } - if (tagName.toLowerCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) { - throw Error('Tag name <' + tagName + '> is not allowed for SafeHtml.'); - } - return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( - tagName, opt_attributes, opt_content); -}; - - -/** - * Creates a SafeHtml representing an iframe tag. - * - * By default the sandbox attribute is set to an empty value, which is the most - * secure option, as it confers the iframe the least privileges. If this - * is too restrictive then granting individual privileges is the preferable - * option. Unsetting the attribute entirely is the least secure option and - * should never be done unless it's stricly necessary. - * - * @param {goog.html.TrustedResourceUrl=} opt_src The value of the src - * attribute. If null or undefined src will not be set. - * @param {goog.html.SafeHtml=} opt_srcdoc The value of the srcdoc attribute. - * If null or undefined srcdoc will not be set. - * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} - * opt_attributes Mapping from attribute names to their values. Only - * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or - * undefined causes the attribute to be omitted. - * @param {!goog.html.SafeHtml.TextOrHtml_| - * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to - * HTML-escape and put inside the tag. Array elements are concatenated. - * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. - * @throws {Error} If invalid tag name, attribute name, or attribute value is - * provided. If opt_attributes contains the src or srcdoc attributes. - */ -goog.html.SafeHtml.createIframe = function( - opt_src, opt_srcdoc, opt_attributes, opt_content) { - var fixedAttributes = {}; - fixedAttributes['src'] = opt_src || null; - fixedAttributes['srcdoc'] = opt_srcdoc || null; - var defaultAttributes = {'sandbox': ''}; - var attributes = goog.html.SafeHtml.combineAttributes( - fixedAttributes, defaultAttributes, opt_attributes); - return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( - 'iframe', attributes, opt_content); -}; - - -/** - * Creates a SafeHtml representing a style tag. The type attribute is set - * to "text/css". - * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>} - * styleSheet Content to put inside the tag. Array elements are - * concatenated. - * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} - * opt_attributes Mapping from attribute names to their values. Only - * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or - * undefined causes the attribute to be omitted. - * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. - * @throws {Error} If invalid attribute name or attribute value is provided. If - * opt_attributes contains the type attribute. - */ -goog.html.SafeHtml.createStyle = function(styleSheet, opt_attributes) { - var fixedAttributes = {'type': 'text/css'}; - var defaultAttributes = {}; - var attributes = goog.html.SafeHtml.combineAttributes( - fixedAttributes, defaultAttributes, opt_attributes); - - var content = ''; - styleSheet = goog.array.concat(styleSheet); - for (var i = 0; i < styleSheet.length; i++) { - content += goog.html.SafeStyleSheet.unwrap(styleSheet[i]); - } - // Convert to SafeHtml so that it's not HTML-escaped. - var htmlContent = goog.html.SafeHtml - .createSafeHtmlSecurityPrivateDoNotAccessOrElse( - content, goog.i18n.bidi.Dir.NEUTRAL); - return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( - 'style', attributes, htmlContent); -}; - - -/** - * @param {string} tagName The tag name. - * @param {string} name The attribute name. - * @param {!goog.html.SafeHtml.AttributeValue_} value The attribute value. - * @return {string} A "name=value" string. - * @throws {Error} If attribute value is unsafe for the given tag and attribute. - * @private - */ -goog.html.SafeHtml.getAttrNameAndValue_ = function(tagName, name, value) { - // If it's goog.string.Const, allow any valid attribute name. - if (value instanceof goog.string.Const) { - value = goog.string.Const.unwrap(value); - } else if (name.toLowerCase() == 'style') { - value = goog.html.SafeHtml.getStyleValue_(value); - } else if (/^on/i.test(name)) { - // TODO(jakubvrana): Disallow more attributes with a special meaning. - throw Error('Attribute "' + name + - '" requires goog.string.Const value, "' + value + '" given.'); - // URL attributes handled differently accroding to tag. - } else if (name.toLowerCase() in goog.html.SafeHtml.URL_ATTRIBUTES_) { - if (value instanceof goog.html.TrustedResourceUrl) { - value = goog.html.TrustedResourceUrl.unwrap(value); - } else if (value instanceof goog.html.SafeUrl) { - value = goog.html.SafeUrl.unwrap(value); - } else { - // TODO(user): Allow strings and sanitize them automatically, - // so that it's consistent with accepting a map directly for "style". - throw Error('Attribute "' + name + '" on tag "' + tagName + - '" requires goog.html.SafeUrl or goog.string.Const value, "' + - value + '" given.'); - } - } - - // Accept SafeUrl, TrustedResourceUrl, etc. for attributes which only require - // HTML-escaping. - if (value.implementsGoogStringTypedString) { - // Ok to call getTypedStringValue() since there's no reliance on the type - // contract for security here. - value = value.getTypedStringValue(); - } - - goog.asserts.assert(goog.isString(value) || goog.isNumber(value), - 'String or number value expected, got ' + - (typeof value) + ' with value: ' + value); - return name + '="' + goog.string.htmlEscape(String(value)) + '"'; -}; - - -/** - * Gets value allowed in "style" attribute. - * @param {goog.html.SafeHtml.AttributeValue_} value It could be SafeStyle or a - * map which will be passed to goog.html.SafeStyle.create. - * @return {string} Unwrapped value. - * @throws {Error} If string value is given. - * @private - */ -goog.html.SafeHtml.getStyleValue_ = function(value) { - if (!goog.isObject(value)) { - throw Error('The "style" attribute requires goog.html.SafeStyle or map ' + - 'of style properties, ' + (typeof value) + ' given: ' + value); - } - if (!(value instanceof goog.html.SafeStyle)) { - // Process the property bag into a style object. - value = goog.html.SafeStyle.create(value); - } - return goog.html.SafeStyle.unwrap(value); -}; - - -/** - * Creates a SafeHtml content with known directionality consisting of a tag with - * optional attributes and optional content. - * @param {!goog.i18n.bidi.Dir} dir Directionality. - * @param {string} tagName - * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} opt_attributes - * @param {!goog.html.SafeHtml.TextOrHtml_| - * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content - * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. - */ -goog.html.SafeHtml.createWithDir = function(dir, tagName, opt_attributes, - opt_content) { - var html = goog.html.SafeHtml.create(tagName, opt_attributes, opt_content); - html.dir_ = dir; - return html; -}; - - -/** - * Creates a new SafeHtml object by concatenating values. - * @param {...(!goog.html.SafeHtml.TextOrHtml_| - * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Values to concatenate. - * @return {!goog.html.SafeHtml} - */ -goog.html.SafeHtml.concat = function(var_args) { - var dir = goog.i18n.bidi.Dir.NEUTRAL; - var content = ''; - - /** - * @param {!goog.html.SafeHtml.TextOrHtml_| - * !Array<!goog.html.SafeHtml.TextOrHtml_>} argument - */ - var addArgument = function(argument) { - if (goog.isArray(argument)) { - goog.array.forEach(argument, addArgument); - } else { - var html = goog.html.SafeHtml.htmlEscape(argument); - content += goog.html.SafeHtml.unwrap(html); - var htmlDir = html.getDirection(); - if (dir == goog.i18n.bidi.Dir.NEUTRAL) { - dir = htmlDir; - } else if (htmlDir != goog.i18n.bidi.Dir.NEUTRAL && dir != htmlDir) { - dir = null; - } - } - }; - - goog.array.forEach(arguments, addArgument); - return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( - content, dir); -}; - - -/** - * Creates a new SafeHtml object with known directionality by concatenating the - * values. - * @param {!goog.i18n.bidi.Dir} dir Directionality. - * @param {...(!goog.html.SafeHtml.TextOrHtml_| - * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Elements of array - * arguments would be processed recursively. - * @return {!goog.html.SafeHtml} - */ -goog.html.SafeHtml.concatWithDir = function(dir, var_args) { - var html = goog.html.SafeHtml.concat(goog.array.slice(arguments, 1)); - html.dir_ = dir; - return html; -}; - - -/** - * Type marker for the SafeHtml type, used to implement additional run-time - * type checking. - * @const - * @private - */ -goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; - - -/** - * Package-internal utility method to create SafeHtml instances. - * - * @param {string} html The string to initialize the SafeHtml object with. - * @param {?goog.i18n.bidi.Dir} dir The directionality of the SafeHtml to be - * constructed, or null if unknown. - * @return {!goog.html.SafeHtml} The initialized SafeHtml object. - * @package - */ -goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse = function( - html, dir) { - return new goog.html.SafeHtml().initSecurityPrivateDoNotAccessOrElse_( - html, dir); -}; - - -/** - * Called from createSafeHtmlSecurityPrivateDoNotAccessOrElse(). This - * method exists only so that the compiler can dead code eliminate static - * fields (like EMPTY) when they're not accessed. - * @param {string} html - * @param {?goog.i18n.bidi.Dir} dir - * @return {!goog.html.SafeHtml} - * @private - */ -goog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( - html, dir) { - this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = html; - this.dir_ = dir; - return this; -}; - - -/** - * Like create() but does not restrict which tags can be constructed. - * - * @param {string} tagName Tag name. Set or validated by caller. - * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} opt_attributes - * @param {(!goog.html.SafeHtml.TextOrHtml_| - * !Array<!goog.html.SafeHtml.TextOrHtml_>)=} opt_content - * @return {!goog.html.SafeHtml} - * @throws {Error} If invalid or unsafe attribute name or value is provided. - * @throws {goog.asserts.AssertionError} If content for void tag is provided. - * @package - */ -goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse = - function(tagName, opt_attributes, opt_content) { - var dir = null; - var result = '<' + tagName; - - if (opt_attributes) { - for (var name in opt_attributes) { - if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(name)) { - throw Error('Invalid attribute name "' + name + '".'); - } - var value = opt_attributes[name]; - if (!goog.isDefAndNotNull(value)) { - continue; - } - result += ' ' + - goog.html.SafeHtml.getAttrNameAndValue_(tagName, name, value); - } - } - - var content = opt_content; - if (!goog.isDef(content)) { - content = []; - } else if (!goog.isArray(content)) { - content = [content]; - } - - if (goog.dom.tags.isVoidTag(tagName.toLowerCase())) { - goog.asserts.assert(!content.length, - 'Void tag <' + tagName + '> does not allow content.'); - result += '>'; - } else { - var html = goog.html.SafeHtml.concat(content); - result += '>' + goog.html.SafeHtml.unwrap(html) + '</' + tagName + '>'; - dir = html.getDirection(); - } - - var dirAttribute = opt_attributes && opt_attributes['dir']; - if (dirAttribute) { - if (/^(ltr|rtl|auto)$/i.test(dirAttribute)) { - // If the tag has the "dir" attribute specified then its direction is - // neutral because it can be safely used in any context. - dir = goog.i18n.bidi.Dir.NEUTRAL; - } else { - dir = null; - } - } - - return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( - result, dir); -}; - - -/** - * @param {!Object<string, string>} fixedAttributes - * @param {!Object<string, string>} defaultAttributes - * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} - * opt_attributes Optional attributes passed to create*(). - * @return {!Object<string, goog.html.SafeHtml.AttributeValue_>} - * @throws {Error} If opt_attributes contains an attribute with the same name - * as an attribute in fixedAttributes. - * @package - */ -goog.html.SafeHtml.combineAttributes = function( - fixedAttributes, defaultAttributes, opt_attributes) { - var combinedAttributes = {}; - var name; - - for (name in fixedAttributes) { - goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case'); - combinedAttributes[name] = fixedAttributes[name]; - } - for (name in defaultAttributes) { - goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case'); - combinedAttributes[name] = defaultAttributes[name]; - } - - for (name in opt_attributes) { - var nameLower = name.toLowerCase(); - if (nameLower in fixedAttributes) { - throw Error('Cannot override "' + nameLower + '" attribute, got "' + - name + '" with value "' + opt_attributes[name] + '"'); - } - if (nameLower in defaultAttributes) { - delete combinedAttributes[nameLower]; - } - combinedAttributes[name] = opt_attributes[name]; - } - - return combinedAttributes; -}; - - -/** - * A SafeHtml instance corresponding to the empty string. - * @const {!goog.html.SafeHtml} - */ -goog.html.SafeHtml.EMPTY = - goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( - '', goog.i18n.bidi.Dir.NEUTRAL); diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safescript.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safescript.js deleted file mode 100644 index 83995aa..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safescript.js +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2014 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 SafeScript type and its builders. - * - * TODO(user): Link to document stating type contract. - */ - -goog.provide('goog.html.SafeScript'); - -goog.require('goog.asserts'); -goog.require('goog.string.Const'); -goog.require('goog.string.TypedString'); - - - -/** - * A string-like object which represents JavaScript code and that carries the - * security type contract that its value, as a string, will not cause execution - * of unconstrained attacker controlled code (XSS) when evaluated as JavaScript - * in a browser. - * - * Instances of this type must be created via the factory method - * {@code goog.html.SafeScript.fromConstant} and not by invoking its - * constructor. The constructor intentionally takes no parameters and the type - * is immutable; hence only a default instance corresponding to the empty string - * can be obtained via constructor invocation. - * - * A SafeScript's string representation can safely be interpolated as the - * content of a script element within HTML. The SafeScript string should not be - * escaped before interpolation. - * - * Note that the SafeScript might contain text that is attacker-controlled but - * that text should have been interpolated with appropriate escaping, - * sanitization and/or validation into the right location in the script, such - * that it is highly constrained in its effect (for example, it had to match a - * set of whitelisted words). - * - * A SafeScript can be constructed via security-reviewed unchecked - * conversions. In this case producers of SafeScript must ensure themselves that - * the SafeScript does not contain unsafe script. Note in particular that - * {@code <} is dangerous, even when inside JavaScript strings, and so should - * always be forbidden or JavaScript escaped in user controlled input. For - * example, if {@code </script><script>evil</script>"} were - * interpolated inside a JavaScript string, it would break out of the context - * of the original script element and {@code evil} would execute. Also note - * that within an HTML script (raw text) element, HTML character references, - * such as "<" are not allowed. See - * http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements. - * - * @see goog.html.SafeScript#fromConstant - * @constructor - * @final - * @struct - * @implements {goog.string.TypedString} - */ -goog.html.SafeScript = function() { - /** - * The contained value of this SafeScript. The field has a purposely - * ugly name to make (non-compiled) code that attempts to directly access this - * field stand out. - * @private {string} - */ - this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = ''; - - /** - * A type marker used to implement additional run-time type checking. - * @see goog.html.SafeScript#unwrap - * @const - * @private - */ - this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = - goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; -}; - - -/** - * @override - * @const - */ -goog.html.SafeScript.prototype.implementsGoogStringTypedString = true; - - -/** - * Type marker for the SafeScript type, used to implement additional - * run-time type checking. - * @const - * @private - */ -goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; - - -/** - * Creates a SafeScript object from a compile-time constant string. - * - * @param {!goog.string.Const} script A compile-time-constant string from which - * to create a SafeScript. - * @return {!goog.html.SafeScript} A SafeScript object initialized to - * {@code script}. - */ -goog.html.SafeScript.fromConstant = function(script) { - var scriptString = goog.string.Const.unwrap(script); - if (scriptString.length === 0) { - return goog.html.SafeScript.EMPTY; - } - return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse( - scriptString); -}; - - -/** - * Returns this SafeScript's value as a string. - * - * IMPORTANT: In code where it is security relevant that an object's type is - * indeed {@code SafeScript}, use {@code goog.html.SafeScript.unwrap} instead of - * this method. If in doubt, assume that it's security relevant. In particular, - * note that goog.html functions which return a goog.html type do not guarantee - * the returned instance is of the right type. For example: - * - * <pre> - * var fakeSafeHtml = new String('fake'); - * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; - * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); - * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by - * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml - * // instanceof goog.html.SafeHtml. - * </pre> - * - * @see goog.html.SafeScript#unwrap - * @override - */ -goog.html.SafeScript.prototype.getTypedStringValue = function() { - return this.privateDoNotAccessOrElseSafeScriptWrappedValue_; -}; - - -if (goog.DEBUG) { - /** - * Returns a debug string-representation of this value. - * - * To obtain the actual string value wrapped in a SafeScript, use - * {@code goog.html.SafeScript.unwrap}. - * - * @see goog.html.SafeScript#unwrap - * @override - */ - goog.html.SafeScript.prototype.toString = function() { - return 'SafeScript{' + - this.privateDoNotAccessOrElseSafeScriptWrappedValue_ + '}'; - }; -} - - -/** - * Performs a runtime check that the provided object is indeed a - * SafeScript object, and returns its value. - * - * @param {!goog.html.SafeScript} safeScript The object to extract from. - * @return {string} The safeScript object's contained string, unless - * the run-time type check fails. In that case, {@code unwrap} returns an - * innocuous string, or, if assertions are enabled, throws - * {@code goog.asserts.AssertionError}. - */ -goog.html.SafeScript.unwrap = function(safeScript) { - // Perform additional Run-time type-checking to ensure that - // safeScript is indeed an instance of the expected type. This - // provides some additional protection against security bugs due to - // application code that disables type checks. - // Specifically, the following checks are performed: - // 1. The object is an instance of the expected type. - // 2. The object is not an instance of a subclass. - // 3. The object carries a type marker for the expected type. "Faking" an - // object requires a reference to the type marker, which has names intended - // to stand out in code reviews. - if (safeScript instanceof goog.html.SafeScript && - safeScript.constructor === goog.html.SafeScript && - safeScript.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === - goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { - return safeScript.privateDoNotAccessOrElseSafeScriptWrappedValue_; - } else { - goog.asserts.fail( - 'expected object of type SafeScript, got \'' + safeScript + '\''); - return 'type_error:SafeScript'; - } -}; - - -/** - * Package-internal utility method to create SafeScript instances. - * - * @param {string} script The string to initialize the SafeScript object with. - * @return {!goog.html.SafeScript} The initialized SafeScript object. - * @package - */ -goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse = - function(script) { - return new goog.html.SafeScript().initSecurityPrivateDoNotAccessOrElse_( - script); -}; - - -/** - * Called from createSafeScriptSecurityPrivateDoNotAccessOrElse(). This - * method exists only so that the compiler can dead code eliminate static - * fields (like EMPTY) when they're not accessed. - * @param {string} script - * @return {!goog.html.SafeScript} - * @private - */ -goog.html.SafeScript.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( - script) { - this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = script; - return this; -}; - - -/** - * A SafeScript instance corresponding to the empty string. - * @const {!goog.html.SafeScript} - */ -goog.html.SafeScript.EMPTY = - goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(''); diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safestyle.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safestyle.js deleted file mode 100644 index 2f9f288..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safestyle.js +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright 2014 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 SafeStyle type and its builders. - * - * TODO(user): Link to document stating type contract. - */ - -goog.provide('goog.html.SafeStyle'); - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.string'); -goog.require('goog.string.Const'); -goog.require('goog.string.TypedString'); - - - -/** - * A string-like object which represents a sequence of CSS declarations - * ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...}) - * and that carries the security type contract that its value, as a string, - * will not cause untrusted script execution (XSS) when evaluated as CSS in a - * browser. - * - * Instances of this type must be created via the factory methods - * ({@code goog.html.SafeStyle.create} or - * {@code goog.html.SafeStyle.fromConstant}) and not by invoking its - * constructor. The constructor intentionally takes no parameters and the type - * is immutable; hence only a default instance corresponding to the empty string - * can be obtained via constructor invocation. - * - * A SafeStyle's string representation ({@link #getSafeStyleString()}) can - * safely: - * <ul> - * <li>Be interpolated as the entire content of a *quoted* HTML style - * attribute, or before already existing properties. The SafeStyle string - * *must be HTML-attribute-escaped* (where " and ' are escaped) before - * interpolation. - * <li>Be interpolated as the entire content of a {}-wrapped block within a - * stylesheet, or before already existing properties. The SafeStyle string - * should not be escaped before interpolation. SafeStyle's contract also - * guarantees that the string will not be able to introduce new properties - * or elide existing ones. - * <li>Be assigned to the style property of a DOM node. The SafeStyle string - * should not be escaped before being assigned to the property. - * </ul> - * - * A SafeStyle may never contain literal angle brackets. Otherwise, it could - * be unsafe to place a SafeStyle into a <style> tag (where it can't - * be HTML escaped). For example, if the SafeStyle containing - * "{@code font: 'foo <style/><script>evil</script>'}" were - * interpolated within a <style> tag, this would then break out of the - * style context into HTML. - * - * A SafeStyle may contain literal single or double quotes, and as such the - * entire style string must be escaped when used in a style attribute (if - * this were not the case, the string could contain a matching quote that - * would escape from the style attribute). - * - * Values of this type must be composable, i.e. for any two values - * {@code style1} and {@code style2} of this type, - * {@code goog.html.SafeStyle.unwrap(style1) + - * goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies - * the SafeStyle type constraint. This requirement implies that for any value - * {@code style} of this type, {@code goog.html.SafeStyle.unwrap(style)} must - * not end in a "property value" or "property name" context. For example, - * a value of {@code background:url("} or {@code font-} would not satisfy the - * SafeStyle contract. This is because concatenating such strings with a - * second value that itself does not contain unsafe CSS can result in an - * overall string that does. For example, if {@code javascript:evil())"} is - * appended to {@code background:url("}, the resulting string may result in - * the execution of a malicious script. - * - * TODO(user): Consider whether we should implement UTF-8 interchange - * validity checks and blacklisting of newlines (including Unicode ones) and - * other whitespace characters (\t, \f). Document here if so and also update - * SafeStyle.fromConstant(). - * - * The following example values comply with this type's contract: - * <ul> - * <li><pre>width: 1em;</pre> - * <li><pre>height:1em;</pre> - * <li><pre>width: 1em;height: 1em;</pre> - * <li><pre>background:url('http://url');</pre> - * </ul> - * In addition, the empty string is safe for use in a CSS attribute. - * - * The following example values do NOT comply with this type's contract: - * <ul> - * <li><pre>background: red</pre> (missing a trailing semi-colon) - * <li><pre>background:</pre> (missing a value and a trailing semi-colon) - * <li><pre>1em</pre> (missing an attribute name, which provides context for - * the value) - * </ul> - * - * @see goog.html.SafeStyle#create - * @see goog.html.SafeStyle#fromConstant - * @see http://www.w3.org/TR/css3-syntax/ - * @constructor - * @final - * @struct - * @implements {goog.string.TypedString} - */ -goog.html.SafeStyle = function() { - /** - * The contained value of this SafeStyle. The field has a purposely - * ugly name to make (non-compiled) code that attempts to directly access this - * field stand out. - * @private {string} - */ - this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = ''; - - /** - * A type marker used to implement additional run-time type checking. - * @see goog.html.SafeStyle#unwrap - * @const - * @private - */ - this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = - goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; -}; - - -/** - * @override - * @const - */ -goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true; - - -/** - * Type marker for the SafeStyle type, used to implement additional - * run-time type checking. - * @const - * @private - */ -goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; - - -/** - * Creates a SafeStyle object from a compile-time constant string. - * - * {@code style} should be in the format - * {@code name: value; [name: value; ...]} and must not have any < or > - * characters in it. This is so that SafeStyle's contract is preserved, - * allowing the SafeStyle to correctly be interpreted as a sequence of CSS - * declarations and without affecting the syntactic structure of any - * surrounding CSS and HTML. - * - * This method performs basic sanity checks on the format of {@code style} - * but does not constrain the format of {@code name} and {@code value}, except - * for disallowing tag characters. - * - * @param {!goog.string.Const} style A compile-time-constant string from which - * to create a SafeStyle. - * @return {!goog.html.SafeStyle} A SafeStyle object initialized to - * {@code style}. - */ -goog.html.SafeStyle.fromConstant = function(style) { - var styleString = goog.string.Const.unwrap(style); - if (styleString.length === 0) { - return goog.html.SafeStyle.EMPTY; - } - goog.html.SafeStyle.checkStyle_(styleString); - goog.asserts.assert(goog.string.endsWith(styleString, ';'), - 'Last character of style string is not \';\': ' + styleString); - goog.asserts.assert(goog.string.contains(styleString, ':'), - 'Style string must contain at least one \':\', to ' + - 'specify a "name: value" pair: ' + styleString); - return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( - styleString); -}; - - -/** - * Checks if the style definition is valid. - * @param {string} style - * @private - */ -goog.html.SafeStyle.checkStyle_ = function(style) { - goog.asserts.assert(!/[<>]/.test(style), - 'Forbidden characters in style string: ' + style); -}; - - -/** - * Returns this SafeStyle's value as a string. - * - * IMPORTANT: In code where it is security relevant that an object's type is - * indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.unwrap} instead of - * this method. If in doubt, assume that it's security relevant. In particular, - * note that goog.html functions which return a goog.html type do not guarantee - * the returned instance is of the right type. For example: - * - * <pre> - * var fakeSafeHtml = new String('fake'); - * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; - * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); - * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by - * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml - * // instanceof goog.html.SafeHtml. - * </pre> - * - * @see goog.html.SafeStyle#unwrap - * @override - */ -goog.html.SafeStyle.prototype.getTypedStringValue = function() { - return this.privateDoNotAccessOrElseSafeStyleWrappedValue_; -}; - - -if (goog.DEBUG) { - /** - * Returns a debug string-representation of this value. - * - * To obtain the actual string value wrapped in a SafeStyle, use - * {@code goog.html.SafeStyle.unwrap}. - * - * @see goog.html.SafeStyle#unwrap - * @override - */ - goog.html.SafeStyle.prototype.toString = function() { - return 'SafeStyle{' + - this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + '}'; - }; -} - - -/** - * Performs a runtime check that the provided object is indeed a - * SafeStyle object, and returns its value. - * - * @param {!goog.html.SafeStyle} safeStyle The object to extract from. - * @return {string} The safeStyle object's contained string, unless - * the run-time type check fails. In that case, {@code unwrap} returns an - * innocuous string, or, if assertions are enabled, throws - * {@code goog.asserts.AssertionError}. - */ -goog.html.SafeStyle.unwrap = function(safeStyle) { - // Perform additional Run-time type-checking to ensure that - // safeStyle is indeed an instance of the expected type. This - // provides some additional protection against security bugs due to - // application code that disables type checks. - // Specifically, the following checks are performed: - // 1. The object is an instance of the expected type. - // 2. The object is not an instance of a subclass. - // 3. The object carries a type marker for the expected type. "Faking" an - // object requires a reference to the type marker, which has names intended - // to stand out in code reviews. - if (safeStyle instanceof goog.html.SafeStyle && - safeStyle.constructor === goog.html.SafeStyle && - safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === - goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { - return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_; - } else { - goog.asserts.fail( - 'expected object of type SafeStyle, got \'' + safeStyle + '\''); - return 'type_error:SafeStyle'; - } -}; - - -/** - * Package-internal utility method to create SafeStyle instances. - * - * @param {string} style The string to initialize the SafeStyle object with. - * @return {!goog.html.SafeStyle} The initialized SafeStyle object. - * @package - */ -goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse = - function(style) { - return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(style); -}; - - -/** - * Called from createSafeStyleSecurityPrivateDoNotAccessOrElse(). This - * method exists only so that the compiler can dead code eliminate static - * fields (like EMPTY) when they're not accessed. - * @param {string} style - * @return {!goog.html.SafeStyle} - * @private - */ -goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( - style) { - this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style; - return this; -}; - - -/** - * A SafeStyle instance corresponding to the empty string. - * @const {!goog.html.SafeStyle} - */ -goog.html.SafeStyle.EMPTY = - goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(''); - - -/** - * The innocuous string generated by goog.html.SafeUrl.create when passed - * an unsafe value. - * @const {string} - */ -goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez'; - - -/** - * Mapping of property names to their values. - * @typedef {!Object<string, goog.string.Const|string>} - */ -goog.html.SafeStyle.PropertyMap; - - -/** - * Creates a new SafeStyle object from the properties specified in the map. - * @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to - * their values, for example {'margin': '1px'}. Names must consist of - * [-_a-zA-Z0-9]. Values might be strings consisting of - * [-,.'"%_!# a-zA-Z0-9], where " and ' must be properly balanced. - * Other values must be wrapped in goog.string.Const. Null value causes - * skipping the property. - * @return {!goog.html.SafeStyle} - * @throws {Error} If invalid name is provided. - * @throws {goog.asserts.AssertionError} If invalid value is provided. With - * disabled assertions, invalid value is replaced by - * goog.html.SafeStyle.INNOCUOUS_STRING. - */ -goog.html.SafeStyle.create = function(map) { - var style = ''; - for (var name in map) { - if (!/^[-_a-zA-Z0-9]+$/.test(name)) { - throw Error('Name allows only [-_a-zA-Z0-9], got: ' + name); - } - var value = map[name]; - if (value == null) { - continue; - } - if (value instanceof goog.string.Const) { - value = goog.string.Const.unwrap(value); - // These characters can be used to change context and we don't want that - // even with const values. - goog.asserts.assert(!/[{;}]/.test(value), 'Value does not allow [{;}].'); - } else if (!goog.html.SafeStyle.VALUE_RE_.test(value)) { - goog.asserts.fail( - 'String value allows only [-,."\'%_!# a-zA-Z0-9], got: ' + value); - value = goog.html.SafeStyle.INNOCUOUS_STRING; - } else if (!goog.html.SafeStyle.hasBalancedQuotes_(value)) { - goog.asserts.fail('String value requires balanced quotes, got: ' + value); - value = goog.html.SafeStyle.INNOCUOUS_STRING; - } - style += name + ':' + value + ';'; - } - if (!style) { - return goog.html.SafeStyle.EMPTY; - } - goog.html.SafeStyle.checkStyle_(style); - return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( - style); -}; - - -/** - * Checks that quotes (" and ') are properly balanced inside a string. Assumes - * that neither escape (\) nor any other character that could result in - * breaking out of a string parsing context are allowed; - * see http://www.w3.org/TR/css3-syntax/#string-token-diagram. - * @param {string} value Untrusted CSS property value. - * @return {boolean} True if property value is safe with respect to quote - * balancedness. - * @private - */ -goog.html.SafeStyle.hasBalancedQuotes_ = function(value) { - var outsideSingle = true; - var outsideDouble = true; - for (var i = 0; i < value.length; i++) { - var c = value.charAt(i); - if (c == "'" && outsideDouble) { - outsideSingle = !outsideSingle; - } else if (c == '"' && outsideSingle) { - outsideDouble = !outsideDouble; - } - } - return outsideSingle && outsideDouble; -}; - - -// Keep in sync with the error string in create(). -/** - * Regular expression for safe values. - * - * Quotes (" and ') are allowed, but a check must be done elsewhere to ensure - * they're balanced. - * - * ',' allows multiple values to be assigned to the same property - * (e.g. background-attachment or font-family) and hence could allow - * multiple values to get injected, but that should pose no risk of XSS. - * @const {!RegExp} - * @private - */ -goog.html.SafeStyle.VALUE_RE_ = /^[-,."'%_!# a-zA-Z0-9]+$/; - - -/** - * Creates a new SafeStyle object by concatenating the values. - * @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args - * SafeStyles to concatenate. - * @return {!goog.html.SafeStyle} - */ -goog.html.SafeStyle.concat = function(var_args) { - var style = ''; - - /** - * @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument - */ - var addArgument = function(argument) { - if (goog.isArray(argument)) { - goog.array.forEach(argument, addArgument); - } else { - style += goog.html.SafeStyle.unwrap(argument); - } - }; - - goog.array.forEach(arguments, addArgument); - if (!style) { - return goog.html.SafeStyle.EMPTY; - } - return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( - style); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safestylesheet.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safestylesheet.js deleted file mode 100644 index 79e8b51..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safestylesheet.js +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2014 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 SafeStyleSheet type and its builders. - * - * TODO(user): Link to document stating type contract. - */ - -goog.provide('goog.html.SafeStyleSheet'); - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.string'); -goog.require('goog.string.Const'); -goog.require('goog.string.TypedString'); - - - -/** - * A string-like object which represents a CSS style sheet and that carries the - * security type contract that its value, as a string, will not cause untrusted - * script execution (XSS) when evaluated as CSS in a browser. - * - * Instances of this type must be created via the factory method - * {@code goog.html.SafeStyleSheet.fromConstant} and not by invoking its - * constructor. The constructor intentionally takes no parameters and the type - * is immutable; hence only a default instance corresponding to the empty string - * can be obtained via constructor invocation. - * - * A SafeStyleSheet's string representation can safely be interpolated as the - * content of a style element within HTML. The SafeStyleSheet string should - * not be escaped before interpolation. - * - * Values of this type must be composable, i.e. for any two values - * {@code styleSheet1} and {@code styleSheet2} of this type, - * {@code goog.html.SafeStyleSheet.unwrap(styleSheet1) + - * goog.html.SafeStyleSheet.unwrap(styleSheet2)} must itself be a value that - * satisfies the SafeStyleSheet type constraint. This requirement implies that - * for any value {@code styleSheet} of this type, - * {@code goog.html.SafeStyleSheet.unwrap(styleSheet1)} must end in - * "beginning of rule" context. - - * A SafeStyleSheet can be constructed via security-reviewed unchecked - * conversions. In this case producers of SafeStyleSheet must ensure themselves - * that the SafeStyleSheet does not contain unsafe script. Note in particular - * that {@code <} is dangerous, even when inside CSS strings, and so should - * always be forbidden or CSS-escaped in user controlled input. For example, if - * {@code </style><script>evil</script>"} were interpolated - * inside a CSS string, it would break out of the context of the original - * style element and {@code evil} would execute. Also note that within an HTML - * style (raw text) element, HTML character references, such as - * {@code &lt;}, are not allowed. See - * http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements - * (similar considerations apply to the style element). - * - * @see goog.html.SafeStyleSheet#fromConstant - * @constructor - * @final - * @struct - * @implements {goog.string.TypedString} - */ -goog.html.SafeStyleSheet = function() { - /** - * The contained value of this SafeStyleSheet. The field has a purposely - * ugly name to make (non-compiled) code that attempts to directly access this - * field stand out. - * @private {string} - */ - this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = ''; - - /** - * A type marker used to implement additional run-time type checking. - * @see goog.html.SafeStyleSheet#unwrap - * @const - * @private - */ - this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = - goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; -}; - - -/** - * @override - * @const - */ -goog.html.SafeStyleSheet.prototype.implementsGoogStringTypedString = true; - - -/** - * Type marker for the SafeStyleSheet type, used to implement additional - * run-time type checking. - * @const - * @private - */ -goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; - - -/** - * Creates a new SafeStyleSheet object by concatenating values. - * @param {...(!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>)} - * var_args Values to concatenate. - * @return {!goog.html.SafeStyleSheet} - */ -goog.html.SafeStyleSheet.concat = function(var_args) { - var result = ''; - - /** - * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>} - * argument - */ - var addArgument = function(argument) { - if (goog.isArray(argument)) { - goog.array.forEach(argument, addArgument); - } else { - result += goog.html.SafeStyleSheet.unwrap(argument); - } - }; - - goog.array.forEach(arguments, addArgument); - return goog.html.SafeStyleSheet - .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(result); -}; - - -/** - * Creates a SafeStyleSheet object from a compile-time constant string. - * - * {@code styleSheet} must not have any < characters in it, so that - * the syntactic structure of the surrounding HTML is not affected. - * - * @param {!goog.string.Const} styleSheet A compile-time-constant string from - * which to create a SafeStyleSheet. - * @return {!goog.html.SafeStyleSheet} A SafeStyleSheet object initialized to - * {@code styleSheet}. - */ -goog.html.SafeStyleSheet.fromConstant = function(styleSheet) { - var styleSheetString = goog.string.Const.unwrap(styleSheet); - if (styleSheetString.length === 0) { - return goog.html.SafeStyleSheet.EMPTY; - } - // > is a valid character in CSS selectors and there's no strict need to - // block it if we already block <. - goog.asserts.assert(!goog.string.contains(styleSheetString, '<'), - "Forbidden '<' character in style sheet string: " + styleSheetString); - return goog.html.SafeStyleSheet. - createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheetString); -}; - - -/** - * Returns this SafeStyleSheet's value as a string. - * - * IMPORTANT: In code where it is security relevant that an object's type is - * indeed {@code SafeStyleSheet}, use {@code goog.html.SafeStyleSheet.unwrap} - * instead of this method. If in doubt, assume that it's security relevant. In - * particular, note that goog.html functions which return a goog.html type do - * not guarantee the returned instance is of the right type. For example: - * - * <pre> - * var fakeSafeHtml = new String('fake'); - * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; - * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); - * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by - * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml - * // instanceof goog.html.SafeHtml. - * </pre> - * - * @see goog.html.SafeStyleSheet#unwrap - * @override - */ -goog.html.SafeStyleSheet.prototype.getTypedStringValue = function() { - return this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_; -}; - - -if (goog.DEBUG) { - /** - * Returns a debug string-representation of this value. - * - * To obtain the actual string value wrapped in a SafeStyleSheet, use - * {@code goog.html.SafeStyleSheet.unwrap}. - * - * @see goog.html.SafeStyleSheet#unwrap - * @override - */ - goog.html.SafeStyleSheet.prototype.toString = function() { - return 'SafeStyleSheet{' + - this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ + '}'; - }; -} - - -/** - * Performs a runtime check that the provided object is indeed a - * SafeStyleSheet object, and returns its value. - * - * @param {!goog.html.SafeStyleSheet} safeStyleSheet The object to extract from. - * @return {string} The safeStyleSheet object's contained string, unless - * the run-time type check fails. In that case, {@code unwrap} returns an - * innocuous string, or, if assertions are enabled, throws - * {@code goog.asserts.AssertionError}. - */ -goog.html.SafeStyleSheet.unwrap = function(safeStyleSheet) { - // Perform additional Run-time type-checking to ensure that - // safeStyleSheet is indeed an instance of the expected type. This - // provides some additional protection against security bugs due to - // application code that disables type checks. - // Specifically, the following checks are performed: - // 1. The object is an instance of the expected type. - // 2. The object is not an instance of a subclass. - // 3. The object carries a type marker for the expected type. "Faking" an - // object requires a reference to the type marker, which has names intended - // to stand out in code reviews. - if (safeStyleSheet instanceof goog.html.SafeStyleSheet && - safeStyleSheet.constructor === goog.html.SafeStyleSheet && - safeStyleSheet.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === - goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { - return safeStyleSheet.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_; - } else { - goog.asserts.fail( - "expected object of type SafeStyleSheet, got '" + safeStyleSheet + - "'"); - return 'type_error:SafeStyleSheet'; - } -}; - - -/** - * Package-internal utility method to create SafeStyleSheet instances. - * - * @param {string} styleSheet The string to initialize the SafeStyleSheet - * object with. - * @return {!goog.html.SafeStyleSheet} The initialized SafeStyleSheet object. - * @package - */ -goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse = - function(styleSheet) { - return new goog.html.SafeStyleSheet().initSecurityPrivateDoNotAccessOrElse_( - styleSheet); -}; - - -/** - * Called from createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(). This - * method exists only so that the compiler can dead code eliminate static - * fields (like EMPTY) when they're not accessed. - * @param {string} styleSheet - * @return {!goog.html.SafeStyleSheet} - * @private - */ -goog.html.SafeStyleSheet.prototype.initSecurityPrivateDoNotAccessOrElse_ = - function(styleSheet) { - this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = styleSheet; - return this; -}; - - -/** - * A SafeStyleSheet instance corresponding to the empty string. - * @const {!goog.html.SafeStyleSheet} - */ -goog.html.SafeStyleSheet.EMPTY = - goog.html.SafeStyleSheet. - createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(''); diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safeurl.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safeurl.js deleted file mode 100644 index 6d2f871..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/safeurl.js +++ /dev/null @@ -1,431 +0,0 @@ -// 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 The SafeUrl type and its builders. - * - * TODO(user): Link to document stating type contract. - */ - -goog.provide('goog.html.SafeUrl'); - -goog.require('goog.asserts'); -goog.require('goog.fs.url'); -goog.require('goog.i18n.bidi.Dir'); -goog.require('goog.i18n.bidi.DirectionalString'); -goog.require('goog.string.Const'); -goog.require('goog.string.TypedString'); - - - -/** - * A string that is safe to use in URL context in DOM APIs and HTML documents. - * - * A SafeUrl is a string-like object that carries the security type contract - * that its value as a string will not cause untrusted script execution - * when evaluated as a hyperlink URL in a browser. - * - * Values of this type are guaranteed to be safe to use in URL/hyperlink - * contexts, such as, assignment to URL-valued DOM properties, or - * interpolation into a HTML template in URL context (e.g., inside a href - * attribute), in the sense that the use will not result in a - * Cross-Site-Scripting vulnerability. - * - * Note that, as documented in {@code goog.html.SafeUrl.unwrap}, this type's - * contract does not guarantee that instances are safe to interpolate into HTML - * without appropriate escaping. - * - * Note also that this type's contract does not imply any guarantees regarding - * the resource the URL refers to. In particular, SafeUrls are <b>not</b> - * safe to use in a context where the referred-to resource is interpreted as - * trusted code, e.g., as the src of a script tag. - * - * Instances of this type must be created via the factory methods - * ({@code goog.html.SafeUrl.fromConstant}, {@code goog.html.SafeUrl.sanitize}), - * etc and not by invoking its constructor. The constructor intentionally - * takes no parameters and the type is immutable; hence only a default instance - * corresponding to the empty string can be obtained via constructor invocation. - * - * @see goog.html.SafeUrl#fromConstant - * @see goog.html.SafeUrl#from - * @see goog.html.SafeUrl#sanitize - * @constructor - * @final - * @struct - * @implements {goog.i18n.bidi.DirectionalString} - * @implements {goog.string.TypedString} - */ -goog.html.SafeUrl = function() { - /** - * The contained value of this SafeUrl. The field has a purposely ugly - * name to make (non-compiled) code that attempts to directly access this - * field stand out. - * @private {string} - */ - this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = ''; - - /** - * A type marker used to implement additional run-time type checking. - * @see goog.html.SafeUrl#unwrap - * @const - * @private - */ - this.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = - goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; -}; - - -/** - * The innocuous string generated by goog.html.SafeUrl.sanitize when passed - * an unsafe URL. - * - * about:invalid is registered in - * http://www.w3.org/TR/css3-values/#about-invalid. - * http://tools.ietf.org/html/rfc6694#section-2.2.1 permits about URLs to - * contain a fragment, which is not to be considered when determining if an - * about URL is well-known. - * - * Using about:invalid seems preferable to using a fixed data URL, since - * browsers might choose to not report CSP violations on it, as legitimate - * CSS function calls to attr() can result in this URL being produced. It is - * also a standard URL which matches exactly the semantics we need: - * "The about:invalid URI references a non-existent document with a generic - * error condition. It can be used when a URI is necessary, but the default - * value shouldn't be resolveable as any type of document". - * - * @const {string} - */ -goog.html.SafeUrl.INNOCUOUS_STRING = 'about:invalid#zClosurez'; - - -/** - * @override - * @const - */ -goog.html.SafeUrl.prototype.implementsGoogStringTypedString = true; - - -/** - * Returns this SafeUrl's value a string. - * - * IMPORTANT: In code where it is security relevant that an object's type is - * indeed {@code SafeUrl}, use {@code goog.html.SafeUrl.unwrap} instead of this - * method. If in doubt, assume that it's security relevant. In particular, note - * that goog.html functions which return a goog.html type do not guarantee that - * the returned instance is of the right type. For example: - * - * <pre> - * var fakeSafeHtml = new String('fake'); - * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; - * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); - * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by - * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof - * // goog.html.SafeHtml. - * </pre> - * - * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the - * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST - * be appropriately escaped before embedding in a HTML document. Note that the - * required escaping is context-sensitive (e.g. a different escaping is - * required for embedding a URL in a style property within a style - * attribute, as opposed to embedding in a href attribute). - * - * @see goog.html.SafeUrl#unwrap - * @override - */ -goog.html.SafeUrl.prototype.getTypedStringValue = function() { - return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_; -}; - - -/** - * @override - * @const - */ -goog.html.SafeUrl.prototype.implementsGoogI18nBidiDirectionalString = true; - - -/** - * Returns this URLs directionality, which is always {@code LTR}. - * @override - */ -goog.html.SafeUrl.prototype.getDirection = function() { - return goog.i18n.bidi.Dir.LTR; -}; - - -if (goog.DEBUG) { - /** - * Returns a debug string-representation of this value. - * - * To obtain the actual string value wrapped in a SafeUrl, use - * {@code goog.html.SafeUrl.unwrap}. - * - * @see goog.html.SafeUrl#unwrap - * @override - */ - goog.html.SafeUrl.prototype.toString = function() { - return 'SafeUrl{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ + - '}'; - }; -} - - -/** - * Performs a runtime check that the provided object is indeed a SafeUrl - * object, and returns its value. - * - * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the - * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST - * be appropriately escaped before embedding in a HTML document. Note that the - * required escaping is context-sensitive (e.g. a different escaping is - * required for embedding a URL in a style property within a style - * attribute, as opposed to embedding in a href attribute). - * - * Note that the returned value does not necessarily correspond to the string - * with which the SafeUrl was constructed, since goog.html.SafeUrl.sanitize - * will percent-encode many characters. - * - * @param {!goog.html.SafeUrl} safeUrl The object to extract from. - * @return {string} The SafeUrl object's contained string, unless the run-time - * type check fails. In that case, {@code unwrap} returns an innocuous - * string, or, if assertions are enabled, throws - * {@code goog.asserts.AssertionError}. - */ -goog.html.SafeUrl.unwrap = function(safeUrl) { - // Perform additional Run-time type-checking to ensure that safeUrl is indeed - // an instance of the expected type. This provides some additional protection - // against security bugs due to application code that disables type checks. - // Specifically, the following checks are performed: - // 1. The object is an instance of the expected type. - // 2. The object is not an instance of a subclass. - // 3. The object carries a type marker for the expected type. "Faking" an - // object requires a reference to the type marker, which has names intended - // to stand out in code reviews. - if (safeUrl instanceof goog.html.SafeUrl && - safeUrl.constructor === goog.html.SafeUrl && - safeUrl.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === - goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { - return safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_; - } else { - goog.asserts.fail('expected object of type SafeUrl, got \'' + - safeUrl + '\''); - return 'type_error:SafeUrl'; - - } -}; - - -/** - * Creates a SafeUrl object from a compile-time constant string. - * - * Compile-time constant strings are inherently program-controlled and hence - * trusted. - * - * @param {!goog.string.Const} url A compile-time-constant string from which to - * create a SafeUrl. - * @return {!goog.html.SafeUrl} A SafeUrl object initialized to {@code url}. - */ -goog.html.SafeUrl.fromConstant = function(url) { - return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse( - goog.string.Const.unwrap(url)); -}; - - -/** - * A pattern that matches Blob types that can have SafeUrls created from - * URL.createObjectURL(blob). Only matches image types, currently. - * @const - * @private - */ -goog.html.SAFE_BLOB_TYPE_PATTERN_ = - /^image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)$/i; - - -/** - * Creates a SafeUrl wrapping a blob URL for the given {@code blob}. The - * blob URL is created with {@code URL.createObjectURL}. If the MIME type - * for {@code blob} is not of a known safe image MIME type, then the - * SafeUrl will wrap {@link #INNOCUOUS_STRING}. - * @see http://www.w3.org/TR/FileAPI/#url - * @param {!Blob} blob - * @return {!goog.html.SafeUrl} The blob URL, or an innocuous string wrapped - * as a SafeUrl. - */ -goog.html.SafeUrl.fromBlob = function(blob) { - var url = goog.html.SAFE_BLOB_TYPE_PATTERN_.test(blob.type) ? - goog.fs.url.createObjectUrl(blob) : goog.html.SafeUrl.INNOCUOUS_STRING; - return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); -}; - - -/** - * A pattern that recognizes a commonly useful subset of URLs that satisfy - * the SafeUrl contract. - * - * This regular expression matches a subset of URLs that will not cause script - * execution if used in URL context within a HTML document. Specifically, this - * regular expression matches if (comment from here on and regex copied from - * Soy's EscapingConventions): - * (1) Either a protocol in a whitelist (http, https, mailto or ftp). - * (2) or no protocol. A protocol must be followed by a colon. The below - * allows that by allowing colons only after one of the characters [/?#]. - * A colon after a hash (#) must be in the fragment. - * Otherwise, a colon after a (?) must be in a query. - * Otherwise, a colon after a single solidus (/) must be in a path. - * Otherwise, a colon after a double solidus (//) must be in the authority - * (before port). - * - * The pattern disallows &, used in HTML entity declarations before - * one of the characters in [/?#]. This disallows HTML entities used in the - * protocol name, which should never happen, e.g. "http" for "http". - * It also disallows HTML entities in the first path part of a relative path, - * e.g. "foo<bar/baz". Our existing escaping functions should not produce - * that. More importantly, it disallows masking of a colon, - * e.g. "javascript:...". - * - * @private - * @const {!RegExp} - */ -goog.html.SAFE_URL_PATTERN_ = - /^(?:(?:https?|mailto|ftp):|[^&:/?#]*(?:[/?#]|$))/i; - - -/** - * Creates a SafeUrl object from {@code url}. If {@code url} is a - * goog.html.SafeUrl then it is simply returned. Otherwise the input string is - * validated to match a pattern of commonly used safe URLs. The string is - * converted to UTF-8 and non-whitelisted characters are percent-encoded. The - * string wrapped by the created SafeUrl will thus contain only ASCII printable - * characters. - * - * {@code url} may be a URL with the http, https, mailto or ftp scheme, - * or a relative URL (i.e., a URL without a scheme; specifically, a - * scheme-relative, absolute-path-relative, or path-relative URL). - * - * {@code url} is converted to UTF-8 and non-whitelisted characters are - * percent-encoded. Whitelisted characters are '%' and, from RFC 3986, - * unreserved characters and reserved characters, with the exception of '\'', - * '(' and ')'. This ensures the the SafeUrl contains only ASCII-printable - * characters and reduces the chance of security bugs were it to be - * interpolated into a specific context without the necessary escaping. - * - * If {@code url} fails validation or does not UTF-16 decode correctly - * (JavaScript strings are UTF-16 encoded), this function returns a SafeUrl - * object containing an innocuous string, goog.html.SafeUrl.INNOCUOUS_STRING. - * - * @see http://url.spec.whatwg.org/#concept-relative-url - * @param {string|!goog.string.TypedString} url The URL to validate. - * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl. - */ -goog.html.SafeUrl.sanitize = function(url) { - if (url instanceof goog.html.SafeUrl) { - return url; - } - else if (url.implementsGoogStringTypedString) { - url = url.getTypedStringValue(); - } else { - url = String(url); - } - if (!goog.html.SAFE_URL_PATTERN_.test(url)) { - url = goog.html.SafeUrl.INNOCUOUS_STRING; - } else { - url = goog.html.SafeUrl.normalize_(url); - } - return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); -}; - - -/** - * Normalizes {@code url} the UTF-8 encoding of url, using a whitelist of - * characters. Whitelisted characters are not percent-encoded. - * @param {string} url The URL to normalize. - * @return {string} The normalized URL. - * @private - */ -goog.html.SafeUrl.normalize_ = function(url) { - try { - var normalized = encodeURI(url); - } catch (e) { // Happens if url contains invalid surrogate sequences. - return goog.html.SafeUrl.INNOCUOUS_STRING; - } - - return normalized.replace( - goog.html.SafeUrl.NORMALIZE_MATCHER_, - function(match) { - return goog.html.SafeUrl.NORMALIZE_REPLACER_MAP_[match]; - }); -}; - - -/** - * Matches characters and strings which need to be replaced in the string - * generated by encodeURI. Specifically: - * - * - '\'', '(' and ')' are not encoded. They are part of the reserved - * characters group in RFC 3986 but only appear in the obsolete mark - * production in Appendix D.2 of RFC 3986, so they can be encoded without - * changing semantics. - * - '[' and ']' are encoded by encodeURI, despite being reserved characters - * which can be used to represent IPv6 addresses. So they need to be decoded. - * - '%' is encoded by encodeURI. However, encoding '%' characters that are - * already part of a valid percent-encoded sequence changes the semantics of a - * URL, and hence we need to preserve them. Note that this may allow - * non-encoded '%' characters to remain in the URL (i.e., occurrences of '%' - * that are not part of a valid percent-encoded sequence, for example, - * 'ab%xy'). - * - * @const {!RegExp} - * @private - */ -goog.html.SafeUrl.NORMALIZE_MATCHER_ = /[()']|%5B|%5D|%25/g; - - -/** - * Map of replacements to be done in string generated by encodeURI. - * @const {!Object<string, string>} - * @private - */ -goog.html.SafeUrl.NORMALIZE_REPLACER_MAP_ = { - '\'': '%27', - '(': '%28', - ')': '%29', - '%5B': '[', - '%5D': ']', - '%25': '%' -}; - - -/** - * Type marker for the SafeUrl type, used to implement additional run-time - * type checking. - * @const - * @private - */ -goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; - - -/** - * Package-internal utility method to create SafeUrl instances. - * - * @param {string} url The string to initialize the SafeUrl object with. - * @return {!goog.html.SafeUrl} The initialized SafeUrl object. - * @package - */ -goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse = function( - url) { - var safeUrl = new goog.html.SafeUrl(); - safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = url; - return safeUrl; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/trustedresourceurl.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/trustedresourceurl.js deleted file mode 100644 index e7c7bf5..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/trustedresourceurl.js +++ /dev/null @@ -1,224 +0,0 @@ -// 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 The TrustedResourceUrl type and its builders. - * - * TODO(user): Link to document stating type contract. - */ - -goog.provide('goog.html.TrustedResourceUrl'); - -goog.require('goog.asserts'); -goog.require('goog.i18n.bidi.Dir'); -goog.require('goog.i18n.bidi.DirectionalString'); -goog.require('goog.string.Const'); -goog.require('goog.string.TypedString'); - - - -/** - * A URL which is under application control and from which script, CSS, and - * other resources that represent executable code, can be fetched. - * - * Given that the URL can only be constructed from strings under application - * control and is used to load resources, bugs resulting in a malformed URL - * should not have a security impact and are likely to be easily detectable - * during testing. Given the wide number of non-RFC compliant URLs in use, - * stricter validation could prevent some applications from being able to use - * this type. - * - * Instances of this type must be created via the factory method, - * ({@code goog.html.TrustedResourceUrl.fromConstant}), and not by invoking its - * constructor. The constructor intentionally takes no parameters and the type - * is immutable; hence only a default instance corresponding to the empty - * string can be obtained via constructor invocation. - * - * @see goog.html.TrustedResourceUrl#fromConstant - * @constructor - * @final - * @struct - * @implements {goog.i18n.bidi.DirectionalString} - * @implements {goog.string.TypedString} - */ -goog.html.TrustedResourceUrl = function() { - /** - * The contained value of this TrustedResourceUrl. The field has a purposely - * ugly name to make (non-compiled) code that attempts to directly access this - * field stand out. - * @private {string} - */ - this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = ''; - - /** - * A type marker used to implement additional run-time type checking. - * @see goog.html.TrustedResourceUrl#unwrap - * @const - * @private - */ - this.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = - goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; -}; - - -/** - * @override - * @const - */ -goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true; - - -/** - * Returns this TrustedResourceUrl's value as a string. - * - * IMPORTANT: In code where it is security relevant that an object's type is - * indeed {@code TrustedResourceUrl}, use - * {@code goog.html.TrustedResourceUrl.unwrap} instead of this method. If in - * doubt, assume that it's security relevant. In particular, note that - * goog.html functions which return a goog.html type do not guarantee that - * the returned instance is of the right type. For example: - * - * <pre> - * var fakeSafeHtml = new String('fake'); - * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; - * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); - * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by - * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof - * // goog.html.SafeHtml. - * </pre> - * - * @see goog.html.TrustedResourceUrl#unwrap - * @override - */ -goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() { - return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_; -}; - - -/** - * @override - * @const - */ -goog.html.TrustedResourceUrl.prototype.implementsGoogI18nBidiDirectionalString = - true; - - -/** - * Returns this URLs directionality, which is always {@code LTR}. - * @override - */ -goog.html.TrustedResourceUrl.prototype.getDirection = function() { - return goog.i18n.bidi.Dir.LTR; -}; - - -if (goog.DEBUG) { - /** - * Returns a debug string-representation of this value. - * - * To obtain the actual string value wrapped in a TrustedResourceUrl, use - * {@code goog.html.TrustedResourceUrl.unwrap}. - * - * @see goog.html.TrustedResourceUrl#unwrap - * @override - */ - goog.html.TrustedResourceUrl.prototype.toString = function() { - return 'TrustedResourceUrl{' + - this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '}'; - }; -} - - -/** - * Performs a runtime check that the provided object is indeed a - * TrustedResourceUrl object, and returns its value. - * - * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to - * extract from. - * @return {string} The trustedResourceUrl object's contained string, unless - * the run-time type check fails. In that case, {@code unwrap} returns an - * innocuous string, or, if assertions are enabled, throws - * {@code goog.asserts.AssertionError}. - */ -goog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) { - // Perform additional Run-time type-checking to ensure that - // trustedResourceUrl is indeed an instance of the expected type. This - // provides some additional protection against security bugs due to - // application code that disables type checks. - // Specifically, the following checks are performed: - // 1. The object is an instance of the expected type. - // 2. The object is not an instance of a subclass. - // 3. The object carries a type marker for the expected type. "Faking" an - // object requires a reference to the type marker, which has names intended - // to stand out in code reviews. - if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl && - trustedResourceUrl.constructor === goog.html.TrustedResourceUrl && - trustedResourceUrl - .TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === - goog.html.TrustedResourceUrl - .TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { - return trustedResourceUrl - .privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_; - } else { - goog.asserts.fail('expected object of type TrustedResourceUrl, got \'' + - trustedResourceUrl + '\''); - return 'type_error:TrustedResourceUrl'; - - } -}; - - -/** - * Creates a TrustedResourceUrl object from a compile-time constant string. - * - * Compile-time constant strings are inherently program-controlled and hence - * trusted. - * - * @param {!goog.string.Const} url A compile-time-constant string from which to - * create a TrustedResourceUrl. - * @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object - * initialized to {@code url}. - */ -goog.html.TrustedResourceUrl.fromConstant = function(url) { - return goog.html.TrustedResourceUrl - .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse( - goog.string.Const.unwrap(url)); -}; - - -/** - * Type marker for the TrustedResourceUrl type, used to implement additional - * run-time type checking. - * @const - * @private - */ -goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; - - -/** - * Package-internal utility method to create TrustedResourceUrl instances. - * - * @param {string} url The string to initialize the TrustedResourceUrl object - * with. - * @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl - * object. - * @package - */ -goog.html.TrustedResourceUrl. - createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) { - var trustedResourceUrl = new goog.html.TrustedResourceUrl(); - trustedResourceUrl.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = - url; - return trustedResourceUrl; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/uncheckedconversions.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/uncheckedconversions.js deleted file mode 100644 index a1a5a9a..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/html/uncheckedconversions.js +++ /dev/null @@ -1,231 +0,0 @@ -// 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 Unchecked conversions to create values of goog.html types from - * plain strings. Use of these functions could potentially result in instances - * of goog.html types that violate their type contracts, and hence result in - * security vulnerabilties. - * - * Therefore, all uses of the methods herein must be carefully security - * reviewed. Avoid use of the methods in this file whenever possible; instead - * prefer to create instances of goog.html types using inherently safe builders - * or template systems. - * - * - * @visibility {//closure/goog/html:approved_for_unchecked_conversion} - * @visibility {//closure/goog/bin/sizetests:__pkg__} - */ - - -goog.provide('goog.html.uncheckedconversions'); - -goog.require('goog.asserts'); -goog.require('goog.html.SafeHtml'); -goog.require('goog.html.SafeScript'); -goog.require('goog.html.SafeStyle'); -goog.require('goog.html.SafeStyleSheet'); -goog.require('goog.html.SafeUrl'); -goog.require('goog.html.TrustedResourceUrl'); -goog.require('goog.string'); -goog.require('goog.string.Const'); - - -/** - * Performs an "unchecked conversion" to SafeHtml from a plain string that is - * known to satisfy the SafeHtml type contract. - * - * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure - * that the value of {@code html} satisfies the SafeHtml type contract in all - * possible program states. - * - * - * @param {!goog.string.Const} justification A constant string explaining why - * this use of this method is safe. May include a security review ticket - * number. - * @param {string} html A string that is claimed to adhere to the SafeHtml - * contract. - * @param {?goog.i18n.bidi.Dir=} opt_dir The optional directionality of the - * SafeHtml to be constructed. A null or undefined value signifies an - * unknown directionality. - * @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml - * object. - * @suppress {visibility} For access to SafeHtml.create... Note that this - * use is appropriate since this method is intended to be "package private" - * withing goog.html. DO NOT call SafeHtml.create... from outside this - * package; use appropriate wrappers instead. - */ -goog.html.uncheckedconversions.safeHtmlFromStringKnownToSatisfyTypeContract = - function(justification, html, opt_dir) { - // unwrap() called inside an assert so that justification can be optimized - // away in production code. - goog.asserts.assertString(goog.string.Const.unwrap(justification), - 'must provide justification'); - goog.asserts.assert( - !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), - 'must provide non-empty justification'); - return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( - html, opt_dir || null); -}; - - -/** - * Performs an "unchecked conversion" to SafeScript from a plain string that is - * known to satisfy the SafeScript type contract. - * - * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure - * that the value of {@code script} satisfies the SafeScript type contract in - * all possible program states. - * - * - * @param {!goog.string.Const} justification A constant string explaining why - * this use of this method is safe. May include a security review ticket - * number. - * @param {string} script The string to wrap as a SafeScript. - * @return {!goog.html.SafeScript} The value of {@code script}, wrapped in a - * SafeScript object. - */ -goog.html.uncheckedconversions.safeScriptFromStringKnownToSatisfyTypeContract = - function(justification, script) { - // unwrap() called inside an assert so that justification can be optimized - // away in production code. - goog.asserts.assertString(goog.string.Const.unwrap(justification), - 'must provide justification'); - goog.asserts.assert( - !goog.string.isEmpty(goog.string.Const.unwrap(justification)), - 'must provide non-empty justification'); - return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse( - script); -}; - - -/** - * Performs an "unchecked conversion" to SafeStyle from a plain string that is - * known to satisfy the SafeStyle type contract. - * - * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure - * that the value of {@code style} satisfies the SafeUrl type contract in all - * possible program states. - * - * - * @param {!goog.string.Const} justification A constant string explaining why - * this use of this method is safe. May include a security review ticket - * number. - * @param {string} style The string to wrap as a SafeStyle. - * @return {!goog.html.SafeStyle} The value of {@code style}, wrapped in a - * SafeStyle object. - */ -goog.html.uncheckedconversions.safeStyleFromStringKnownToSatisfyTypeContract = - function(justification, style) { - // unwrap() called inside an assert so that justification can be optimized - // away in production code. - goog.asserts.assertString(goog.string.Const.unwrap(justification), - 'must provide justification'); - goog.asserts.assert( - !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), - 'must provide non-empty justification'); - return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( - style); -}; - - -/** - * Performs an "unchecked conversion" to SafeStyleSheet from a plain string - * that is known to satisfy the SafeStyleSheet type contract. - * - * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure - * that the value of {@code styleSheet} satisfies the SafeUrl type contract in - * all possible program states. - * - * - * @param {!goog.string.Const} justification A constant string explaining why - * this use of this method is safe. May include a security review ticket - * number. - * @param {string} styleSheet The string to wrap as a SafeStyleSheet. - * @return {!goog.html.SafeStyleSheet} The value of {@code styleSheet}, wrapped - * in a SafeStyleSheet object. - */ -goog.html.uncheckedconversions. - safeStyleSheetFromStringKnownToSatisfyTypeContract = - function(justification, styleSheet) { - // unwrap() called inside an assert so that justification can be optimized - // away in production code. - goog.asserts.assertString(goog.string.Const.unwrap(justification), - 'must provide justification'); - goog.asserts.assert( - !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), - 'must provide non-empty justification'); - return goog.html.SafeStyleSheet. - createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet); -}; - - -/** - * Performs an "unchecked conversion" to SafeUrl from a plain string that is - * known to satisfy the SafeUrl type contract. - * - * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure - * that the value of {@code url} satisfies the SafeUrl type contract in all - * possible program states. - * - * - * @param {!goog.string.Const} justification A constant string explaining why - * this use of this method is safe. May include a security review ticket - * number. - * @param {string} url The string to wrap as a SafeUrl. - * @return {!goog.html.SafeUrl} The value of {@code url}, wrapped in a SafeUrl - * object. - */ -goog.html.uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract = - function(justification, url) { - // unwrap() called inside an assert so that justification can be optimized - // away in production code. - goog.asserts.assertString(goog.string.Const.unwrap(justification), - 'must provide justification'); - goog.asserts.assert( - !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), - 'must provide non-empty justification'); - return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); -}; - - -/** - * Performs an "unchecked conversion" to TrustedResourceUrl from a plain string - * that is known to satisfy the TrustedResourceUrl type contract. - * - * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure - * that the value of {@code url} satisfies the TrustedResourceUrl type contract - * in all possible program states. - * - * - * @param {!goog.string.Const} justification A constant string explaining why - * this use of this method is safe. May include a security review ticket - * number. - * @param {string} url The string to wrap as a TrustedResourceUrl. - * @return {!goog.html.TrustedResourceUrl} The value of {@code url}, wrapped in - * a TrustedResourceUrl object. - */ -goog.html.uncheckedconversions. - trustedResourceUrlFromStringKnownToSatisfyTypeContract = - function(justification, url) { - // unwrap() called inside an assert so that justification can be optimized - // away in production code. - goog.asserts.assertString(goog.string.Const.unwrap(justification), - 'must provide justification'); - goog.asserts.assert( - !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), - 'must provide non-empty justification'); - return goog.html.TrustedResourceUrl. - createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/i18n/bidi.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/i18n/bidi.js deleted file mode 100644 index 771ea3b..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/i18n/bidi.js +++ /dev/null @@ -1,877 +0,0 @@ -// 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 Utility functions for supporting Bidi issues. - */ - - -/** - * Namespace for bidi supporting functions. - */ -goog.provide('goog.i18n.bidi'); -goog.provide('goog.i18n.bidi.Dir'); -goog.provide('goog.i18n.bidi.DirectionalString'); -goog.provide('goog.i18n.bidi.Format'); - - -/** - * @define {boolean} FORCE_RTL forces the {@link goog.i18n.bidi.IS_RTL} constant - * to say that the current locale is a RTL locale. This should only be used - * if you want to override the default behavior for deciding whether the - * current locale is RTL or not. - * - * {@see goog.i18n.bidi.IS_RTL} - */ -goog.define('goog.i18n.bidi.FORCE_RTL', false); - - -/** - * Constant that defines whether or not the current locale is a RTL locale. - * If {@link goog.i18n.bidi.FORCE_RTL} is not true, this constant will default - * to check that {@link goog.LOCALE} is one of a few major RTL locales. - * - * <p>This is designed to be a maximally efficient compile-time constant. For - * example, for the default goog.LOCALE, compiling - * "if (goog.i18n.bidi.IS_RTL) alert('rtl') else {}" should produce no code. It - * is this design consideration that limits the implementation to only - * supporting a few major RTL locales, as opposed to the broader repertoire of - * something like goog.i18n.bidi.isRtlLanguage. - * - * <p>Since this constant refers to the directionality of the locale, it is up - * to the caller to determine if this constant should also be used for the - * direction of the UI. - * - * {@see goog.LOCALE} - * - * @type {boolean} - * - * TODO(user): write a test that checks that this is a compile-time constant. - */ -goog.i18n.bidi.IS_RTL = goog.i18n.bidi.FORCE_RTL || - ( - (goog.LOCALE.substring(0, 2).toLowerCase() == 'ar' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'fa' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'he' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'iw' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'ps' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'sd' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'ug' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'ur' || - goog.LOCALE.substring(0, 2).toLowerCase() == 'yi') && - (goog.LOCALE.length == 2 || - goog.LOCALE.substring(2, 3) == '-' || - goog.LOCALE.substring(2, 3) == '_') - ) || ( - goog.LOCALE.length >= 3 && - goog.LOCALE.substring(0, 3).toLowerCase() == 'ckb' && - (goog.LOCALE.length == 3 || - goog.LOCALE.substring(3, 4) == '-' || - goog.LOCALE.substring(3, 4) == '_') - ); - - -/** - * Unicode formatting characters and directionality string constants. - * @enum {string} - */ -goog.i18n.bidi.Format = { - /** Unicode "Left-To-Right Embedding" (LRE) character. */ - LRE: '\u202A', - /** Unicode "Right-To-Left Embedding" (RLE) character. */ - RLE: '\u202B', - /** Unicode "Pop Directional Formatting" (PDF) character. */ - PDF: '\u202C', - /** Unicode "Left-To-Right Mark" (LRM) character. */ - LRM: '\u200E', - /** Unicode "Right-To-Left Mark" (RLM) character. */ - RLM: '\u200F' -}; - - -/** - * Directionality enum. - * @enum {number} - */ -goog.i18n.bidi.Dir = { - /** - * Left-to-right. - */ - LTR: 1, - - /** - * Right-to-left. - */ - RTL: -1, - - /** - * Neither left-to-right nor right-to-left. - */ - NEUTRAL: 0 -}; - - -/** - * 'right' string constant. - * @type {string} - */ -goog.i18n.bidi.RIGHT = 'right'; - - -/** - * 'left' string constant. - * @type {string} - */ -goog.i18n.bidi.LEFT = 'left'; - - -/** - * 'left' if locale is RTL, 'right' if not. - * @type {string} - */ -goog.i18n.bidi.I18N_RIGHT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.LEFT : - goog.i18n.bidi.RIGHT; - - -/** - * 'right' if locale is RTL, 'left' if not. - * @type {string} - */ -goog.i18n.bidi.I18N_LEFT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.RIGHT : - goog.i18n.bidi.LEFT; - - -/** - * Convert a directionality given in various formats to a goog.i18n.bidi.Dir - * constant. Useful for interaction with different standards of directionality - * representation. - * - * @param {goog.i18n.bidi.Dir|number|boolean|null} givenDir Directionality given - * in one of the following formats: - * 1. A goog.i18n.bidi.Dir constant. - * 2. A number (positive = LTR, negative = RTL, 0 = neutral). - * 3. A boolean (true = RTL, false = LTR). - * 4. A null for unknown directionality. - * @param {boolean=} opt_noNeutral Whether a givenDir of zero or - * goog.i18n.bidi.Dir.NEUTRAL should be treated as null, i.e. unknown, in - * order to preserve legacy behavior. - * @return {?goog.i18n.bidi.Dir} A goog.i18n.bidi.Dir constant matching the - * given directionality. If given null, returns null (i.e. unknown). - */ -goog.i18n.bidi.toDir = function(givenDir, opt_noNeutral) { - if (typeof givenDir == 'number') { - // This includes the non-null goog.i18n.bidi.Dir case. - return givenDir > 0 ? goog.i18n.bidi.Dir.LTR : - givenDir < 0 ? goog.i18n.bidi.Dir.RTL : - opt_noNeutral ? null : goog.i18n.bidi.Dir.NEUTRAL; - } else if (givenDir == null) { - return null; - } else { - // Must be typeof givenDir == 'boolean'. - return givenDir ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR; - } -}; - - -/** - * A practical pattern to identify strong LTR characters. This pattern is not - * theoretically correct according to the Unicode standard. It is simplified for - * performance and small code size. - * @type {string} - * @private - */ -goog.i18n.bidi.ltrChars_ = - 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' + - '\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF'; - - -/** - * A practical pattern to identify strong RTL character. This pattern is not - * theoretically correct according to the Unicode standard. It is simplified - * for performance and small code size. - * @type {string} - * @private - */ -goog.i18n.bidi.rtlChars_ = '\u0591-\u07FF\u200F\uFB1D-\uFDFF\uFE70-\uFEFC'; - - -/** - * Simplified regular expression for an HTML tag (opening or closing) or an HTML - * escape. We might want to skip over such expressions when estimating the text - * directionality. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.htmlSkipReg_ = /<[^>]*>|&[^;]+;/g; - - -/** - * Returns the input text with spaces instead of HTML tags or HTML escapes, if - * opt_isStripNeeded is true. Else returns the input as is. - * Useful for text directionality estimation. - * Note: the function should not be used in other contexts; it is not 100% - * correct, but rather a good-enough implementation for directionality - * estimation purposes. - * @param {string} str The given string. - * @param {boolean=} opt_isStripNeeded Whether to perform the stripping. - * Default: false (to retain consistency with calling functions). - * @return {string} The given string cleaned of HTML tags / escapes. - * @private - */ -goog.i18n.bidi.stripHtmlIfNeeded_ = function(str, opt_isStripNeeded) { - return opt_isStripNeeded ? str.replace(goog.i18n.bidi.htmlSkipReg_, '') : - str; -}; - - -/** - * Regular expression to check for RTL characters. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.rtlCharReg_ = new RegExp('[' + goog.i18n.bidi.rtlChars_ + ']'); - - -/** - * Regular expression to check for LTR characters. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.ltrCharReg_ = new RegExp('[' + goog.i18n.bidi.ltrChars_ + ']'); - - -/** - * Test whether the given string has any RTL characters in it. - * @param {string} str The given string that need to be tested. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether the string contains RTL characters. - */ -goog.i18n.bidi.hasAnyRtl = function(str, opt_isHtml) { - return goog.i18n.bidi.rtlCharReg_.test(goog.i18n.bidi.stripHtmlIfNeeded_( - str, opt_isHtml)); -}; - - -/** - * Test whether the given string has any RTL characters in it. - * @param {string} str The given string that need to be tested. - * @return {boolean} Whether the string contains RTL characters. - * @deprecated Use hasAnyRtl. - */ -goog.i18n.bidi.hasRtlChar = goog.i18n.bidi.hasAnyRtl; - - -/** - * Test whether the given string has any LTR characters in it. - * @param {string} str The given string that need to be tested. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether the string contains LTR characters. - */ -goog.i18n.bidi.hasAnyLtr = function(str, opt_isHtml) { - return goog.i18n.bidi.ltrCharReg_.test(goog.i18n.bidi.stripHtmlIfNeeded_( - str, opt_isHtml)); -}; - - -/** - * Regular expression pattern to check if the first character in the string - * is LTR. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.ltrRe_ = new RegExp('^[' + goog.i18n.bidi.ltrChars_ + ']'); - - -/** - * Regular expression pattern to check if the first character in the string - * is RTL. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.rtlRe_ = new RegExp('^[' + goog.i18n.bidi.rtlChars_ + ']'); - - -/** - * Check if the first character in the string is RTL or not. - * @param {string} str The given string that need to be tested. - * @return {boolean} Whether the first character in str is an RTL char. - */ -goog.i18n.bidi.isRtlChar = function(str) { - return goog.i18n.bidi.rtlRe_.test(str); -}; - - -/** - * Check if the first character in the string is LTR or not. - * @param {string} str The given string that need to be tested. - * @return {boolean} Whether the first character in str is an LTR char. - */ -goog.i18n.bidi.isLtrChar = function(str) { - return goog.i18n.bidi.ltrRe_.test(str); -}; - - -/** - * Check if the first character in the string is neutral or not. - * @param {string} str The given string that need to be tested. - * @return {boolean} Whether the first character in str is a neutral char. - */ -goog.i18n.bidi.isNeutralChar = function(str) { - return !goog.i18n.bidi.isLtrChar(str) && !goog.i18n.bidi.isRtlChar(str); -}; - - -/** - * Regular expressions to check if a piece of text is of LTR directionality - * on first character with strong directionality. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.ltrDirCheckRe_ = new RegExp( - '^[^' + goog.i18n.bidi.rtlChars_ + ']*[' + goog.i18n.bidi.ltrChars_ + ']'); - - -/** - * Regular expressions to check if a piece of text is of RTL directionality - * on first character with strong directionality. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.rtlDirCheckRe_ = new RegExp( - '^[^' + goog.i18n.bidi.ltrChars_ + ']*[' + goog.i18n.bidi.rtlChars_ + ']'); - - -/** - * Check whether the first strongly directional character (if any) is RTL. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether RTL directionality is detected using the first - * strongly-directional character method. - */ -goog.i18n.bidi.startsWithRtl = function(str, opt_isHtml) { - return goog.i18n.bidi.rtlDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_( - str, opt_isHtml)); -}; - - -/** - * Check whether the first strongly directional character (if any) is RTL. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether RTL directionality is detected using the first - * strongly-directional character method. - * @deprecated Use startsWithRtl. - */ -goog.i18n.bidi.isRtlText = goog.i18n.bidi.startsWithRtl; - - -/** - * Check whether the first strongly directional character (if any) is LTR. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether LTR directionality is detected using the first - * strongly-directional character method. - */ -goog.i18n.bidi.startsWithLtr = function(str, opt_isHtml) { - return goog.i18n.bidi.ltrDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_( - str, opt_isHtml)); -}; - - -/** - * Check whether the first strongly directional character (if any) is LTR. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether LTR directionality is detected using the first - * strongly-directional character method. - * @deprecated Use startsWithLtr. - */ -goog.i18n.bidi.isLtrText = goog.i18n.bidi.startsWithLtr; - - -/** - * Regular expression to check if a string looks like something that must - * always be LTR even in RTL text, e.g. a URL. When estimating the - * directionality of text containing these, we treat these as weakly LTR, - * like numbers. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.isRequiredLtrRe_ = /^http:\/\/.*/; - - -/** - * Check whether the input string either contains no strongly directional - * characters or looks like a url. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether neutral directionality is detected. - */ -goog.i18n.bidi.isNeutralText = function(str, opt_isHtml) { - str = goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml); - return goog.i18n.bidi.isRequiredLtrRe_.test(str) || - !goog.i18n.bidi.hasAnyLtr(str) && !goog.i18n.bidi.hasAnyRtl(str); -}; - - -/** - * Regular expressions to check if the last strongly-directional character in a - * piece of text is LTR. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.ltrExitDirCheckRe_ = new RegExp( - '[' + goog.i18n.bidi.ltrChars_ + '][^' + goog.i18n.bidi.rtlChars_ + ']*$'); - - -/** - * Regular expressions to check if the last strongly-directional character in a - * piece of text is RTL. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.rtlExitDirCheckRe_ = new RegExp( - '[' + goog.i18n.bidi.rtlChars_ + '][^' + goog.i18n.bidi.ltrChars_ + ']*$'); - - -/** - * Check if the exit directionality a piece of text is LTR, i.e. if the last - * strongly-directional character in the string is LTR. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether LTR exit directionality was detected. - */ -goog.i18n.bidi.endsWithLtr = function(str, opt_isHtml) { - return goog.i18n.bidi.ltrExitDirCheckRe_.test( - goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); -}; - - -/** - * Check if the exit directionality a piece of text is LTR, i.e. if the last - * strongly-directional character in the string is LTR. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether LTR exit directionality was detected. - * @deprecated Use endsWithLtr. - */ -goog.i18n.bidi.isLtrExitText = goog.i18n.bidi.endsWithLtr; - - -/** - * Check if the exit directionality a piece of text is RTL, i.e. if the last - * strongly-directional character in the string is RTL. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether RTL exit directionality was detected. - */ -goog.i18n.bidi.endsWithRtl = function(str, opt_isHtml) { - return goog.i18n.bidi.rtlExitDirCheckRe_.test( - goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); -}; - - -/** - * Check if the exit directionality a piece of text is RTL, i.e. if the last - * strongly-directional character in the string is RTL. - * @param {string} str String being checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether RTL exit directionality was detected. - * @deprecated Use endsWithRtl. - */ -goog.i18n.bidi.isRtlExitText = goog.i18n.bidi.endsWithRtl; - - -/** - * A regular expression for matching right-to-left language codes. - * See {@link #isRtlLanguage} for the design. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.rtlLocalesRe_ = new RegExp( - '^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|' + - '.*[-_](Arab|Hebr|Thaa|Nkoo|Tfng))' + - '(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)', - 'i'); - - -/** - * Check if a BCP 47 / III language code indicates an RTL language, i.e. either: - * - a language code explicitly specifying one of the right-to-left scripts, - * e.g. "az-Arab", or<p> - * - a language code specifying one of the languages normally written in a - * right-to-left script, e.g. "fa" (Farsi), except ones explicitly specifying - * Latin or Cyrillic script (which are the usual LTR alternatives).<p> - * The list of right-to-left scripts appears in the 100-199 range in - * http://www.unicode.org/iso15924/iso15924-num.html, of which Arabic and - * Hebrew are by far the most widely used. We also recognize Thaana, N'Ko, and - * Tifinagh, which also have significant modern usage. The rest (Syriac, - * Samaritan, Mandaic, etc.) seem to have extremely limited or no modern usage - * and are not recognized to save on code size. - * The languages usually written in a right-to-left script are taken as those - * with Suppress-Script: Hebr|Arab|Thaa|Nkoo|Tfng in - * http://www.iana.org/assignments/language-subtag-registry, - * as well as Central (or Sorani) Kurdish (ckb), Sindhi (sd) and Uyghur (ug). - * Other subtags of the language code, e.g. regions like EG (Egypt), are - * ignored. - * @param {string} lang BCP 47 (a.k.a III) language code. - * @return {boolean} Whether the language code is an RTL language. - */ -goog.i18n.bidi.isRtlLanguage = function(lang) { - return goog.i18n.bidi.rtlLocalesRe_.test(lang); -}; - - -/** - * Regular expression for bracket guard replacement in html. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.bracketGuardHtmlRe_ = - /(\(.*?\)+)|(\[.*?\]+)|(\{.*?\}+)|(<.*?(>)+)/g; - - -/** - * Regular expression for bracket guard replacement in text. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.bracketGuardTextRe_ = - /(\(.*?\)+)|(\[.*?\]+)|(\{.*?\}+)|(<.*?>+)/g; - - -/** - * Apply bracket guard using html span tag. This is to address the problem of - * messy bracket display frequently happens in RTL layout. - * @param {string} s The string that need to be processed. - * @param {boolean=} opt_isRtlContext specifies default direction (usually - * direction of the UI). - * @return {string} The processed string, with all bracket guarded. - */ -goog.i18n.bidi.guardBracketInHtml = function(s, opt_isRtlContext) { - var useRtl = opt_isRtlContext === undefined ? - goog.i18n.bidi.hasAnyRtl(s) : opt_isRtlContext; - if (useRtl) { - return s.replace(goog.i18n.bidi.bracketGuardHtmlRe_, - '<span dir=rtl>$&</span>'); - } - return s.replace(goog.i18n.bidi.bracketGuardHtmlRe_, - '<span dir=ltr>$&</span>'); -}; - - -/** - * Apply bracket guard using LRM and RLM. This is to address the problem of - * messy bracket display frequently happens in RTL layout. - * This version works for both plain text and html. But it does not work as - * good as guardBracketInHtml in some cases. - * @param {string} s The string that need to be processed. - * @param {boolean=} opt_isRtlContext specifies default direction (usually - * direction of the UI). - * @return {string} The processed string, with all bracket guarded. - */ -goog.i18n.bidi.guardBracketInText = function(s, opt_isRtlContext) { - var useRtl = opt_isRtlContext === undefined ? - goog.i18n.bidi.hasAnyRtl(s) : opt_isRtlContext; - var mark = useRtl ? goog.i18n.bidi.Format.RLM : goog.i18n.bidi.Format.LRM; - return s.replace(goog.i18n.bidi.bracketGuardTextRe_, mark + '$&' + mark); -}; - - -/** - * Enforce the html snippet in RTL directionality regardless overall context. - * If the html piece was enclosed by tag, dir will be applied to existing - * tag, otherwise a span tag will be added as wrapper. For this reason, if - * html snippet start with with tag, this tag must enclose the whole piece. If - * the tag already has a dir specified, this new one will override existing - * one in behavior (tested on FF and IE). - * @param {string} html The string that need to be processed. - * @return {string} The processed string, with directionality enforced to RTL. - */ -goog.i18n.bidi.enforceRtlInHtml = function(html) { - if (html.charAt(0) == '<') { - return html.replace(/<\w+/, '$& dir=rtl'); - } - // '\n' is important for FF so that it won't incorrectly merge span groups - return '\n<span dir=rtl>' + html + '</span>'; -}; - - -/** - * Enforce RTL on both end of the given text piece using unicode BiDi formatting - * characters RLE and PDF. - * @param {string} text The piece of text that need to be wrapped. - * @return {string} The wrapped string after process. - */ -goog.i18n.bidi.enforceRtlInText = function(text) { - return goog.i18n.bidi.Format.RLE + text + goog.i18n.bidi.Format.PDF; -}; - - -/** - * Enforce the html snippet in RTL directionality regardless overall context. - * If the html piece was enclosed by tag, dir will be applied to existing - * tag, otherwise a span tag will be added as wrapper. For this reason, if - * html snippet start with with tag, this tag must enclose the whole piece. If - * the tag already has a dir specified, this new one will override existing - * one in behavior (tested on FF and IE). - * @param {string} html The string that need to be processed. - * @return {string} The processed string, with directionality enforced to RTL. - */ -goog.i18n.bidi.enforceLtrInHtml = function(html) { - if (html.charAt(0) == '<') { - return html.replace(/<\w+/, '$& dir=ltr'); - } - // '\n' is important for FF so that it won't incorrectly merge span groups - return '\n<span dir=ltr>' + html + '</span>'; -}; - - -/** - * Enforce LTR on both end of the given text piece using unicode BiDi formatting - * characters LRE and PDF. - * @param {string} text The piece of text that need to be wrapped. - * @return {string} The wrapped string after process. - */ -goog.i18n.bidi.enforceLtrInText = function(text) { - return goog.i18n.bidi.Format.LRE + text + goog.i18n.bidi.Format.PDF; -}; - - -/** - * Regular expression to find dimensions such as "padding: .3 0.4ex 5px 6;" - * @type {RegExp} - * @private - */ -goog.i18n.bidi.dimensionsRe_ = - /:\s*([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)/g; - - -/** - * Regular expression for left. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.leftRe_ = /left/gi; - - -/** - * Regular expression for right. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.rightRe_ = /right/gi; - - -/** - * Placeholder regular expression for swapping. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.tempRe_ = /%%%%/g; - - -/** - * Swap location parameters and 'left'/'right' in CSS specification. The - * processed string will be suited for RTL layout. Though this function can - * cover most cases, there are always exceptions. It is suggested to put - * those exceptions in separate group of CSS string. - * @param {string} cssStr CSS spefication string. - * @return {string} Processed CSS specification string. - */ -goog.i18n.bidi.mirrorCSS = function(cssStr) { - return cssStr. - // reverse dimensions - replace(goog.i18n.bidi.dimensionsRe_, ':$1 $4 $3 $2'). - replace(goog.i18n.bidi.leftRe_, '%%%%'). // swap left and right - replace(goog.i18n.bidi.rightRe_, goog.i18n.bidi.LEFT). - replace(goog.i18n.bidi.tempRe_, goog.i18n.bidi.RIGHT); -}; - - -/** - * Regular expression for hebrew double quote substitution, finding quote - * directly after hebrew characters. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.doubleQuoteSubstituteRe_ = /([\u0591-\u05f2])"/g; - - -/** - * Regular expression for hebrew single quote substitution, finding quote - * directly after hebrew characters. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.singleQuoteSubstituteRe_ = /([\u0591-\u05f2])'/g; - - -/** - * Replace the double and single quote directly after a Hebrew character with - * GERESH and GERSHAYIM. In such case, most likely that's user intention. - * @param {string} str String that need to be processed. - * @return {string} Processed string with double/single quote replaced. - */ -goog.i18n.bidi.normalizeHebrewQuote = function(str) { - return str. - replace(goog.i18n.bidi.doubleQuoteSubstituteRe_, '$1\u05f4'). - replace(goog.i18n.bidi.singleQuoteSubstituteRe_, '$1\u05f3'); -}; - - -/** - * Regular expression to split a string into "words" for directionality - * estimation based on relative word counts. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.wordSeparatorRe_ = /\s+/; - - -/** - * Regular expression to check if a string contains any numerals. Used to - * differentiate between completely neutral strings and those containing - * numbers, which are weakly LTR. - * @type {RegExp} - * @private - */ -goog.i18n.bidi.hasNumeralsRe_ = /\d/; - - -/** - * This constant controls threshold of RTL directionality. - * @type {number} - * @private - */ -goog.i18n.bidi.rtlDetectionThreshold_ = 0.40; - - -/** - * Estimates the directionality of a string based on relative word counts. - * If the number of RTL words is above a certain percentage of the total number - * of strongly directional words, returns RTL. - * Otherwise, if any words are strongly or weakly LTR, returns LTR. - * Otherwise, returns UNKNOWN, which is used to mean "neutral". - * Numbers are counted as weakly LTR. - * @param {string} str The string to be checked. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {goog.i18n.bidi.Dir} Estimated overall directionality of {@code str}. - */ -goog.i18n.bidi.estimateDirection = function(str, opt_isHtml) { - var rtlCount = 0; - var totalCount = 0; - var hasWeaklyLtr = false; - var tokens = goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml). - split(goog.i18n.bidi.wordSeparatorRe_); - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (goog.i18n.bidi.startsWithRtl(token)) { - rtlCount++; - totalCount++; - } else if (goog.i18n.bidi.isRequiredLtrRe_.test(token)) { - hasWeaklyLtr = true; - } else if (goog.i18n.bidi.hasAnyLtr(token)) { - totalCount++; - } else if (goog.i18n.bidi.hasNumeralsRe_.test(token)) { - hasWeaklyLtr = true; - } - } - - return totalCount == 0 ? - (hasWeaklyLtr ? goog.i18n.bidi.Dir.LTR : goog.i18n.bidi.Dir.NEUTRAL) : - (rtlCount / totalCount > goog.i18n.bidi.rtlDetectionThreshold_ ? - goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR); -}; - - -/** - * Check the directionality of a piece of text, return true if the piece of - * text should be laid out in RTL direction. - * @param {string} str The piece of text that need to be detected. - * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. - * Default: false. - * @return {boolean} Whether this piece of text should be laid out in RTL. - */ -goog.i18n.bidi.detectRtlDirectionality = function(str, opt_isHtml) { - return goog.i18n.bidi.estimateDirection(str, opt_isHtml) == - goog.i18n.bidi.Dir.RTL; -}; - - -/** - * Sets text input element's directionality and text alignment based on a - * given directionality. Does nothing if the given directionality is unknown or - * neutral. - * @param {Element} element Input field element to set directionality to. - * @param {goog.i18n.bidi.Dir|number|boolean|null} dir Desired directionality, - * given in one of the following formats: - * 1. A goog.i18n.bidi.Dir constant. - * 2. A number (positive = LRT, negative = RTL, 0 = neutral). - * 3. A boolean (true = RTL, false = LTR). - * 4. A null for unknown directionality. - */ -goog.i18n.bidi.setElementDirAndAlign = function(element, dir) { - if (element) { - dir = goog.i18n.bidi.toDir(dir); - if (dir) { - element.style.textAlign = - dir == goog.i18n.bidi.Dir.RTL ? - goog.i18n.bidi.RIGHT : goog.i18n.bidi.LEFT; - element.dir = dir == goog.i18n.bidi.Dir.RTL ? 'rtl' : 'ltr'; - } - } -}; - - - -/** - * Strings that have an (optional) known direction. - * - * Implementations of this interface are string-like objects that carry an - * attached direction, if known. - * @interface - */ -goog.i18n.bidi.DirectionalString = function() {}; - - -/** - * Interface marker of the DirectionalString interface. - * - * This property can be used to determine at runtime whether or not an object - * implements this interface. All implementations of this interface set this - * property to {@code true}. - * @type {boolean} - */ -goog.i18n.bidi.DirectionalString.prototype. - implementsGoogI18nBidiDirectionalString; - - -/** - * Retrieves this object's known direction (if any). - * @return {?goog.i18n.bidi.Dir} The known direction. Null if unknown. - */ -goog.i18n.bidi.DirectionalString.prototype.getDirection; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/iter/iter.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/iter/iter.js deleted file mode 100644 index 751caff..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/iter/iter.js +++ /dev/null @@ -1,1305 +0,0 @@ -// 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 Python style iteration utilities. - * @author arv@google.com (Erik Arvidsson) - */ - - -goog.provide('goog.iter'); -goog.provide('goog.iter.Iterable'); -goog.provide('goog.iter.Iterator'); -goog.provide('goog.iter.StopIteration'); - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.functions'); -goog.require('goog.math'); - - -/** - * @typedef {goog.iter.Iterator|{length:number}|{__iterator__}} - */ -goog.iter.Iterable; - - -/** - * Singleton Error object that is used to terminate iterations. - * @const {!Error} - */ -goog.iter.StopIteration = ('StopIteration' in goog.global) ? - // For script engines that support legacy iterators. - goog.global['StopIteration'] : - Error('StopIteration'); - - - -/** - * Class/interface for iterators. An iterator needs to implement a {@code next} - * method and it needs to throw a {@code goog.iter.StopIteration} when the - * iteration passes beyond the end. Iterators have no {@code hasNext} method. - * It is recommended to always use the helper functions to iterate over the - * iterator or in case you are only targeting JavaScript 1.7 for in loops. - * @constructor - * @template VALUE - */ -goog.iter.Iterator = function() {}; - - -/** - * Returns the next value of the iteration. This will throw the object - * {@see goog.iter#StopIteration} when the iteration passes the end. - * @return {VALUE} Any object or value. - */ -goog.iter.Iterator.prototype.next = function() { - throw goog.iter.StopIteration; -}; - - -/** - * Returns the {@code Iterator} object itself. This is used to implement - * the iterator protocol in JavaScript 1.7 - * @param {boolean=} opt_keys Whether to return the keys or values. Default is - * to only return the values. This is being used by the for-in loop (true) - * and the for-each-in loop (false). Even though the param gives a hint - * about what the iterator will return there is no guarantee that it will - * return the keys when true is passed. - * @return {!goog.iter.Iterator<VALUE>} The object itself. - */ -goog.iter.Iterator.prototype.__iterator__ = function(opt_keys) { - return this; -}; - - -/** - * Returns an iterator that knows how to iterate over the values in the object. - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable If the - * object is an iterator it will be returned as is. If the object has an - * {@code __iterator__} method that will be called to get the value - * iterator. If the object is an array-like object we create an iterator - * for that. - * @return {!goog.iter.Iterator<VALUE>} An iterator that knows how to iterate - * over the values in {@code iterable}. - * @template VALUE - */ -goog.iter.toIterator = function(iterable) { - if (iterable instanceof goog.iter.Iterator) { - return iterable; - } - if (typeof iterable.__iterator__ == 'function') { - return iterable.__iterator__(false); - } - if (goog.isArrayLike(iterable)) { - var i = 0; - var newIter = new goog.iter.Iterator; - newIter.next = function() { - while (true) { - if (i >= iterable.length) { - throw goog.iter.StopIteration; - } - // Don't include deleted elements. - if (!(i in iterable)) { - i++; - continue; - } - return iterable[i++]; - } - }; - return newIter; - } - - - // TODO(arv): Should we fall back on goog.structs.getValues()? - throw Error('Not implemented'); -}; - - -/** - * Calls a function for each element in the iterator with the element of the - * iterator passed as argument. - * - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * to iterate over. If the iterable is an object {@code toIterator} will be - * called on it. - * @param {function(this:THIS,VALUE,?,!goog.iter.Iterator<VALUE>)} f - * The function to call for every element. This function takes 3 arguments - * (the element, undefined, and the iterator) and the return value is - * irrelevant. The reason for passing undefined as the second argument is - * so that the same function can be used in {@see goog.array#forEach} as - * well as others. The third parameter is of type "number" for - * arraylike objects, undefined, otherwise. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @template THIS, VALUE - */ -goog.iter.forEach = function(iterable, f, opt_obj) { - if (goog.isArrayLike(iterable)) { - /** @preserveTry */ - try { - // NOTES: this passes the index number to the second parameter - // of the callback contrary to the documentation above. - goog.array.forEach(/** @type {goog.array.ArrayLike} */(iterable), f, - opt_obj); - } catch (ex) { - if (ex !== goog.iter.StopIteration) { - throw ex; - } - } - } else { - iterable = goog.iter.toIterator(iterable); - /** @preserveTry */ - try { - while (true) { - f.call(opt_obj, iterable.next(), undefined, iterable); - } - } catch (ex) { - if (ex !== goog.iter.StopIteration) { - throw ex; - } - } - } -}; - - -/** - * Calls a function for every element in the iterator, and if the function - * returns true adds the element to a new iterator. - * - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * to iterate over. - * @param { - * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f - * The function to call for every element. This function takes 3 arguments - * (the element, undefined, and the iterator) and should return a boolean. - * If the return value is true the element will be included in the returned - * iterator. If it is false the element is not included. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @return {!goog.iter.Iterator<VALUE>} A new iterator in which only elements - * that passed the test are present. - * @template THIS, VALUE - */ -goog.iter.filter = function(iterable, f, opt_obj) { - var iterator = goog.iter.toIterator(iterable); - var newIter = new goog.iter.Iterator; - newIter.next = function() { - while (true) { - var val = iterator.next(); - if (f.call(opt_obj, val, undefined, iterator)) { - return val; - } - } - }; - return newIter; -}; - - -/** - * Calls a function for every element in the iterator, and if the function - * returns false adds the element to a new iterator. - * - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * to iterate over. - * @param { - * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f - * The function to call for every element. This function takes 3 arguments - * (the element, undefined, and the iterator) and should return a boolean. - * If the return value is false the element will be included in the returned - * iterator. If it is true the element is not included. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @return {!goog.iter.Iterator<VALUE>} A new iterator in which only elements - * that did not pass the test are present. - * @template THIS, VALUE - */ -goog.iter.filterFalse = function(iterable, f, opt_obj) { - return goog.iter.filter(iterable, goog.functions.not(f), opt_obj); -}; - - -/** - * Creates a new iterator that returns the values in a range. This function - * can take 1, 2 or 3 arguments: - * <pre> - * range(5) same as range(0, 5, 1) - * range(2, 5) same as range(2, 5, 1) - * </pre> - * - * @param {number} startOrStop The stop value if only one argument is provided. - * The start value if 2 or more arguments are provided. If only one - * argument is used the start value is 0. - * @param {number=} opt_stop The stop value. If left out then the first - * argument is used as the stop value. - * @param {number=} opt_step The number to increment with between each call to - * next. This can be negative. - * @return {!goog.iter.Iterator<number>} A new iterator that returns the values - * in the range. - */ -goog.iter.range = function(startOrStop, opt_stop, opt_step) { - var start = 0; - var stop = startOrStop; - var step = opt_step || 1; - if (arguments.length > 1) { - start = startOrStop; - stop = opt_stop; - } - if (step == 0) { - throw Error('Range step argument must not be zero'); - } - - var newIter = new goog.iter.Iterator; - newIter.next = function() { - if (step > 0 && start >= stop || step < 0 && start <= stop) { - throw goog.iter.StopIteration; - } - var rv = start; - start += step; - return rv; - }; - return newIter; -}; - - -/** - * Joins the values in a iterator with a delimiter. - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * to get the values from. - * @param {string} deliminator The text to put between the values. - * @return {string} The joined value string. - * @template VALUE - */ -goog.iter.join = function(iterable, deliminator) { - return goog.iter.toArray(iterable).join(deliminator); -}; - - -/** - * For every element in the iterator call a function and return a new iterator - * with that value. - * - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterator to iterate over. - * @param { - * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):RESULT} f - * The function to call for every element. This function takes 3 arguments - * (the element, undefined, and the iterator) and should return a new value. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @return {!goog.iter.Iterator<RESULT>} A new iterator that returns the - * results of applying the function to each element in the original - * iterator. - * @template THIS, VALUE, RESULT - */ -goog.iter.map = function(iterable, f, opt_obj) { - var iterator = goog.iter.toIterator(iterable); - var newIter = new goog.iter.Iterator; - newIter.next = function() { - var val = iterator.next(); - return f.call(opt_obj, val, undefined, iterator); - }; - return newIter; -}; - - -/** - * Passes every element of an iterator into a function and accumulates the - * result. - * - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * to iterate over. - * @param {function(this:THIS,VALUE,VALUE):VALUE} f The function to call for - * every element. This function takes 2 arguments (the function's previous - * result or the initial value, and the value of the current element). - * function(previousValue, currentElement) : newValue. - * @param {VALUE} val The initial value to pass into the function on the first - * call. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * f. - * @return {VALUE} Result of evaluating f repeatedly across the values of - * the iterator. - * @template THIS, VALUE - */ -goog.iter.reduce = function(iterable, f, val, opt_obj) { - var rval = val; - goog.iter.forEach(iterable, function(val) { - rval = f.call(opt_obj, rval, val); - }); - return rval; -}; - - -/** - * Goes through the values in the iterator. Calls f for each of these, and if - * any of them returns true, this returns true (without checking the rest). If - * all return false this will return false. - * - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * object. - * @param { - * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f - * The function to call for every value. This function takes 3 arguments - * (the value, undefined, and the iterator) and should return a boolean. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @return {boolean} true if any value passes the test. - * @template THIS, VALUE - */ -goog.iter.some = function(iterable, f, opt_obj) { - iterable = goog.iter.toIterator(iterable); - /** @preserveTry */ - try { - while (true) { - if (f.call(opt_obj, iterable.next(), undefined, iterable)) { - return true; - } - } - } catch (ex) { - if (ex !== goog.iter.StopIteration) { - throw ex; - } - } - return false; -}; - - -/** - * Goes through the values in the iterator. Calls f for each of these and if any - * of them returns false this returns false (without checking the rest). If all - * return true this will return true. - * - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * object. - * @param { - * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f - * The function to call for every value. This function takes 3 arguments - * (the value, undefined, and the iterator) and should return a boolean. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @return {boolean} true if every value passes the test. - * @template THIS, VALUE - */ -goog.iter.every = function(iterable, f, opt_obj) { - iterable = goog.iter.toIterator(iterable); - /** @preserveTry */ - try { - while (true) { - if (!f.call(opt_obj, iterable.next(), undefined, iterable)) { - return false; - } - } - } catch (ex) { - if (ex !== goog.iter.StopIteration) { - throw ex; - } - } - return true; -}; - - -/** - * Takes zero or more iterables and returns one iterator that will iterate over - * them in the order chained. - * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any - * number of iterable objects. - * @return {!goog.iter.Iterator<VALUE>} Returns a new iterator that will - * iterate over all the given iterables' contents. - * @template VALUE - */ -goog.iter.chain = function(var_args) { - return goog.iter.chainFromIterable(arguments); -}; - - -/** - * Takes a single iterable containing zero or more iterables and returns one - * iterator that will iterate over each one in the order given. - * @see http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable - * @param {goog.iter.Iterable} iterable The iterable of iterables to chain. - * @return {!goog.iter.Iterator<VALUE>} Returns a new iterator that will - * iterate over all the contents of the iterables contained within - * {@code iterable}. - * @template VALUE - */ -goog.iter.chainFromIterable = function(iterable) { - var iterator = goog.iter.toIterator(iterable); - var iter = new goog.iter.Iterator(); - var current = null; - - iter.next = function() { - while (true) { - if (current == null) { - var it = iterator.next(); - current = goog.iter.toIterator(it); - } - try { - return current.next(); - } catch (ex) { - if (ex !== goog.iter.StopIteration) { - throw ex; - } - current = null; - } - } - }; - - return iter; -}; - - -/** - * Builds a new iterator that iterates over the original, but skips elements as - * long as a supplied function returns true. - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * object. - * @param { - * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f - * The function to call for every value. This function takes 3 arguments - * (the value, undefined, and the iterator) and should return a boolean. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @return {!goog.iter.Iterator<VALUE>} A new iterator that drops elements from - * the original iterator as long as {@code f} is true. - * @template THIS, VALUE - */ -goog.iter.dropWhile = function(iterable, f, opt_obj) { - var iterator = goog.iter.toIterator(iterable); - var newIter = new goog.iter.Iterator; - var dropping = true; - newIter.next = function() { - while (true) { - var val = iterator.next(); - if (dropping && f.call(opt_obj, val, undefined, iterator)) { - continue; - } else { - dropping = false; - } - return val; - } - }; - return newIter; -}; - - -/** - * Builds a new iterator that iterates over the original, but only as long as a - * supplied function returns true. - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * object. - * @param { - * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f - * The function to call for every value. This function takes 3 arguments - * (the value, undefined, and the iterator) and should return a boolean. - * @param {THIS=} opt_obj This is used as the 'this' object in f when called. - * @return {!goog.iter.Iterator<VALUE>} A new iterator that keeps elements in - * the original iterator as long as the function is true. - * @template THIS, VALUE - */ -goog.iter.takeWhile = function(iterable, f, opt_obj) { - var iterator = goog.iter.toIterator(iterable); - var iter = new goog.iter.Iterator(); - iter.next = function() { - var val = iterator.next(); - if (f.call(opt_obj, val, undefined, iterator)) { - return val; - } - throw goog.iter.StopIteration; - }; - return iter; -}; - - -/** - * Converts the iterator to an array - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator - * to convert to an array. - * @return {!Array<VALUE>} An array of the elements the iterator iterates over. - * @template VALUE - */ -goog.iter.toArray = function(iterable) { - // Fast path for array-like. - if (goog.isArrayLike(iterable)) { - return goog.array.toArray(/** @type {!goog.array.ArrayLike} */(iterable)); - } - iterable = goog.iter.toIterator(iterable); - var array = []; - goog.iter.forEach(iterable, function(val) { - array.push(val); - }); - return array; -}; - - -/** - * Iterates over two iterables and returns true if they contain the same - * sequence of elements and have the same length. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable1 The first - * iterable object. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable2 The second - * iterable object. - * @param {function(VALUE,VALUE):boolean=} opt_equalsFn Optional comparison - * function. - * Should take two arguments to compare, and return true if the arguments - * are equal. Defaults to {@link goog.array.defaultCompareEquality} which - * compares the elements using the built-in '===' operator. - * @return {boolean} true if the iterables contain the same sequence of elements - * and have the same length. - * @template VALUE - */ -goog.iter.equals = function(iterable1, iterable2, opt_equalsFn) { - var fillValue = {}; - var pairs = goog.iter.zipLongest(fillValue, iterable1, iterable2); - var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality; - return goog.iter.every(pairs, function(pair) { - return equalsFn(pair[0], pair[1]); - }); -}; - - -/** - * Advances the iterator to the next position, returning the given default value - * instead of throwing an exception if the iterator has no more entries. - * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterable - * object. - * @param {VALUE} defaultValue The value to return if the iterator is empty. - * @return {VALUE} The next item in the iteration, or defaultValue if the - * iterator was empty. - * @template VALUE - */ -goog.iter.nextOrValue = function(iterable, defaultValue) { - try { - return goog.iter.toIterator(iterable).next(); - } catch (e) { - if (e != goog.iter.StopIteration) { - throw e; - } - return defaultValue; - } -}; - - -/** - * Cartesian product of zero or more sets. Gives an iterator that gives every - * combination of one element chosen from each set. For example, - * ([1, 2], [3, 4]) gives ([1, 3], [1, 4], [2, 3], [2, 4]). - * @see http://docs.python.org/library/itertools.html#itertools.product - * @param {...!goog.array.ArrayLike<VALUE>} var_args Zero or more sets, as - * arrays. - * @return {!goog.iter.Iterator<!Array<VALUE>>} An iterator that gives each - * n-tuple (as an array). - * @template VALUE - */ -goog.iter.product = function(var_args) { - var someArrayEmpty = goog.array.some(arguments, function(arr) { - return !arr.length; - }); - - // An empty set in a cartesian product gives an empty set. - if (someArrayEmpty || !arguments.length) { - return new goog.iter.Iterator(); - } - - var iter = new goog.iter.Iterator(); - var arrays = arguments; - - // The first indices are [0, 0, ...] - var indicies = goog.array.repeat(0, arrays.length); - - iter.next = function() { - - if (indicies) { - var retVal = goog.array.map(indicies, function(valueIndex, arrayIndex) { - return arrays[arrayIndex][valueIndex]; - }); - - // Generate the next-largest indices for the next call. - // Increase the rightmost index. If it goes over, increase the next - // rightmost (like carry-over addition). - for (var i = indicies.length - 1; i >= 0; i--) { - // Assertion prevents compiler warning below. - goog.asserts.assert(indicies); - if (indicies[i] < arrays[i].length - 1) { - indicies[i]++; - break; - } - - // We're at the last indices (the last element of every array), so - // the iteration is over on the next call. - if (i == 0) { - indicies = null; - break; - } - // Reset the index in this column and loop back to increment the - // next one. - indicies[i] = 0; - } - return retVal; - } - - throw goog.iter.StopIteration; - }; - - return iter; -}; - - -/** - * Create an iterator to cycle over the iterable's elements indefinitely. - * For example, ([1, 2, 3]) would return : 1, 2, 3, 1, 2, 3, ... - * @see: http://docs.python.org/library/itertools.html#itertools.cycle. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable object. - * @return {!goog.iter.Iterator<VALUE>} An iterator that iterates indefinitely - * over the values in {@code iterable}. - * @template VALUE - */ -goog.iter.cycle = function(iterable) { - var baseIterator = goog.iter.toIterator(iterable); - - // We maintain a cache to store the iterable elements as we iterate - // over them. The cache is used to return elements once we have - // iterated over the iterable once. - var cache = []; - var cacheIndex = 0; - - var iter = new goog.iter.Iterator(); - - // This flag is set after the iterable is iterated over once - var useCache = false; - - iter.next = function() { - var returnElement = null; - - // Pull elements off the original iterator if not using cache - if (!useCache) { - try { - // Return the element from the iterable - returnElement = baseIterator.next(); - cache.push(returnElement); - return returnElement; - } catch (e) { - // If an exception other than StopIteration is thrown - // or if there are no elements to iterate over (the iterable was empty) - // throw an exception - if (e != goog.iter.StopIteration || goog.array.isEmpty(cache)) { - throw e; - } - // set useCache to true after we know that a 'StopIteration' exception - // was thrown and the cache is not empty (to handle the 'empty iterable' - // use case) - useCache = true; - } - } - - returnElement = cache[cacheIndex]; - cacheIndex = (cacheIndex + 1) % cache.length; - - return returnElement; - }; - - return iter; -}; - - -/** - * Creates an iterator that counts indefinitely from a starting value. - * @see http://docs.python.org/2/library/itertools.html#itertools.count - * @param {number=} opt_start The starting value. Default is 0. - * @param {number=} opt_step The number to increment with between each call to - * next. Negative and floating point numbers are allowed. Default is 1. - * @return {!goog.iter.Iterator<number>} A new iterator that returns the values - * in the series. - */ -goog.iter.count = function(opt_start, opt_step) { - var counter = opt_start || 0; - var step = goog.isDef(opt_step) ? opt_step : 1; - var iter = new goog.iter.Iterator(); - - iter.next = function() { - var returnValue = counter; - counter += step; - return returnValue; - }; - - return iter; -}; - - -/** - * Creates an iterator that returns the same object or value repeatedly. - * @param {VALUE} value Any object or value to repeat. - * @return {!goog.iter.Iterator<VALUE>} A new iterator that returns the - * repeated value. - * @template VALUE - */ -goog.iter.repeat = function(value) { - var iter = new goog.iter.Iterator(); - - iter.next = goog.functions.constant(value); - - return iter; -}; - - -/** - * Creates an iterator that returns running totals from the numbers in - * {@code iterable}. For example, the array {@code [1, 2, 3, 4, 5]} yields - * {@code 1 -> 3 -> 6 -> 10 -> 15}. - * @see http://docs.python.org/3.2/library/itertools.html#itertools.accumulate - * @param {!goog.iter.Iterable<number>} iterable The iterable of numbers to - * accumulate. - * @return {!goog.iter.Iterator<number>} A new iterator that returns the - * numbers in the series. - */ -goog.iter.accumulate = function(iterable) { - var iterator = goog.iter.toIterator(iterable); - var total = 0; - var iter = new goog.iter.Iterator(); - - iter.next = function() { - total += iterator.next(); - return total; - }; - - return iter; -}; - - -/** - * Creates an iterator that returns arrays containing the ith elements from the - * provided iterables. The returned arrays will be the same size as the number - * of iterables given in {@code var_args}. Once the shortest iterable is - * exhausted, subsequent calls to {@code next()} will throw - * {@code goog.iter.StopIteration}. - * @see http://docs.python.org/2/library/itertools.html#itertools.izip - * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any - * number of iterable objects. - * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator that returns - * arrays of elements from the provided iterables. - * @template VALUE - */ -goog.iter.zip = function(var_args) { - var args = arguments; - var iter = new goog.iter.Iterator(); - - if (args.length > 0) { - var iterators = goog.array.map(args, goog.iter.toIterator); - iter.next = function() { - var arr = goog.array.map(iterators, function(it) { - return it.next(); - }); - return arr; - }; - } - - return iter; -}; - - -/** - * Creates an iterator that returns arrays containing the ith elements from the - * provided iterables. The returned arrays will be the same size as the number - * of iterables given in {@code var_args}. Shorter iterables will be extended - * with {@code fillValue}. Once the longest iterable is exhausted, subsequent - * calls to {@code next()} will throw {@code goog.iter.StopIteration}. - * @see http://docs.python.org/2/library/itertools.html#itertools.izip_longest - * @param {VALUE} fillValue The object or value used to fill shorter iterables. - * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any - * number of iterable objects. - * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator that returns - * arrays of elements from the provided iterables. - * @template VALUE - */ -goog.iter.zipLongest = function(fillValue, var_args) { - var args = goog.array.slice(arguments, 1); - var iter = new goog.iter.Iterator(); - - if (args.length > 0) { - var iterators = goog.array.map(args, goog.iter.toIterator); - - iter.next = function() { - var iteratorsHaveValues = false; // false when all iterators are empty. - var arr = goog.array.map(iterators, function(it) { - var returnValue; - try { - returnValue = it.next(); - // Iterator had a value, so we've not exhausted the iterators. - // Set flag accordingly. - iteratorsHaveValues = true; - } catch (ex) { - if (ex !== goog.iter.StopIteration) { - throw ex; - } - returnValue = fillValue; - } - return returnValue; - }); - - if (!iteratorsHaveValues) { - throw goog.iter.StopIteration; - } - return arr; - }; - } - - return iter; -}; - - -/** - * Creates an iterator that filters {@code iterable} based on a series of - * {@code selectors}. On each call to {@code next()}, one item is taken from - * both the {@code iterable} and {@code selectors} iterators. If the item from - * {@code selectors} evaluates to true, the item from {@code iterable} is given. - * Otherwise, it is skipped. Once either {@code iterable} or {@code selectors} - * is exhausted, subsequent calls to {@code next()} will throw - * {@code goog.iter.StopIteration}. - * @see http://docs.python.org/2/library/itertools.html#itertools.compress - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to filter. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} selectors An - * iterable of items to be evaluated in a boolean context to determine if - * the corresponding element in {@code iterable} should be included in the - * result. - * @return {!goog.iter.Iterator<VALUE>} A new iterator that returns the - * filtered values. - * @template VALUE - */ -goog.iter.compress = function(iterable, selectors) { - var selectorIterator = goog.iter.toIterator(selectors); - - return goog.iter.filter(iterable, function() { - return !!selectorIterator.next(); - }); -}; - - - -/** - * Implements the {@code goog.iter.groupBy} iterator. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to group. - * @param {function(...VALUE): KEY=} opt_keyFunc Optional function for - * determining the key value for each group in the {@code iterable}. Default - * is the identity function. - * @constructor - * @extends {goog.iter.Iterator<!Array<?>>} - * @template KEY, VALUE - * @private - */ -goog.iter.GroupByIterator_ = function(iterable, opt_keyFunc) { - - /** - * The iterable to group, coerced to an iterator. - * @type {!goog.iter.Iterator} - */ - this.iterator = goog.iter.toIterator(iterable); - - /** - * A function for determining the key value for each element in the iterable. - * If no function is provided, the identity function is used and returns the - * element unchanged. - * @type {function(...VALUE): KEY} - */ - this.keyFunc = opt_keyFunc || goog.functions.identity; - - /** - * The target key for determining the start of a group. - * @type {KEY} - */ - this.targetKey; - - /** - * The current key visited during iteration. - * @type {KEY} - */ - this.currentKey; - - /** - * The current value being added to the group. - * @type {VALUE} - */ - this.currentValue; -}; -goog.inherits(goog.iter.GroupByIterator_, goog.iter.Iterator); - - -/** @override */ -goog.iter.GroupByIterator_.prototype.next = function() { - while (this.currentKey == this.targetKey) { - this.currentValue = this.iterator.next(); // Exits on StopIteration - this.currentKey = this.keyFunc(this.currentValue); - } - this.targetKey = this.currentKey; - return [this.currentKey, this.groupItems_(this.targetKey)]; -}; - - -/** - * Performs the grouping of objects using the given key. - * @param {KEY} targetKey The target key object for the group. - * @return {!Array<VALUE>} An array of grouped objects. - * @private - */ -goog.iter.GroupByIterator_.prototype.groupItems_ = function(targetKey) { - var arr = []; - while (this.currentKey == targetKey) { - arr.push(this.currentValue); - try { - this.currentValue = this.iterator.next(); - } catch (ex) { - if (ex !== goog.iter.StopIteration) { - throw ex; - } - break; - } - this.currentKey = this.keyFunc(this.currentValue); - } - return arr; -}; - - -/** - * Creates an iterator that returns arrays containing elements from the - * {@code iterable} grouped by a key value. For iterables with repeated - * elements (i.e. sorted according to a particular key function), this function - * has a {@code uniq}-like effect. For example, grouping the array: - * {@code [A, B, B, C, C, A]} produces - * {@code [A, [A]], [B, [B, B]], [C, [C, C]], [A, [A]]}. - * @see http://docs.python.org/2/library/itertools.html#itertools.groupby - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to group. - * @param {function(...VALUE): KEY=} opt_keyFunc Optional function for - * determining the key value for each group in the {@code iterable}. Default - * is the identity function. - * @return {!goog.iter.Iterator<!Array<?>>} A new iterator that returns - * arrays of consecutive key and groups. - * @template KEY, VALUE - */ -goog.iter.groupBy = function(iterable, opt_keyFunc) { - return new goog.iter.GroupByIterator_(iterable, opt_keyFunc); -}; - - -/** - * Gives an iterator that gives the result of calling the given function - * <code>f</code> with the arguments taken from the next element from - * <code>iterable</code> (the elements are expected to also be iterables). - * - * Similar to {@see goog.iter#map} but allows the function to accept multiple - * arguments from the iterable. - * - * @param {!goog.iter.Iterable<!goog.iter.Iterable>} iterable The iterable of - * iterables to iterate over. - * @param {function(this:THIS,...*):RESULT} f The function to call for every - * element. This function takes N+2 arguments, where N represents the - * number of items from the next element of the iterable. The two - * additional arguments passed to the function are undefined and the - * iterator itself. The function should return a new value. - * @param {THIS=} opt_obj The object to be used as the value of 'this' within - * {@code f}. - * @return {!goog.iter.Iterator<RESULT>} A new iterator that returns the - * results of applying the function to each element in the original - * iterator. - * @template THIS, RESULT - */ -goog.iter.starMap = function(iterable, f, opt_obj) { - var iterator = goog.iter.toIterator(iterable); - var iter = new goog.iter.Iterator(); - - iter.next = function() { - var args = goog.iter.toArray(iterator.next()); - return f.apply(opt_obj, goog.array.concat(args, undefined, iterator)); - }; - - return iter; -}; - - -/** - * Returns an array of iterators each of which can iterate over the values in - * {@code iterable} without advancing the others. - * @see http://docs.python.org/2/library/itertools.html#itertools.tee - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to tee. - * @param {number=} opt_num The number of iterators to create. Default is 2. - * @return {!Array<goog.iter.Iterator<VALUE>>} An array of iterators. - * @template VALUE - */ -goog.iter.tee = function(iterable, opt_num) { - var iterator = goog.iter.toIterator(iterable); - var num = goog.isNumber(opt_num) ? opt_num : 2; - var buffers = goog.array.map(goog.array.range(num), function() { - return []; - }); - - var addNextIteratorValueToBuffers = function() { - var val = iterator.next(); - goog.array.forEach(buffers, function(buffer) { - buffer.push(val); - }); - }; - - var createIterator = function(buffer) { - // Each tee'd iterator has an associated buffer (initially empty). When a - // tee'd iterator's buffer is empty, it calls - // addNextIteratorValueToBuffers(), adding the next value to all tee'd - // iterators' buffers, and then returns that value. This allows each - // iterator to be advanced independently. - var iter = new goog.iter.Iterator(); - - iter.next = function() { - if (goog.array.isEmpty(buffer)) { - addNextIteratorValueToBuffers(); - } - goog.asserts.assert(!goog.array.isEmpty(buffer)); - return buffer.shift(); - }; - - return iter; - }; - - return goog.array.map(buffers, createIterator); -}; - - -/** - * Creates an iterator that returns arrays containing a count and an element - * obtained from the given {@code iterable}. - * @see http://docs.python.org/2/library/functions.html#enumerate - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to enumerate. - * @param {number=} opt_start Optional starting value. Default is 0. - * @return {!goog.iter.Iterator<!Array<?>>} A new iterator containing - * count/item pairs. - * @template VALUE - */ -goog.iter.enumerate = function(iterable, opt_start) { - return goog.iter.zip(goog.iter.count(opt_start), iterable); -}; - - -/** - * Creates an iterator that returns the first {@code limitSize} elements from an - * iterable. If this number is greater than the number of elements in the - * iterable, all the elements are returned. - * @see http://goo.gl/V0sihp Inspired by the limit iterator in Guava. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to limit. - * @param {number} limitSize The maximum number of elements to return. - * @return {!goog.iter.Iterator<VALUE>} A new iterator containing - * {@code limitSize} elements. - * @template VALUE - */ -goog.iter.limit = function(iterable, limitSize) { - goog.asserts.assert(goog.math.isInt(limitSize) && limitSize >= 0); - - var iterator = goog.iter.toIterator(iterable); - - var iter = new goog.iter.Iterator(); - var remaining = limitSize; - - iter.next = function() { - if (remaining-- > 0) { - return iterator.next(); - } - throw goog.iter.StopIteration; - }; - - return iter; -}; - - -/** - * Creates an iterator that is advanced {@code count} steps ahead. Consumed - * values are silently discarded. If {@code count} is greater than the number - * of elements in {@code iterable}, an empty iterator is returned. Subsequent - * calls to {@code next()} will throw {@code goog.iter.StopIteration}. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to consume. - * @param {number} count The number of elements to consume from the iterator. - * @return {!goog.iter.Iterator<VALUE>} An iterator advanced zero or more steps - * ahead. - * @template VALUE - */ -goog.iter.consume = function(iterable, count) { - goog.asserts.assert(goog.math.isInt(count) && count >= 0); - - var iterator = goog.iter.toIterator(iterable); - - while (count-- > 0) { - goog.iter.nextOrValue(iterator, null); - } - - return iterator; -}; - - -/** - * Creates an iterator that returns a range of elements from an iterable. - * Similar to {@see goog.array#slice} but does not support negative indexes. - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to slice. - * @param {number} start The index of the first element to return. - * @param {number=} opt_end The index after the last element to return. If - * defined, must be greater than or equal to {@code start}. - * @return {!goog.iter.Iterator<VALUE>} A new iterator containing a slice of - * the original. - * @template VALUE - */ -goog.iter.slice = function(iterable, start, opt_end) { - goog.asserts.assert(goog.math.isInt(start) && start >= 0); - - var iterator = goog.iter.consume(iterable, start); - - if (goog.isNumber(opt_end)) { - goog.asserts.assert( - goog.math.isInt(/** @type {number} */ (opt_end)) && opt_end >= start); - iterator = goog.iter.limit(iterator, opt_end - start /* limitSize */); - } - - return iterator; -}; - - -/** - * Checks an array for duplicate elements. - * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to check for - * duplicates. - * @return {boolean} True, if the array contains duplicates, false otherwise. - * @private - * @template VALUE - */ -// TODO(user): Consider moving this into goog.array as a public function. -goog.iter.hasDuplicates_ = function(arr) { - var deduped = []; - goog.array.removeDuplicates(arr, deduped); - return arr.length != deduped.length; -}; - - -/** - * Creates an iterator that returns permutations of elements in - * {@code iterable}. - * - * Permutations are obtained by taking the Cartesian product of - * {@code opt_length} iterables and filtering out those with repeated - * elements. For example, the permutations of {@code [1,2,3]} are - * {@code [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]}. - * @see http://docs.python.org/2/library/itertools.html#itertools.permutations - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable from which to generate permutations. - * @param {number=} opt_length Length of each permutation. If omitted, defaults - * to the length of {@code iterable}. - * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing the - * permutations of {@code iterable}. - * @template VALUE - */ -goog.iter.permutations = function(iterable, opt_length) { - var elements = goog.iter.toArray(iterable); - var length = goog.isNumber(opt_length) ? opt_length : elements.length; - - var sets = goog.array.repeat(elements, length); - var product = goog.iter.product.apply(undefined, sets); - - return goog.iter.filter(product, function(arr) { - return !goog.iter.hasDuplicates_(arr); - }); -}; - - -/** - * Creates an iterator that returns combinations of elements from - * {@code iterable}. - * - * Combinations are obtained by taking the {@see goog.iter#permutations} of - * {@code iterable} and filtering those whose elements appear in the order they - * are encountered in {@code iterable}. For example, the 3-length combinations - * of {@code [0,1,2,3]} are {@code [[0,1,2], [0,1,3], [0,2,3], [1,2,3]]}. - * @see http://docs.python.org/2/library/itertools.html#itertools.combinations - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable from which to generate combinations. - * @param {number} length The length of each combination. - * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing - * combinations from the {@code iterable}. - * @template VALUE - */ -goog.iter.combinations = function(iterable, length) { - var elements = goog.iter.toArray(iterable); - var indexes = goog.iter.range(elements.length); - var indexIterator = goog.iter.permutations(indexes, length); - // sortedIndexIterator will now give arrays of with the given length that - // indicate what indexes into "elements" should be returned on each iteration. - var sortedIndexIterator = goog.iter.filter(indexIterator, function(arr) { - return goog.array.isSorted(arr); - }); - - var iter = new goog.iter.Iterator(); - - function getIndexFromElements(index) { - return elements[index]; - } - - iter.next = function() { - return goog.array.map( - /** @type {!Array<number>} */ - (sortedIndexIterator.next()), getIndexFromElements); - }; - - return iter; -}; - - -/** - * Creates an iterator that returns combinations of elements from - * {@code iterable}, with repeated elements possible. - * - * Combinations are obtained by taking the Cartesian product of {@code length} - * iterables and filtering those whose elements appear in the order they are - * encountered in {@code iterable}. For example, the 2-length combinations of - * {@code [1,2,3]} are {@code [[1,1], [1,2], [1,3], [2,2], [2,3], [3,3]]}. - * @see http://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement - * @see http://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition - * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The - * iterable to combine. - * @param {number} length The length of each combination. - * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing - * combinations from the {@code iterable}. - * @template VALUE - */ -goog.iter.combinationsWithReplacement = function(iterable, length) { - var elements = goog.iter.toArray(iterable); - var indexes = goog.array.range(elements.length); - var sets = goog.array.repeat(indexes, length); - var indexIterator = goog.iter.product.apply(undefined, sets); - // sortedIndexIterator will now give arrays of with the given length that - // indicate what indexes into "elements" should be returned on each iteration. - var sortedIndexIterator = goog.iter.filter(indexIterator, function(arr) { - return goog.array.isSorted(arr); - }); - - var iter = new goog.iter.Iterator(); - - function getIndexFromElements(index) { - return elements[index]; - } - - iter.next = function() { - return goog.array.map( - /** @type {!Array<number>} */ - (sortedIndexIterator.next()), getIndexFromElements); - }; - - return iter; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/browser.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/browser.js deleted file mode 100644 index 7f64e42..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/browser.js +++ /dev/null @@ -1,327 +0,0 @@ -// 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 Closure user agent detection (Browser). - * @see <a href="http://www.useragentstring.com/">User agent strings</a> - * For more information on rendering engine, platform, or device see the other - * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform, - * goog.labs.userAgent.device respectively.) - * - * @author martone@google.com (Andy Martone) - */ - -goog.provide('goog.labs.userAgent.browser'); - -goog.require('goog.array'); -goog.require('goog.labs.userAgent.util'); -goog.require('goog.object'); -goog.require('goog.string'); - - -// TODO(nnaze): Refactor to remove excessive exclusion logic in matching -// functions. - - -/** - * @return {boolean} Whether the user's browser is Opera. - * @private - */ -goog.labs.userAgent.browser.matchOpera_ = function() { - return goog.labs.userAgent.util.matchUserAgent('Opera') || - goog.labs.userAgent.util.matchUserAgent('OPR'); -}; - - -/** - * @return {boolean} Whether the user's browser is IE. - * @private - */ -goog.labs.userAgent.browser.matchIE_ = function() { - return goog.labs.userAgent.util.matchUserAgent('Edge') || - goog.labs.userAgent.util.matchUserAgent('Trident') || - goog.labs.userAgent.util.matchUserAgent('MSIE'); -}; - - -/** - * @return {boolean} Whether the user's browser is Firefox. - * @private - */ -goog.labs.userAgent.browser.matchFirefox_ = function() { - return goog.labs.userAgent.util.matchUserAgent('Firefox'); -}; - - -/** - * @return {boolean} Whether the user's browser is Safari. - * @private - */ -goog.labs.userAgent.browser.matchSafari_ = function() { - return goog.labs.userAgent.util.matchUserAgent('Safari') && - !(goog.labs.userAgent.browser.matchChrome_() || - goog.labs.userAgent.browser.matchCoast_() || - goog.labs.userAgent.browser.matchOpera_() || - goog.labs.userAgent.browser.matchIE_() || - goog.labs.userAgent.browser.isSilk() || - goog.labs.userAgent.util.matchUserAgent('Android')); -}; - - -/** - * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based - * iOS browser). - * @private - */ -goog.labs.userAgent.browser.matchCoast_ = function() { - return goog.labs.userAgent.util.matchUserAgent('Coast'); -}; - - -/** - * @return {boolean} Whether the user's browser is iOS Webview. - * @private - */ -goog.labs.userAgent.browser.matchIosWebview_ = function() { - // iOS Webview does not show up as Chrome or Safari. Also check for Opera's - // WebKit-based iOS browser, Coast. - return (goog.labs.userAgent.util.matchUserAgent('iPad') || - goog.labs.userAgent.util.matchUserAgent('iPhone')) && - !goog.labs.userAgent.browser.matchSafari_() && - !goog.labs.userAgent.browser.matchChrome_() && - !goog.labs.userAgent.browser.matchCoast_() && - goog.labs.userAgent.util.matchUserAgent('AppleWebKit'); -}; - - -/** - * @return {boolean} Whether the user's browser is Chrome. - * @private - */ -goog.labs.userAgent.browser.matchChrome_ = function() { - return (goog.labs.userAgent.util.matchUserAgent('Chrome') || - goog.labs.userAgent.util.matchUserAgent('CriOS')) && - !goog.labs.userAgent.browser.matchOpera_() && - !goog.labs.userAgent.browser.matchIE_(); -}; - - -/** - * @return {boolean} Whether the user's browser is the Android browser. - * @private - */ -goog.labs.userAgent.browser.matchAndroidBrowser_ = function() { - // Android can appear in the user agent string for Chrome on Android. - // This is not the Android standalone browser if it does. - return goog.labs.userAgent.util.matchUserAgent('Android') && - !(goog.labs.userAgent.browser.isChrome() || - goog.labs.userAgent.browser.isFirefox() || - goog.labs.userAgent.browser.isOpera() || - goog.labs.userAgent.browser.isSilk()); -}; - - -/** - * @return {boolean} Whether the user's browser is Opera. - */ -goog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_; - - -/** - * @return {boolean} Whether the user's browser is IE. - */ -goog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_; - - -/** - * @return {boolean} Whether the user's browser is Firefox. - */ -goog.labs.userAgent.browser.isFirefox = - goog.labs.userAgent.browser.matchFirefox_; - - -/** - * @return {boolean} Whether the user's browser is Safari. - */ -goog.labs.userAgent.browser.isSafari = - goog.labs.userAgent.browser.matchSafari_; - - -/** - * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based - * iOS browser). - */ -goog.labs.userAgent.browser.isCoast = - goog.labs.userAgent.browser.matchCoast_; - - -/** - * @return {boolean} Whether the user's browser is iOS Webview. - */ -goog.labs.userAgent.browser.isIosWebview = - goog.labs.userAgent.browser.matchIosWebview_; - - -/** - * @return {boolean} Whether the user's browser is Chrome. - */ -goog.labs.userAgent.browser.isChrome = - goog.labs.userAgent.browser.matchChrome_; - - -/** - * @return {boolean} Whether the user's browser is the Android browser. - */ -goog.labs.userAgent.browser.isAndroidBrowser = - goog.labs.userAgent.browser.matchAndroidBrowser_; - - -/** - * For more information, see: - * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html - * @return {boolean} Whether the user's browser is Silk. - */ -goog.labs.userAgent.browser.isSilk = function() { - return goog.labs.userAgent.util.matchUserAgent('Silk'); -}; - - -/** - * @return {string} The browser version or empty string if version cannot be - * determined. Note that for Internet Explorer, this returns the version of - * the browser, not the version of the rendering engine. (IE 8 in - * compatibility mode will return 8.0 rather than 7.0. To determine the - * rendering engine version, look at document.documentMode instead. See - * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more - * details.) - */ -goog.labs.userAgent.browser.getVersion = function() { - var userAgentString = goog.labs.userAgent.util.getUserAgent(); - // Special case IE since IE's version is inside the parenthesis and - // without the '/'. - if (goog.labs.userAgent.browser.isIE()) { - return goog.labs.userAgent.browser.getIEVersion_(userAgentString); - } - - var versionTuples = goog.labs.userAgent.util.extractVersionTuples( - userAgentString); - - // Construct a map for easy lookup. - var versionMap = {}; - goog.array.forEach(versionTuples, function(tuple) { - // Note that the tuple is of length three, but we only care about the - // first two. - var key = tuple[0]; - var value = tuple[1]; - versionMap[key] = value; - }); - - var versionMapHasKey = goog.partial(goog.object.containsKey, versionMap); - - // Gives the value with the first key it finds, otherwise empty string. - function lookUpValueWithKeys(keys) { - var key = goog.array.find(keys, versionMapHasKey); - return versionMap[key] || ''; - } - - // Check Opera before Chrome since Opera 15+ has "Chrome" in the string. - // See - // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond - if (goog.labs.userAgent.browser.isOpera()) { - // Opera 10 has Version/10.0 but Opera/9.8, so look for "Version" first. - // Opera uses 'OPR' for more recent UAs. - return lookUpValueWithKeys(['Version', 'Opera', 'OPR']); - } - - if (goog.labs.userAgent.browser.isChrome()) { - return lookUpValueWithKeys(['Chrome', 'CriOS']); - } - - // Usually products browser versions are in the third tuple after "Mozilla" - // and the engine. - var tuple = versionTuples[2]; - return tuple && tuple[1] || ''; -}; - - -/** - * @param {string|number} version The version to check. - * @return {boolean} Whether the browser version is higher or the same as the - * given version. - */ -goog.labs.userAgent.browser.isVersionOrHigher = function(version) { - return goog.string.compareVersions(goog.labs.userAgent.browser.getVersion(), - version) >= 0; -}; - - -/** - * Determines IE version. More information: - * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString - * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx - * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx - * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx - * - * @param {string} userAgent the User-Agent. - * @return {string} - * @private - */ -goog.labs.userAgent.browser.getIEVersion_ = function(userAgent) { - // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade - // bug. Example UA: - // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) - // like Gecko. - // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments. - var rv = /rv: *([\d\.]*)/.exec(userAgent); - if (rv && rv[1]) { - return rv[1]; - } - - var edge = /Edge\/([\d\.]+)/.exec(userAgent); - if (edge) { - return edge[1]; - } - - var version = ''; - var msie = /MSIE +([\d\.]+)/.exec(userAgent); - if (msie && msie[1]) { - // IE in compatibility mode usually identifies itself as MSIE 7.0; in this - // case, use the Trident version to determine the version of IE. For more - // details, see the links above. - var tridentVersion = /Trident\/(\d.\d)/.exec(userAgent); - if (msie[1] == '7.0') { - if (tridentVersion && tridentVersion[1]) { - switch (tridentVersion[1]) { - case '4.0': - version = '8.0'; - break; - case '5.0': - version = '9.0'; - break; - case '6.0': - version = '10.0'; - break; - case '7.0': - version = '11.0'; - break; - } - } else { - version = '7.0'; - } - } else { - version = msie[1]; - } - } - return version; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/engine.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/engine.js deleted file mode 100644 index bea9b69..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/engine.js +++ /dev/null @@ -1,160 +0,0 @@ -// 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 Closure user agent detection. - * @see http://en.wikipedia.org/wiki/User_agent - * For more information on browser brand, platform, or device see the other - * sub-namespaces in goog.labs.userAgent (browser, platform, and device). - * - */ - -goog.provide('goog.labs.userAgent.engine'); - -goog.require('goog.array'); -goog.require('goog.labs.userAgent.util'); -goog.require('goog.string'); - - -/** - * @return {boolean} Whether the rendering engine is Presto. - */ -goog.labs.userAgent.engine.isPresto = function() { - return goog.labs.userAgent.util.matchUserAgent('Presto'); -}; - - -/** - * @return {boolean} Whether the rendering engine is Trident. - */ -goog.labs.userAgent.engine.isTrident = function() { - // IE only started including the Trident token in IE8. - return goog.labs.userAgent.util.matchUserAgent('Trident') || - goog.labs.userAgent.util.matchUserAgent('MSIE'); -}; - - -/** - * @return {boolean} Whether the rendering engine is Edge. - */ -goog.labs.userAgent.engine.isEdge = function() { - return goog.labs.userAgent.util.matchUserAgent('Edge'); -}; - - -/** - * @return {boolean} Whether the rendering engine is WebKit. - */ -goog.labs.userAgent.engine.isWebKit = function() { - return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') && - !goog.labs.userAgent.engine.isEdge(); -}; - - -/** - * @return {boolean} Whether the rendering engine is Gecko. - */ -goog.labs.userAgent.engine.isGecko = function() { - return goog.labs.userAgent.util.matchUserAgent('Gecko') && - !goog.labs.userAgent.engine.isWebKit() && - !goog.labs.userAgent.engine.isTrident() && - !goog.labs.userAgent.engine.isEdge(); -}; - - -/** - * @return {string} The rendering engine's version or empty string if version - * can't be determined. - */ -goog.labs.userAgent.engine.getVersion = function() { - var userAgentString = goog.labs.userAgent.util.getUserAgent(); - if (userAgentString) { - var tuples = goog.labs.userAgent.util.extractVersionTuples( - userAgentString); - - var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples); - if (engineTuple) { - // In Gecko, the version string is either in the browser info or the - // Firefox version. See Gecko user agent string reference: - // http://goo.gl/mULqa - if (engineTuple[0] == 'Gecko') { - return goog.labs.userAgent.engine.getVersionForKey_( - tuples, 'Firefox'); - } - - return engineTuple[1]; - } - - // MSIE has only one version identifier, and the Trident version is - // specified in the parenthetical. IE Edge is covered in the engine tuple - // detection. - var browserTuple = tuples[0]; - var info; - if (browserTuple && (info = browserTuple[2])) { - var match = /Trident\/([^\s;]+)/.exec(info); - if (match) { - return match[1]; - } - } - } - return ''; -}; - - -/** - * @param {!Array.<!Array.<string>>} tuples Extracted version tuples. - * @return {!Array.<string>|undefined} The engine tuple or undefined if not - * found. - * @private - */ -goog.labs.userAgent.engine.getEngineTuple_ = function(tuples) { - if (!goog.labs.userAgent.engine.isEdge()) { - return tuples[1]; - } - for (var i = 0; i < tuples.length; i++) { - var tuple = tuples[i]; - if (tuple[0] == 'Edge') { - return tuple; - } - } -}; - - -/** - * @param {string|number} version The version to check. - * @return {boolean} Whether the rendering engine version is higher or the same - * as the given version. - */ -goog.labs.userAgent.engine.isVersionOrHigher = function(version) { - return goog.string.compareVersions(goog.labs.userAgent.engine.getVersion(), - version) >= 0; -}; - - -/** - * @param {!Array<!Array<string>>} tuples Version tuples. - * @param {string} key The key to look for. - * @return {string} The version string of the given key, if present. - * Otherwise, the empty string. - * @private - */ -goog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) { - // TODO(nnaze): Move to util if useful elsewhere. - - var pair = goog.array.find(tuples, function(pair) { - return key == pair[0]; - }); - - return pair && pair[1] || ''; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/platform.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/platform.js deleted file mode 100644 index ece7c07..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/platform.js +++ /dev/null @@ -1,160 +0,0 @@ -// 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 Closure user agent platform detection. - * @see <a href="http://www.useragentstring.com/">User agent strings</a> - * For more information on browser brand, rendering engine, or device see the - * other sub-namespaces in goog.labs.userAgent (browser, engine, and device - * respectively). - * - */ - -goog.provide('goog.labs.userAgent.platform'); - -goog.require('goog.labs.userAgent.util'); -goog.require('goog.string'); - - -/** - * @return {boolean} Whether the platform is Android. - */ -goog.labs.userAgent.platform.isAndroid = function() { - return goog.labs.userAgent.util.matchUserAgent('Android'); -}; - - -/** - * @return {boolean} Whether the platform is iPod. - */ -goog.labs.userAgent.platform.isIpod = function() { - return goog.labs.userAgent.util.matchUserAgent('iPod'); -}; - - -/** - * @return {boolean} Whether the platform is iPhone. - */ -goog.labs.userAgent.platform.isIphone = function() { - return goog.labs.userAgent.util.matchUserAgent('iPhone') && - !goog.labs.userAgent.util.matchUserAgent('iPod') && - !goog.labs.userAgent.util.matchUserAgent('iPad'); -}; - - -/** - * @return {boolean} Whether the platform is iPad. - */ -goog.labs.userAgent.platform.isIpad = function() { - return goog.labs.userAgent.util.matchUserAgent('iPad'); -}; - - -/** - * @return {boolean} Whether the platform is iOS. - */ -goog.labs.userAgent.platform.isIos = function() { - return goog.labs.userAgent.platform.isIphone() || - goog.labs.userAgent.platform.isIpad() || - goog.labs.userAgent.platform.isIpod(); -}; - - -/** - * @return {boolean} Whether the platform is Mac. - */ -goog.labs.userAgent.platform.isMacintosh = function() { - return goog.labs.userAgent.util.matchUserAgent('Macintosh'); -}; - - -/** - * Note: ChromeOS is not considered to be Linux as it does not report itself - * as Linux in the user agent string. - * @return {boolean} Whether the platform is Linux. - */ -goog.labs.userAgent.platform.isLinux = function() { - return goog.labs.userAgent.util.matchUserAgent('Linux'); -}; - - -/** - * @return {boolean} Whether the platform is Windows. - */ -goog.labs.userAgent.platform.isWindows = function() { - return goog.labs.userAgent.util.matchUserAgent('Windows'); -}; - - -/** - * @return {boolean} Whether the platform is ChromeOS. - */ -goog.labs.userAgent.platform.isChromeOS = function() { - return goog.labs.userAgent.util.matchUserAgent('CrOS'); -}; - - -/** - * The version of the platform. We only determine the version for Windows, - * Mac, and Chrome OS. It doesn't make much sense on Linux. For Windows, we only - * look at the NT version. Non-NT-based versions (e.g. 95, 98, etc.) are given - * version 0.0. - * - * @return {string} The platform version or empty string if version cannot be - * determined. - */ -goog.labs.userAgent.platform.getVersion = function() { - var userAgentString = goog.labs.userAgent.util.getUserAgent(); - var version = '', re; - if (goog.labs.userAgent.platform.isWindows()) { - re = /Windows (?:NT|Phone) ([0-9.]+)/; - var match = re.exec(userAgentString); - if (match) { - version = match[1]; - } else { - version = '0.0'; - } - } else if (goog.labs.userAgent.platform.isIos()) { - re = /(?:iPhone|iPod|iPad|CPU)\s+OS\s+(\S+)/; - var match = re.exec(userAgentString); - // Report the version as x.y.z and not x_y_z - version = match && match[1].replace(/_/g, '.'); - } else if (goog.labs.userAgent.platform.isMacintosh()) { - re = /Mac OS X ([0-9_.]+)/; - var match = re.exec(userAgentString); - // Note: some old versions of Camino do not report an OSX version. - // Default to 10. - version = match ? match[1].replace(/_/g, '.') : '10'; - } else if (goog.labs.userAgent.platform.isAndroid()) { - re = /Android\s+([^\);]+)(\)|;)/; - var match = re.exec(userAgentString); - version = match && match[1]; - } else if (goog.labs.userAgent.platform.isChromeOS()) { - re = /(?:CrOS\s+(?:i686|x86_64)\s+([0-9.]+))/; - var match = re.exec(userAgentString); - version = match && match[1]; - } - return version || ''; -}; - - -/** - * @param {string|number} version The version to check. - * @return {boolean} Whether the browser version is higher or the same as the - * given version. - */ -goog.labs.userAgent.platform.isVersionOrHigher = function(version) { - return goog.string.compareVersions(goog.labs.userAgent.platform.getVersion(), - version) >= 0; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/util.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/util.js deleted file mode 100644 index ebba9b5..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/labs/useragent/util.js +++ /dev/null @@ -1,148 +0,0 @@ -// 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 Utilities used by goog.labs.userAgent tools. These functions - * should not be used outside of goog.labs.userAgent.*. - * - * - * @author nnaze@google.com (Nathan Naze) - */ - -goog.provide('goog.labs.userAgent.util'); - -goog.require('goog.string'); - - -/** - * Gets the native userAgent string from navigator if it exists. - * If navigator or navigator.userAgent string is missing, returns an empty - * string. - * @return {string} - * @private - */ -goog.labs.userAgent.util.getNativeUserAgentString_ = function() { - var navigator = goog.labs.userAgent.util.getNavigator_(); - if (navigator) { - var userAgent = navigator.userAgent; - if (userAgent) { - return userAgent; - } - } - return ''; -}; - - -/** - * Getter for the native navigator. - * This is a separate function so it can be stubbed out in testing. - * @return {Navigator} - * @private - */ -goog.labs.userAgent.util.getNavigator_ = function() { - return goog.global.navigator; -}; - - -/** - * A possible override for applications which wish to not check - * navigator.userAgent but use a specified value for detection instead. - * @private {string} - */ -goog.labs.userAgent.util.userAgent_ = - goog.labs.userAgent.util.getNativeUserAgentString_(); - - -/** - * Applications may override browser detection on the built in - * navigator.userAgent object by setting this string. Set to null to use the - * browser object instead. - * @param {?string=} opt_userAgent The User-Agent override. - */ -goog.labs.userAgent.util.setUserAgent = function(opt_userAgent) { - goog.labs.userAgent.util.userAgent_ = opt_userAgent || - goog.labs.userAgent.util.getNativeUserAgentString_(); -}; - - -/** - * @return {string} The user agent string. - */ -goog.labs.userAgent.util.getUserAgent = function() { - return goog.labs.userAgent.util.userAgent_; -}; - - -/** - * @param {string} str - * @return {boolean} Whether the user agent contains the given string, ignoring - * case. - */ -goog.labs.userAgent.util.matchUserAgent = function(str) { - var userAgent = goog.labs.userAgent.util.getUserAgent(); - return goog.string.contains(userAgent, str); -}; - - -/** - * @param {string} str - * @return {boolean} Whether the user agent contains the given string. - */ -goog.labs.userAgent.util.matchUserAgentIgnoreCase = function(str) { - var userAgent = goog.labs.userAgent.util.getUserAgent(); - return goog.string.caseInsensitiveContains(userAgent, str); -}; - - -/** - * Parses the user agent into tuples for each section. - * @param {string} userAgent - * @return {!Array<!Array<string>>} Tuples of key, version, and the contents - * of the parenthetical. - */ -goog.labs.userAgent.util.extractVersionTuples = function(userAgent) { - // Matches each section of a user agent string. - // Example UA: - // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) - // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 - // This has three version tuples: Mozilla, AppleWebKit, and Mobile. - - var versionRegExp = new RegExp( - // Key. Note that a key may have a space. - // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0') - '(\\w[\\w ]+)' + - - '/' + // slash - '([^\\s]+)' + // version (i.e. '5.0b') - '\\s*' + // whitespace - '(?:\\((.*?)\\))?', // parenthetical info. parentheses not matched. - 'g'); - - var data = []; - var match; - - // Iterate and collect the version tuples. Each iteration will be the - // next regex match. - while (match = versionRegExp.exec(userAgent)) { - data.push([ - match[1], // key - match[2], // value - // || undefined as this is not undefined in IE7 and IE8 - match[3] || undefined // info - ]); - } - - return data; -}; - diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/log/log.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/log/log.js deleted file mode 100644 index b93d835..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/log/log.js +++ /dev/null @@ -1,197 +0,0 @@ -// 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 Basic strippable logging definitions. - * @see http://go/closurelogging - * - * @author johnlenz@google.com (John Lenz) - */ - -goog.provide('goog.log'); -goog.provide('goog.log.Level'); -goog.provide('goog.log.LogRecord'); -goog.provide('goog.log.Logger'); - -goog.require('goog.debug'); -goog.require('goog.debug.LogManager'); -goog.require('goog.debug.LogRecord'); -goog.require('goog.debug.Logger'); - - -/** @define {boolean} Whether logging is enabled. */ -goog.define('goog.log.ENABLED', goog.debug.LOGGING_ENABLED); - - -/** @const */ -goog.log.ROOT_LOGGER_NAME = goog.debug.Logger.ROOT_LOGGER_NAME; - - - -/** - * @constructor - * @final - */ -goog.log.Logger = goog.debug.Logger; - - - -/** - * @constructor - * @final - */ -goog.log.Level = goog.debug.Logger.Level; - - - -/** - * @constructor - * @final - */ -goog.log.LogRecord = goog.debug.LogRecord; - - -/** - * Finds or creates a logger for a named subsystem. If a logger has already been - * created with the given name it is returned. Otherwise a new logger is - * created. If a new logger is created its log level will be configured based - * on the goog.debug.LogManager configuration and it will configured to also - * send logging output to its parent's handlers. - * @see goog.debug.LogManager - * - * @param {string} name A name for the logger. This should be a dot-separated - * name and should normally be based on the package name or class name of - * the subsystem, such as goog.net.BrowserChannel. - * @param {goog.log.Level=} opt_level If provided, override the - * default logging level with the provided level. - * @return {goog.log.Logger} The named logger or null if logging is disabled. - */ -goog.log.getLogger = function(name, opt_level) { - if (goog.log.ENABLED) { - var logger = goog.debug.LogManager.getLogger(name); - if (opt_level && logger) { - logger.setLevel(opt_level); - } - return logger; - } else { - return null; - } -}; - - -// TODO(johnlenz): try to tighten the types to these functions. -/** - * Adds a handler to the logger. This doesn't use the event system because - * we want to be able to add logging to the event system. - * @param {goog.log.Logger} logger - * @param {Function} handler Handler function to add. - */ -goog.log.addHandler = function(logger, handler) { - if (goog.log.ENABLED && logger) { - logger.addHandler(handler); - } -}; - - -/** - * Removes a handler from the logger. This doesn't use the event system because - * we want to be able to add logging to the event system. - * @param {goog.log.Logger} logger - * @param {Function} handler Handler function to remove. - * @return {boolean} Whether the handler was removed. - */ -goog.log.removeHandler = function(logger, handler) { - if (goog.log.ENABLED && logger) { - return logger.removeHandler(handler); - } else { - return false; - } -}; - - -/** - * Logs a message. If the logger is currently enabled for the - * given message level then the given message is forwarded to all the - * registered output Handler objects. - * @param {goog.log.Logger} logger - * @param {goog.log.Level} level One of the level identifiers. - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error|Object=} opt_exception An exception associated with the - * message. - */ -goog.log.log = function(logger, level, msg, opt_exception) { - if (goog.log.ENABLED && logger) { - logger.log(level, msg, opt_exception); - } -}; - - -/** - * Logs a message at the Level.SEVERE level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.log.Logger} logger - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.log.error = function(logger, msg, opt_exception) { - if (goog.log.ENABLED && logger) { - logger.severe(msg, opt_exception); - } -}; - - -/** - * Logs a message at the Level.WARNING level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.log.Logger} logger - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.log.warning = function(logger, msg, opt_exception) { - if (goog.log.ENABLED && logger) { - logger.warning(msg, opt_exception); - } -}; - - -/** - * Logs a message at the Level.INFO level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.log.Logger} logger - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.log.info = function(logger, msg, opt_exception) { - if (goog.log.ENABLED && logger) { - logger.info(msg, opt_exception); - } -}; - - -/** - * Logs a message at the Level.Fine level. - * If the logger is currently enabled for the given message level then the - * given message is forwarded to all the registered output Handler objects. - * @param {goog.log.Logger} logger - * @param {goog.debug.Loggable} msg The message to log. - * @param {Error=} opt_exception An exception associated with the message. - */ -goog.log.fine = function(logger, msg, opt_exception) { - if (goog.log.ENABLED && logger) { - logger.fine(msg, opt_exception); - } -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/box.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/box.js deleted file mode 100644 index 63ebc0d..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/box.js +++ /dev/null @@ -1,389 +0,0 @@ -// 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. - * - * This class assumes 'screen coordinates': larger Y coordinates are further - * from the top of the screen. - * - * @param {number} top Top. - * @param {number} right Right. - * @param {number} bottom Bottom. - * @param {number} left Left. - * @struct - * @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; -}; - - -/** - * @return {number} width The width of this Box. - */ -goog.math.Box.prototype.getWidth = function() { - return this.right - this.left; -}; - - -/** - * @return {number} height The height of this Box. - */ -goog.math.Box.prototype.getHeight = function() { - return this.bottom - this.top; -}; - - -/** - * 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; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/coordinate.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/coordinate.js deleted file mode 100644 index 798d3851..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/coordinate.js +++ /dev/null @@ -1,268 +0,0 @@ -// 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. - * @struct - * @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; -}; - - -/** - * Rotates this coordinate clockwise about the origin (or, optionally, the given - * center) by the given angle, in radians. - * @param {number} radians The angle by which to rotate this coordinate - * clockwise about the given center, in radians. - * @param {!goog.math.Coordinate=} opt_center The center of rotation. Defaults - * to (0, 0) if not given. - */ -goog.math.Coordinate.prototype.rotateRadians = function(radians, opt_center) { - var center = opt_center || new goog.math.Coordinate(0, 0); - - var x = this.x; - var y = this.y; - var cos = Math.cos(radians); - var sin = Math.sin(radians); - - this.x = (x - center.x) * cos - (y - center.y) * sin + center.x; - this.y = (x - center.x) * sin + (y - center.y) * cos + center.y; -}; - - -/** - * Rotates this coordinate clockwise about the origin (or, optionally, the given - * center) by the given angle, in degrees. - * @param {number} degrees The angle by which to rotate this coordinate - * clockwise about the given center, in degrees. - * @param {!goog.math.Coordinate=} opt_center The center of rotation. Defaults - * to (0, 0) if not given. - */ -goog.math.Coordinate.prototype.rotateDegrees = function(degrees, opt_center) { - this.rotateRadians(goog.math.toRadians(degrees), opt_center); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/math.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/math.js deleted file mode 100644 index 2947cf8..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/math.js +++ /dev/null @@ -1,435 +0,0 @@ -// 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 point 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); -}; - - -// TODO(user): Rename to normalizeAngle, retaining old name as deprecated -// alias. -/** - * Normalizes an angle to be in range [0-360). Angles outside this range will - * be normalized to be the equivalent angle with that range. - * @param {number} angle Angle in degrees. - * @return {number} Standardized angle. - */ -goog.math.standardAngle = function(angle) { - return goog.math.modulo(angle, 360); -}; - - -/** - * Normalizes an angle to be in range [0-2*PI). Angles outside this range will - * be normalized to be the equivalent angle with that range. - * @param {number} angle Angle in radians. - * @return {number} Standardized angle. - */ -goog.math.standardAngleInRadians = function(angle) { - return goog.math.modulo(angle, 2 * Math.PI); -}; - - -/** - * 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 <= length2; 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 unbiased sample variance of the arguments. For a definition, - * see e.g. http://en.wikipedia.org/wiki/Variance - * @param {...number} var_args Number samples to analyze. - * @return {number} The unbiased sample variance 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.sampleVariance = 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 variance; -}; - - -/** - * 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) { - return Math.sqrt(goog.math.sampleVariance.apply(null, arguments)); -}; - - -/** - * 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); -}; - - -/** - * Returns the precise value of floor(log10(num)). - * Simpler implementations didn't work because of floating point rounding - * errors. For example - * <ul> - * <li>Math.floor(Math.log(num) / Math.LN10) is off by one for num == 1e+3. - * <li>Math.floor(Math.log(num) * Math.LOG10E) is off by one for num == 1e+15. - * <li>Math.floor(Math.log10(num)) is off by one for num == 1e+15 - 1. - * </ul> - * @param {number} num A floating point number. - * @return {number} Its logarithm to base 10 rounded down to the nearest - * integer if num > 0. -Infinity if num == 0. NaN if num < 0. - */ -goog.math.log10Floor = function(num) { - if (num > 0) { - var x = Math.round(Math.log(num) * Math.LOG10E); - return x - (parseFloat('1e' + x) > num); - } - return num == 0 ? -Infinity : NaN; -}; - - -/** - * 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)); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/rect.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/rect.js deleted file mode 100644 index c44b80e..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/rect.js +++ /dev/null @@ -1,464 +0,0 @@ -// 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. - * @struct - * @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; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/size.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/size.js deleted file mode 100644 index f5c379b7..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/math/size.js +++ /dev/null @@ -1,227 +0,0 @@ -// 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. - * @author brenneman@google.com (Shawn Brenneman) - */ - - -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. - * @struct - * @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 perfectly cover the dimensions of a given size. - * If the size is already larger than the target, it will be scaled down to the - * minimum size at which it still covers the entire target. 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.scaleToCover = function(target) { - var s = this.aspectRatio() <= target.aspectRatio() ? - target.width / this.width : - target.height / this.height; - - return this.scale(s); -}; - - -/** - * 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); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/object/object.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/object/object.js deleted file mode 100644 index 20a77f7..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/object/object.js +++ /dev/null @@ -1,686 +0,0 @@ -// 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 for manipulating objects/maps/hashes. - * @author arv@google.com (Erik Arvidsson) - */ - -goog.provide('goog.object'); - - -/** - * Calls a function for each element in an object/map/hash. - * - * @param {Object<K,V>} obj The object over which to iterate. - * @param {function(this:T,V,?,Object<K,V>):?} f The function to call - * for every element. This function takes 3 arguments (the element, the - * index and the object) and the return value is ignored. - * @param {T=} opt_obj This is used as the 'this' object within f. - * @template T,K,V - */ -goog.object.forEach = function(obj, f, opt_obj) { - for (var key in obj) { - f.call(opt_obj, obj[key], key, obj); - } -}; - - -/** - * Calls a function for each element in an object/map/hash. If that call returns - * true, adds the element to a new object. - * - * @param {Object<K,V>} obj The object over which to iterate. - * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call - * for every element. This - * function takes 3 arguments (the element, the index and the object) - * and should return a boolean. If the return value is true the - * element is added to the result object. If it is false the - * element is not included. - * @param {T=} opt_obj This is used as the 'this' object within f. - * @return {!Object<K,V>} a new object in which only elements that passed the - * test are present. - * @template T,K,V - */ -goog.object.filter = function(obj, f, opt_obj) { - var res = {}; - for (var key in obj) { - if (f.call(opt_obj, obj[key], key, obj)) { - res[key] = obj[key]; - } - } - return res; -}; - - -/** - * For every element in an object/map/hash calls a function and inserts the - * result into a new object. - * - * @param {Object<K,V>} obj The object over which to iterate. - * @param {function(this:T,V,?,Object<K,V>):R} f The function to call - * for every element. This function - * takes 3 arguments (the element, the index and the object) - * and should return something. The result will be inserted - * into a new object. - * @param {T=} opt_obj This is used as the 'this' object within f. - * @return {!Object<K,R>} a new object with the results from f. - * @template T,K,V,R - */ -goog.object.map = function(obj, f, opt_obj) { - var res = {}; - for (var key in obj) { - res[key] = f.call(opt_obj, obj[key], key, obj); - } - return res; -}; - - -/** - * Calls a function for each element in an object/map/hash. If any - * call returns true, returns true (without checking the rest). If - * all calls return false, returns false. - * - * @param {Object<K,V>} obj The object to check. - * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to - * call for every element. This function - * takes 3 arguments (the element, the index and the object) and should - * return a boolean. - * @param {T=} opt_obj This is used as the 'this' object within f. - * @return {boolean} true if any element passes the test. - * @template T,K,V - */ -goog.object.some = function(obj, f, opt_obj) { - for (var key in obj) { - if (f.call(opt_obj, obj[key], key, obj)) { - return true; - } - } - return false; -}; - - -/** - * Calls a function for each element in an object/map/hash. If - * all calls return true, returns true. If any call returns false, returns - * false at this point and does not continue to check the remaining elements. - * - * @param {Object<K,V>} obj The object to check. - * @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to - * call for every element. This function - * takes 3 arguments (the element, the index and the object) and should - * return a boolean. - * @param {T=} opt_obj This is used as the 'this' object within f. - * @return {boolean} false if any element fails the test. - * @template T,K,V - */ -goog.object.every = function(obj, f, opt_obj) { - for (var key in obj) { - if (!f.call(opt_obj, obj[key], key, obj)) { - return false; - } - } - return true; -}; - - -/** - * Returns the number of key-value pairs in the object map. - * - * @param {Object} obj The object for which to get the number of key-value - * pairs. - * @return {number} The number of key-value pairs in the object map. - */ -goog.object.getCount = function(obj) { - // JS1.5 has __count__ but it has been deprecated so it raises a warning... - // in other words do not use. Also __count__ only includes the fields on the - // actual object and not in the prototype chain. - var rv = 0; - for (var key in obj) { - rv++; - } - return rv; -}; - - -/** - * Returns one key from the object map, if any exists. - * For map literals the returned key will be the first one in most of the - * browsers (a know exception is Konqueror). - * - * @param {Object} obj The object to pick a key from. - * @return {string|undefined} The key or undefined if the object is empty. - */ -goog.object.getAnyKey = function(obj) { - for (var key in obj) { - return key; - } -}; - - -/** - * Returns one value from the object map, if any exists. - * For map literals the returned value will be the first one in most of the - * browsers (a know exception is Konqueror). - * - * @param {Object<K,V>} obj The object to pick a value from. - * @return {V|undefined} The value or undefined if the object is empty. - * @template K,V - */ -goog.object.getAnyValue = function(obj) { - for (var key in obj) { - return obj[key]; - } -}; - - -/** - * Whether the object/hash/map contains the given object as a value. - * An alias for goog.object.containsValue(obj, val). - * - * @param {Object<K,V>} obj The object in which to look for val. - * @param {V} val The object for which to check. - * @return {boolean} true if val is present. - * @template K,V - */ -goog.object.contains = function(obj, val) { - return goog.object.containsValue(obj, val); -}; - - -/** - * Returns the values of the object/map/hash. - * - * @param {Object<K,V>} obj The object from which to get the values. - * @return {!Array<V>} The values in the object/map/hash. - * @template K,V - */ -goog.object.getValues = function(obj) { - var res = []; - var i = 0; - for (var key in obj) { - res[i++] = obj[key]; - } - return res; -}; - - -/** - * Returns the keys of the object/map/hash. - * - * @param {Object} obj The object from which to get the keys. - * @return {!Array<string>} Array of property keys. - */ -goog.object.getKeys = function(obj) { - var res = []; - var i = 0; - for (var key in obj) { - res[i++] = key; - } - return res; -}; - - -/** - * Get a value from an object multiple levels deep. This is useful for - * pulling values from deeply nested objects, such as JSON responses. - * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3) - * - * @param {!Object} obj An object to get the value from. Can be array-like. - * @param {...(string|number|!Array<number|string>)} var_args A number of keys - * (as strings, or numbers, for array-like objects). Can also be - * specified as a single array of keys. - * @return {*} The resulting value. If, at any point, the value for a key - * is undefined, returns undefined. - */ -goog.object.getValueByKeys = function(obj, var_args) { - var isArrayLike = goog.isArrayLike(var_args); - var keys = isArrayLike ? var_args : arguments; - - // Start with the 2nd parameter for the variable parameters syntax. - for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) { - obj = obj[keys[i]]; - if (!goog.isDef(obj)) { - break; - } - } - - return obj; -}; - - -/** - * Whether the object/map/hash contains the given key. - * - * @param {Object} obj The object in which to look for key. - * @param {*} key The key for which to check. - * @return {boolean} true If the map contains the key. - */ -goog.object.containsKey = function(obj, key) { - return key in obj; -}; - - -/** - * Whether the object/map/hash contains the given value. This is O(n). - * - * @param {Object<K,V>} obj The object in which to look for val. - * @param {V} val The value for which to check. - * @return {boolean} true If the map contains the value. - * @template K,V - */ -goog.object.containsValue = function(obj, val) { - for (var key in obj) { - if (obj[key] == val) { - return true; - } - } - return false; -}; - - -/** - * Searches an object for an element that satisfies the given condition and - * returns its key. - * @param {Object<K,V>} obj The object to search in. - * @param {function(this:T,V,string,Object<K,V>):boolean} f The - * function to call for every element. Takes 3 arguments (the value, - * the key and the object) and should return a boolean. - * @param {T=} opt_this An optional "this" context for the function. - * @return {string|undefined} The key of an element for which the function - * returns true or undefined if no such element is found. - * @template T,K,V - */ -goog.object.findKey = function(obj, f, opt_this) { - for (var key in obj) { - if (f.call(opt_this, obj[key], key, obj)) { - return key; - } - } - return undefined; -}; - - -/** - * Searches an object for an element that satisfies the given condition and - * returns its value. - * @param {Object<K,V>} obj The object to search in. - * @param {function(this:T,V,string,Object<K,V>):boolean} f The function - * to call for every element. Takes 3 arguments (the value, the key - * and the object) and should return a boolean. - * @param {T=} opt_this An optional "this" context for the function. - * @return {V} The value of an element for which the function returns true or - * undefined if no such element is found. - * @template T,K,V - */ -goog.object.findValue = function(obj, f, opt_this) { - var key = goog.object.findKey(obj, f, opt_this); - return key && obj[key]; -}; - - -/** - * Whether the object/map/hash is empty. - * - * @param {Object} obj The object to test. - * @return {boolean} true if obj is empty. - */ -goog.object.isEmpty = function(obj) { - for (var key in obj) { - return false; - } - return true; -}; - - -/** - * Removes all key value pairs from the object/map/hash. - * - * @param {Object} obj The object to clear. - */ -goog.object.clear = function(obj) { - for (var i in obj) { - delete obj[i]; - } -}; - - -/** - * Removes a key-value pair based on the key. - * - * @param {Object} obj The object from which to remove the key. - * @param {*} key The key to remove. - * @return {boolean} Whether an element was removed. - */ -goog.object.remove = function(obj, key) { - var rv; - if ((rv = key in obj)) { - delete obj[key]; - } - return rv; -}; - - -/** - * Adds a key-value pair to the object. Throws an exception if the key is - * already in use. Use set if you want to change an existing pair. - * - * @param {Object<K,V>} obj The object to which to add the key-value pair. - * @param {string} key The key to add. - * @param {V} val The value to add. - * @template K,V - */ -goog.object.add = function(obj, key, val) { - if (key in obj) { - throw Error('The object already contains the key "' + key + '"'); - } - goog.object.set(obj, key, val); -}; - - -/** - * Returns the value for the given key. - * - * @param {Object<K,V>} obj The object from which to get the value. - * @param {string} key The key for which to get the value. - * @param {R=} opt_val The value to return if no item is found for the given - * key (default is undefined). - * @return {V|R|undefined} The value for the given key. - * @template K,V,R - */ -goog.object.get = function(obj, key, opt_val) { - if (key in obj) { - return obj[key]; - } - return opt_val; -}; - - -/** - * Adds a key-value pair to the object/map/hash. - * - * @param {Object<K,V>} obj The object to which to add the key-value pair. - * @param {string} key The key to add. - * @param {V} value The value to add. - * @template K,V - */ -goog.object.set = function(obj, key, value) { - obj[key] = value; -}; - - -/** - * Adds a key-value pair to the object/map/hash if it doesn't exist yet. - * - * @param {Object<K,V>} obj The object to which to add the key-value pair. - * @param {string} key The key to add. - * @param {V} value The value to add if the key wasn't present. - * @return {V} The value of the entry at the end of the function. - * @template K,V - */ -goog.object.setIfUndefined = function(obj, key, value) { - return key in obj ? obj[key] : (obj[key] = value); -}; - - -/** - * Sets a key and value to an object if the key is not set. The value will be - * the return value of the given function. If the key already exists, the - * object will not be changed and the function will not be called (the function - * will be lazily evaluated -- only called if necessary). - * - * This function is particularly useful for use with a map used a as a cache. - * - * @param {!Object<K,V>} obj The object to which to add the key-value pair. - * @param {string} key The key to add. - * @param {function():V} f The value to add if the key wasn't present. - * @return {V} The value of the entry at the end of the function. - * @template K,V - */ -goog.object.setWithReturnValueIfNotSet = function(obj, key, f) { - if (key in obj) { - return obj[key]; - } - - var val = f(); - obj[key] = val; - return val; -}; - - -/** - * Compares two objects for equality using === on the values. - * - * @param {!Object<K,V>} a - * @param {!Object<K,V>} b - * @return {boolean} - * @template K,V - */ -goog.object.equals = function(a, b) { - for (var k in a) { - if (!(k in b) || a[k] !== b[k]) { - return false; - } - } - for (var k in b) { - if (!(k in a)) { - return false; - } - } - return true; -}; - - -/** - * Does a flat clone of the object. - * - * @param {Object<K,V>} obj Object to clone. - * @return {!Object<K,V>} Clone of the input object. - * @template K,V - */ -goog.object.clone = function(obj) { - // We cannot use the prototype trick because a lot of methods depend on where - // the actual key is set. - - var res = {}; - for (var key in obj) { - res[key] = obj[key]; - } - return res; - // We could also use goog.mixin but I wanted this to be independent from that. -}; - - -/** - * Clones a value. The input may be an Object, Array, or basic type. Objects and - * arrays will be cloned recursively. - * - * WARNINGS: - * <code>goog.object.unsafeClone</code> does not detect reference loops. Objects - * that refer to themselves will cause infinite recursion. - * - * <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and - * copies UIDs created by <code>getUid</code> into cloned results. - * - * @param {*} obj The value to clone. - * @return {*} A clone of the input value. - */ -goog.object.unsafeClone = function(obj) { - var type = goog.typeOf(obj); - if (type == 'object' || type == 'array') { - if (obj.clone) { - return obj.clone(); - } - var clone = type == 'array' ? [] : {}; - for (var key in obj) { - clone[key] = goog.object.unsafeClone(obj[key]); - } - return clone; - } - - return obj; -}; - - -/** - * Returns a new object in which all the keys and values are interchanged - * (keys become values and values become keys). If multiple keys map to the - * same value, the chosen transposed value is implementation-dependent. - * - * @param {Object} obj The object to transpose. - * @return {!Object} The transposed object. - */ -goog.object.transpose = function(obj) { - var transposed = {}; - for (var key in obj) { - transposed[obj[key]] = key; - } - return transposed; -}; - - -/** - * The names of the fields that are defined on Object.prototype. - * @type {Array<string>} - * @private - */ -goog.object.PROTOTYPE_FIELDS_ = [ - 'constructor', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'toLocaleString', - 'toString', - 'valueOf' -]; - - -/** - * Extends an object with another object. - * This operates 'in-place'; it does not create a new Object. - * - * Example: - * var o = {}; - * goog.object.extend(o, {a: 0, b: 1}); - * o; // {a: 0, b: 1} - * goog.object.extend(o, {b: 2, c: 3}); - * o; // {a: 0, b: 2, c: 3} - * - * @param {Object} target The object to modify. Existing properties will be - * overwritten if they are also present in one of the objects in - * {@code var_args}. - * @param {...Object} var_args The objects from which values will be copied. - */ -goog.object.extend = function(target, var_args) { - var key, source; - for (var i = 1; i < arguments.length; i++) { - source = arguments[i]; - for (key in source) { - target[key] = source[key]; - } - - // For IE the for-in-loop does not contain any properties that are not - // enumerable on the prototype object (for example isPrototypeOf from - // Object.prototype) and it will also not include 'replace' on objects that - // extend String and change 'replace' (not that it is common for anyone to - // extend anything except Object). - - for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) { - key = goog.object.PROTOTYPE_FIELDS_[j]; - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } -}; - - -/** - * Creates a new object built from the key-value pairs provided as arguments. - * @param {...*} var_args If only one argument is provided and it is an array - * then this is used as the arguments, otherwise even arguments are used as - * the property names and odd arguments are used as the property values. - * @return {!Object} The new object. - * @throws {Error} If there are uneven number of arguments or there is only one - * non array argument. - */ -goog.object.create = function(var_args) { - var argLength = arguments.length; - if (argLength == 1 && goog.isArray(arguments[0])) { - return goog.object.create.apply(null, arguments[0]); - } - - if (argLength % 2) { - throw Error('Uneven number of arguments'); - } - - var rv = {}; - for (var i = 0; i < argLength; i += 2) { - rv[arguments[i]] = arguments[i + 1]; - } - return rv; -}; - - -/** - * Creates a new object where the property names come from the arguments but - * the value is always set to true - * @param {...*} var_args If only one argument is provided and it is an array - * then this is used as the arguments, otherwise the arguments are used - * as the property names. - * @return {!Object} The new object. - */ -goog.object.createSet = function(var_args) { - var argLength = arguments.length; - if (argLength == 1 && goog.isArray(arguments[0])) { - return goog.object.createSet.apply(null, arguments[0]); - } - - var rv = {}; - for (var i = 0; i < argLength; i++) { - rv[arguments[i]] = true; - } - return rv; -}; - - -/** - * Creates an immutable view of the underlying object, if the browser - * supports immutable objects. - * - * In default mode, writes to this view will fail silently. In strict mode, - * they will throw an error. - * - * @param {!Object<K,V>} obj An object. - * @return {!Object<K,V>} An immutable view of that object, or the - * original object if this browser does not support immutables. - * @template K,V - */ -goog.object.createImmutableView = function(obj) { - var result = obj; - if (Object.isFrozen && !Object.isFrozen(obj)) { - result = Object.create(obj); - Object.freeze(result); - } - return result; -}; - - -/** - * @param {!Object} obj An object. - * @return {boolean} Whether this is an immutable view of the object. - */ -goog.object.isImmutableView = function(obj) { - return !!Object.isFrozen && Object.isFrozen(obj); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/promise.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/promise.js deleted file mode 100644 index fb88e46..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/promise.js +++ /dev/null @@ -1,1241 +0,0 @@ -// 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. - -goog.provide('goog.Promise'); - -goog.require('goog.Thenable'); -goog.require('goog.asserts'); -goog.require('goog.async.FreeList'); -goog.require('goog.async.run'); -goog.require('goog.async.throwException'); -goog.require('goog.debug.Error'); -goog.require('goog.promise.Resolver'); - - - -/** - * Promises provide a result that may be resolved asynchronously. A Promise may - * be resolved by being fulfilled or rejected with a value, which will be known - * as the fulfillment value or the rejection reason. Whether fulfilled or - * rejected, the Promise result is immutable once it is set. - * - * Promises may represent results of any type, including undefined. Rejection - * reasons are typically Errors, but may also be of any type. Closure Promises - * allow for optional type annotations that enforce that fulfillment values are - * of the appropriate types at compile time. - * - * The result of a Promise is accessible by calling {@code then} and registering - * {@code onFulfilled} and {@code onRejected} callbacks. Once the Promise - * resolves, the relevant callbacks are invoked with the fulfillment value or - * rejection reason as argument. Callbacks are always invoked in the order they - * were registered, even when additional {@code then} calls are made from inside - * another callback. A callback is always run asynchronously sometime after the - * scope containing the registering {@code then} invocation has returned. - * - * If a Promise is resolved with another Promise, the first Promise will block - * until the second is resolved, and then assumes the same result as the second - * Promise. This allows Promises to depend on the results of other Promises, - * linking together multiple asynchronous operations. - * - * This implementation is compatible with the Promises/A+ specification and - * passes that specification's conformance test suite. A Closure Promise may be - * resolved with a Promise instance (or sufficiently compatible Promise-like - * object) created by other Promise implementations. From the specification, - * Promise-like objects are known as "Thenables". - * - * @see http://promisesaplus.com/ - * - * @param {function( - * this:RESOLVER_CONTEXT, - * function((TYPE|IThenable<TYPE>|Thenable)=), - * function(*)): void} resolver - * Initialization function that is invoked immediately with {@code resolve} - * and {@code reject} functions as arguments. The Promise is resolved or - * rejected with the first argument passed to either function. - * @param {RESOLVER_CONTEXT=} opt_context An optional context for executing the - * resolver function. If unspecified, the resolver function will be executed - * in the default scope. - * @constructor - * @struct - * @final - * @implements {goog.Thenable<TYPE>} - * @template TYPE,RESOLVER_CONTEXT - */ -goog.Promise = function(resolver, opt_context) { - /** - * The internal state of this Promise. Either PENDING, FULFILLED, REJECTED, or - * BLOCKED. - * @private {goog.Promise.State_} - */ - this.state_ = goog.Promise.State_.PENDING; - - /** - * The resolved result of the Promise. Immutable once set with either a - * fulfillment value or rejection reason. - * @private {*} - */ - this.result_ = undefined; - - /** - * For Promises created by calling {@code then()}, the originating parent. - * @private {goog.Promise} - */ - this.parent_ = null; - - /** - * The linked list of {@code onFulfilled} and {@code onRejected} callbacks - * added to this Promise by calls to {@code then()}. - * @private {?goog.Promise.CallbackEntry_} - */ - this.callbackEntries_ = null; - - /** - * The tail of the linked list of {@code onFulfilled} and {@code onRejected} - * callbacks added to this Promise by calls to {@code then()}. - * @private {?goog.Promise.CallbackEntry_} - */ - this.callbackEntriesTail_ = null; - - /** - * Whether the Promise is in the queue of Promises to execute. - * @private {boolean} - */ - this.executing_ = false; - - if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) { - /** - * A timeout ID used when the {@code UNHANDLED_REJECTION_DELAY} is greater - * than 0 milliseconds. The ID is set when the Promise is rejected, and - * cleared only if an {@code onRejected} callback is invoked for the - * Promise (or one of its descendants) before the delay is exceeded. - * - * If the rejection is not handled before the timeout completes, the - * rejection reason is passed to the unhandled rejection handler. - * @private {number} - */ - this.unhandledRejectionId_ = 0; - } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) { - /** - * When the {@code UNHANDLED_REJECTION_DELAY} is set to 0 milliseconds, a - * boolean that is set if the Promise is rejected, and reset to false if an - * {@code onRejected} callback is invoked for the Promise (or one of its - * descendants). If the rejection is not handled before the next timestep, - * the rejection reason is passed to the unhandled rejection handler. - * @private {boolean} - */ - this.hadUnhandledRejection_ = false; - } - - if (goog.Promise.LONG_STACK_TRACES) { - /** - * A list of stack trace frames pointing to the locations where this Promise - * was created or had callbacks added to it. Saved to add additional context - * to stack traces when an exception is thrown. - * @private {!Array<string>} - */ - this.stack_ = []; - this.addStackTrace_(new Error('created')); - - /** - * Index of the most recently executed stack frame entry. - * @private {number} - */ - this.currentStep_ = 0; - } - - if (resolver == goog.Promise.RESOLVE_FAST_PATH_) { - // If the special sentinel resolver value is passed (from - // goog.Promise.resolve) we short cut to immediately resolve the promise - // using the value passed as opt_context. Don't try this at home. - this.resolve_(goog.Promise.State_.FULFILLED, opt_context); - } else { - try { - var self = this; - resolver.call( - opt_context, - function(value) { - self.resolve_(goog.Promise.State_.FULFILLED, value); - }, - function(reason) { - if (goog.DEBUG && - !(reason instanceof goog.Promise.CancellationError)) { - try { - // Promise was rejected. Step up one call frame to see why. - if (reason instanceof Error) { - throw reason; - } else { - throw new Error('Promise rejected.'); - } - } catch (e) { - // Only thrown so browser dev tools can catch rejections of - // promises when the option to break on caught exceptions is - // activated. - } - } - self.resolve_(goog.Promise.State_.REJECTED, reason); - }); - } catch (e) { - this.resolve_(goog.Promise.State_.REJECTED, e); - } - } -}; - - -/** - * @define {boolean} Whether traces of {@code then} calls should be included in - * exceptions thrown - */ -goog.define('goog.Promise.LONG_STACK_TRACES', false); - - -/** - * @define {number} The delay in milliseconds before a rejected Promise's reason - * is passed to the rejection handler. By default, the rejection handler - * rethrows the rejection reason so that it appears in the developer console or - * {@code window.onerror} handler. - * - * Rejections are rethrown as quickly as possible by default. A negative value - * disables rejection handling entirely. - */ -goog.define('goog.Promise.UNHANDLED_REJECTION_DELAY', 0); - - -/** - * The possible internal states for a Promise. These states are not directly - * observable to external callers. - * @enum {number} - * @private - */ -goog.Promise.State_ = { - /** The Promise is waiting for resolution. */ - PENDING: 0, - - /** The Promise is blocked waiting for the result of another Thenable. */ - BLOCKED: 1, - - /** The Promise has been resolved with a fulfillment value. */ - FULFILLED: 2, - - /** The Promise has been resolved with a rejection reason. */ - REJECTED: 3 -}; - - - -/** - * Entries in the callback chain. Each call to {@code then}, - * {@code thenCatch}, or {@code thenAlways} creates an entry containing the - * functions that may be invoked once the Promise is resolved. - * - * @private @final @struct @constructor - */ -goog.Promise.CallbackEntry_ = function() { - /** @type {?goog.Promise} */ - this.child = null; - /** @type {Function} */ - this.onFulfilled = null; - /** @type {Function} */ - this.onRejected = null; - /** @type {?} */ - this.context = null; - /** @type {?goog.Promise.CallbackEntry_} */ - this.next = null; - - /** - * A boolean value to indicate this is a "thenAlways" callback entry. - * Unlike a normal "then/thenVoid" a "thenAlways doesn't particapate - * in "cancel" considerations but is simply an observer and requires - * special handling. - * @type {boolean} - */ - this.always = false; -}; - - -/** clear the object prior to reuse */ -goog.Promise.CallbackEntry_.prototype.reset = function() { - this.child = null; - this.onFulfilled = null; - this.onRejected = null; - this.context = null; - this.always = false; -}; - - -/** - * @define {number} The number of currently unused objects to keep around for - * reuse. - */ -goog.define('goog.Promise.DEFAULT_MAX_UNUSED', 100); - - -/** @const @private {goog.async.FreeList<!goog.Promise.CallbackEntry_>} */ -goog.Promise.freelist_ = new goog.async.FreeList( - function() { - return new goog.Promise.CallbackEntry_(); - }, - function(item) { - item.reset(); - }, - goog.Promise.DEFAULT_MAX_UNUSED); - - -/** - * @param {Function} onFulfilled - * @param {Function} onRejected - * @param {?} context - * @return {!goog.Promise.CallbackEntry_} - * @private - */ -goog.Promise.getCallbackEntry_ = function(onFulfilled, onRejected, context) { - var entry = goog.Promise.freelist_.get(); - entry.onFulfilled = onFulfilled; - entry.onRejected = onRejected; - entry.context = context; - return entry; -}; - - -/** - * @param {!goog.Promise.CallbackEntry_} entry - * @private - */ -goog.Promise.returnEntry_ = function(entry) { - goog.Promise.freelist_.put(entry); -}; - - -/** - * If this passed as the first argument to the {@link goog.Promise} constructor - * the the opt_context is (against its primary use) used to immediately resolve - * the promise. This is used from {@link goog.Promise.resolve} as an - * optimization to avoid allocating 3 closures that are never really needed. - * @private @const {!Function} - */ -goog.Promise.RESOLVE_FAST_PATH_ = function() {}; - - -/** - * @param {(TYPE|goog.Thenable<TYPE>|Thenable)=} opt_value - * @return {!goog.Promise<TYPE>} A new Promise that is immediately resolved - * with the given value. - * @template TYPE - */ -goog.Promise.resolve = function(opt_value) { - // Passes the value as the context, which is a special fast pass when - // goog.Promise.RESOLVE_FAST_PATH_ is passed as the first argument. - return new goog.Promise(goog.Promise.RESOLVE_FAST_PATH_, opt_value); -}; - - -/** - * @param {*=} opt_reason - * @return {!goog.Promise} A new Promise that is immediately rejected with the - * given reason. - */ -goog.Promise.reject = function(opt_reason) { - return new goog.Promise(function(resolve, reject) { - reject(opt_reason); - }); -}; - - -/** - * @param {!Array<!(goog.Thenable<TYPE>|Thenable)>} promises - * @return {!goog.Promise<TYPE>} A Promise that receives the result of the - * first Promise (or Promise-like) input to complete. - * @template TYPE - */ -goog.Promise.race = function(promises) { - return new goog.Promise(function(resolve, reject) { - if (!promises.length) { - resolve(undefined); - } - for (var i = 0, promise; promise = promises[i]; i++) { - goog.Promise.maybeThenVoid_(promise, resolve, reject); - } - }); -}; - - -/** - * @param {!Array<!(goog.Thenable<TYPE>|Thenable)>} promises - * @return {!goog.Promise<!Array<TYPE>>} A Promise that receives a list of - * every fulfilled value once every input Promise (or Promise-like) is - * successfully fulfilled, or is rejected by the first rejection result. - * @template TYPE - */ -goog.Promise.all = function(promises) { - return new goog.Promise(function(resolve, reject) { - var toFulfill = promises.length; - var values = []; - - if (!toFulfill) { - resolve(values); - return; - } - - var onFulfill = function(index, value) { - toFulfill--; - values[index] = value; - if (toFulfill == 0) { - resolve(values); - } - }; - - var onReject = function(reason) { - reject(reason); - }; - - for (var i = 0, promise; promise = promises[i]; i++) { - goog.Promise.maybeThenVoid_( - promise, goog.partial(onFulfill, i), onReject); - } - }); -}; - - -/** - * @param {!Array<!(goog.Thenable<TYPE>|Thenable)>} promises - * @return {!goog.Promise<TYPE>} A Promise that receives the value of the first - * input to be fulfilled, or is rejected with a list of every rejection - * reason if all inputs are rejected. - * @template TYPE - */ -goog.Promise.firstFulfilled = function(promises) { - return new goog.Promise(function(resolve, reject) { - var toReject = promises.length; - var reasons = []; - - if (!toReject) { - resolve(undefined); - return; - } - - var onFulfill = function(value) { - resolve(value); - }; - - var onReject = function(index, reason) { - toReject--; - reasons[index] = reason; - if (toReject == 0) { - reject(reasons); - } - }; - - for (var i = 0, promise; promise = promises[i]; i++) { - goog.Promise.maybeThenVoid_( - promise, onFulfill, goog.partial(onReject, i)); - } - }); -}; - - -/** - * @return {!goog.promise.Resolver<TYPE>} Resolver wrapping the promise and its - * resolve / reject functions. Resolving or rejecting the resolver - * resolves or rejects the promise. - * @template TYPE - */ -goog.Promise.withResolver = function() { - var resolve, reject; - var promise = new goog.Promise(function(rs, rj) { - resolve = rs; - reject = rj; - }); - return new goog.Promise.Resolver_(promise, resolve, reject); -}; - - -/** - * Adds callbacks that will operate on the result of the Promise, returning a - * new child Promise. - * - * If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked - * with the fulfillment value as argument, and the child Promise will be - * fulfilled with the return value of the callback. If the callback throws an - * exception, the child Promise will be rejected with the thrown value instead. - * - * If the Promise is rejected, the {@code onRejected} callback will be invoked - * with the rejection reason as argument, and the child Promise will be resolved - * with the return value or rejected with the thrown value of the callback. - * - * @override - */ -goog.Promise.prototype.then = function( - opt_onFulfilled, opt_onRejected, opt_context) { - - if (opt_onFulfilled != null) { - goog.asserts.assertFunction(opt_onFulfilled, - 'opt_onFulfilled should be a function.'); - } - if (opt_onRejected != null) { - goog.asserts.assertFunction(opt_onRejected, - 'opt_onRejected should be a function. Did you pass opt_context ' + - 'as the second argument instead of the third?'); - } - - if (goog.Promise.LONG_STACK_TRACES) { - this.addStackTrace_(new Error('then')); - } - - return this.addChildPromise_( - goog.isFunction(opt_onFulfilled) ? opt_onFulfilled : null, - goog.isFunction(opt_onRejected) ? opt_onRejected : null, - opt_context); -}; -goog.Thenable.addImplementation(goog.Promise); - - -/** - * Adds callbacks that will operate on the result of the Promise without - * returning a child Promise (unlike "then"). - * - * If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked - * with the fulfillment value as argument. - * - * If the Promise is rejected, the {@code onRejected} callback will be invoked - * with the rejection reason as argument. - * - * @param {?(function(this:THIS, TYPE): - * (RESULT|IThenable<RESULT>|Thenable))=} opt_onFulfilled A - * function that will be invoked with the fulfillment value if the Promise - * is fullfilled. - * @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will - * be invoked with the rejection reason if the Promise is rejected. - * @param {THIS=} opt_context An optional context object that will be the - * execution context for the callbacks. By default, functions are executed - * with the default this. - * @package - * @template RESULT,THIS - */ -goog.Promise.prototype.thenVoid = function( - opt_onFulfilled, opt_onRejected, opt_context) { - - if (opt_onFulfilled != null) { - goog.asserts.assertFunction(opt_onFulfilled, - 'opt_onFulfilled should be a function.'); - } - if (opt_onRejected != null) { - goog.asserts.assertFunction(opt_onRejected, - 'opt_onRejected should be a function. Did you pass opt_context ' + - 'as the second argument instead of the third?'); - } - - if (goog.Promise.LONG_STACK_TRACES) { - this.addStackTrace_(new Error('then')); - } - - // Note: no default rejection handler is provided here as we need to - // distinguish unhandled rejections. - this.addCallbackEntry_(goog.Promise.getCallbackEntry_( - opt_onFulfilled || goog.nullFunction, - opt_onRejected || null, - opt_context)); -}; - - -/** - * Calls "thenVoid" if possible to avoid allocating memory. Otherwise calls - * "then". - * @param {(goog.Thenable<TYPE>|Thenable)} promise - * @param {function(this:THIS, TYPE): ?} onFulfilled - * @param {function(this:THIS, *): *} onRejected - * @param {THIS=} opt_context - * @template THIS,TYPE - * @private - */ -goog.Promise.maybeThenVoid_ = function( - promise, onFulfilled, onRejected, opt_context) { - if (promise instanceof goog.Promise) { - promise.thenVoid(onFulfilled, onRejected, opt_context); - } else { - promise.then(onFulfilled, onRejected, opt_context); - } -}; - - -/** - * Adds a callback that will be invoked whether the Promise is fulfilled or - * rejected. The callback receives no argument, and no new child Promise is - * created. This is useful for ensuring that cleanup takes place after certain - * asynchronous operations. Callbacks added with {@code thenAlways} will be - * executed in the same order with other calls to {@code then}, - * {@code thenAlways}, or {@code thenCatch}. - * - * Since it does not produce a new child Promise, cancellation propagation is - * not prevented by adding callbacks with {@code thenAlways}. A Promise that has - * a cleanup handler added with {@code thenAlways} will be canceled if all of - * its children created by {@code then} (or {@code thenCatch}) are canceled. - * Additionally, since any rejections are not passed to the callback, it does - * not stop the unhandled rejection handler from running. - * - * @param {function(this:THIS): void} onResolved A function that will be invoked - * when the Promise is resolved. - * @param {THIS=} opt_context An optional context object that will be the - * execution context for the callbacks. By default, functions are executed - * in the global scope. - * @return {!goog.Promise<TYPE>} This Promise, for chaining additional calls. - * @template THIS - */ -goog.Promise.prototype.thenAlways = function(onResolved, opt_context) { - if (goog.Promise.LONG_STACK_TRACES) { - this.addStackTrace_(new Error('thenAlways')); - } - - var callback = function() { - try { - // Ensure that no arguments are passed to onResolved. - onResolved.call(opt_context); - } catch (err) { - goog.Promise.handleRejection_.call(null, err); - } - }; - - var entry = goog.Promise.getCallbackEntry_(callback, callback, null); - entry.always = true; - this.addCallbackEntry_(entry); - return this; -}; - - -/** - * Adds a callback that will be invoked only if the Promise is rejected. This - * is equivalent to {@code then(null, onRejected)}. - * - * @param {!function(this:THIS, *): *} onRejected A function that will be - * invoked with the rejection reason if the Promise is rejected. - * @param {THIS=} opt_context An optional context object that will be the - * execution context for the callbacks. By default, functions are executed - * in the global scope. - * @return {!goog.Promise} A new Promise that will receive the result of the - * callback. - * @template THIS - */ -goog.Promise.prototype.thenCatch = function(onRejected, opt_context) { - if (goog.Promise.LONG_STACK_TRACES) { - this.addStackTrace_(new Error('thenCatch')); - } - return this.addChildPromise_(null, onRejected, opt_context); -}; - - -/** - * Cancels the Promise if it is still pending by rejecting it with a cancel - * Error. No action is performed if the Promise is already resolved. - * - * All child Promises of the canceled Promise will be rejected with the same - * cancel error, as with normal Promise rejection. If the Promise to be canceled - * is the only child of a pending Promise, the parent Promise will also be - * canceled. Cancellation may propagate upward through multiple generations. - * - * @param {string=} opt_message An optional debugging message for describing the - * cancellation reason. - */ -goog.Promise.prototype.cancel = function(opt_message) { - if (this.state_ == goog.Promise.State_.PENDING) { - goog.async.run(function() { - var err = new goog.Promise.CancellationError(opt_message); - this.cancelInternal_(err); - }, this); - } -}; - - -/** - * Cancels this Promise with the given error. - * - * @param {!Error} err The cancellation error. - * @private - */ -goog.Promise.prototype.cancelInternal_ = function(err) { - if (this.state_ == goog.Promise.State_.PENDING) { - if (this.parent_) { - // Cancel the Promise and remove it from the parent's child list. - this.parent_.cancelChild_(this, err); - this.parent_ = null; - } else { - this.resolve_(goog.Promise.State_.REJECTED, err); - } - } -}; - - -/** - * Cancels a child Promise from the list of callback entries. If the Promise has - * not already been resolved, reject it with a cancel error. If there are no - * other children in the list of callback entries, propagate the cancellation - * by canceling this Promise as well. - * - * @param {!goog.Promise} childPromise The Promise to cancel. - * @param {!Error} err The cancel error to use for rejecting the Promise. - * @private - */ -goog.Promise.prototype.cancelChild_ = function(childPromise, err) { - if (!this.callbackEntries_) { - return; - } - var childCount = 0; - var childEntry = null; - var beforeChildEntry = null; - - // Find the callback entry for the childPromise, and count whether there are - // additional child Promises. - for (var entry = this.callbackEntries_; entry; entry = entry.next) { - if (!entry.always) { - childCount++; - if (entry.child == childPromise) { - childEntry = entry; - } - if (childEntry && childCount > 1) { - break; - } - } - if (!childEntry) { - beforeChildEntry = entry; - } - } - - // Can a child entry be missing? - - // If the child Promise was the only child, cancel this Promise as well. - // Otherwise, reject only the child Promise with the cancel error. - if (childEntry) { - if (this.state_ == goog.Promise.State_.PENDING && childCount == 1) { - this.cancelInternal_(err); - } else { - if (beforeChildEntry) { - this.removeEntryAfter_(beforeChildEntry); - } else { - this.popEntry_(); - } - - this.executeCallback_( - childEntry, goog.Promise.State_.REJECTED, err); - } - } -}; - - -/** - * Adds a callback entry to the current Promise, and schedules callback - * execution if the Promise has already been resolved. - * - * @param {goog.Promise.CallbackEntry_} callbackEntry Record containing - * {@code onFulfilled} and {@code onRejected} callbacks to execute after - * the Promise is resolved. - * @private - */ -goog.Promise.prototype.addCallbackEntry_ = function(callbackEntry) { - if (!this.hasEntry_() && - (this.state_ == goog.Promise.State_.FULFILLED || - this.state_ == goog.Promise.State_.REJECTED)) { - this.scheduleCallbacks_(); - } - this.queueEntry_(callbackEntry); -}; - - -/** - * Creates a child Promise and adds it to the callback entry list. The result of - * the child Promise is determined by the state of the parent Promise and the - * result of the {@code onFulfilled} or {@code onRejected} callbacks as - * specified in the Promise resolution procedure. - * - * @see http://promisesaplus.com/#the__method - * - * @param {?function(this:THIS, TYPE): - * (RESULT|goog.Promise<RESULT>|Thenable)} onFulfilled A callback that - * will be invoked if the Promise is fullfilled, or null. - * @param {?function(this:THIS, *): *} onRejected A callback that will be - * invoked if the Promise is rejected, or null. - * @param {THIS=} opt_context An optional execution context for the callbacks. - * in the default calling context. - * @return {!goog.Promise} The child Promise. - * @template RESULT,THIS - * @private - */ -goog.Promise.prototype.addChildPromise_ = function( - onFulfilled, onRejected, opt_context) { - - /** @type {goog.Promise.CallbackEntry_} */ - var callbackEntry = goog.Promise.getCallbackEntry_(null, null, null); - - callbackEntry.child = new goog.Promise(function(resolve, reject) { - // Invoke onFulfilled, or resolve with the parent's value if absent. - callbackEntry.onFulfilled = onFulfilled ? function(value) { - try { - var result = onFulfilled.call(opt_context, value); - resolve(result); - } catch (err) { - reject(err); - } - } : resolve; - - // Invoke onRejected, or reject with the parent's reason if absent. - callbackEntry.onRejected = onRejected ? function(reason) { - try { - var result = onRejected.call(opt_context, reason); - if (!goog.isDef(result) && - reason instanceof goog.Promise.CancellationError) { - // Propagate cancellation to children if no other result is returned. - reject(reason); - } else { - resolve(result); - } - } catch (err) { - reject(err); - } - } : reject; - }); - - callbackEntry.child.parent_ = this; - this.addCallbackEntry_(callbackEntry); - return callbackEntry.child; -}; - - -/** - * Unblocks the Promise and fulfills it with the given value. - * - * @param {TYPE} value - * @private - */ -goog.Promise.prototype.unblockAndFulfill_ = function(value) { - goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED); - this.state_ = goog.Promise.State_.PENDING; - this.resolve_(goog.Promise.State_.FULFILLED, value); -}; - - -/** - * Unblocks the Promise and rejects it with the given rejection reason. - * - * @param {*} reason - * @private - */ -goog.Promise.prototype.unblockAndReject_ = function(reason) { - goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED); - this.state_ = goog.Promise.State_.PENDING; - this.resolve_(goog.Promise.State_.REJECTED, reason); -}; - - -/** - * Attempts to resolve a Promise with a given resolution state and value. This - * is a no-op if the given Promise has already been resolved. - * - * If the given result is a Thenable (such as another Promise), the Promise will - * be resolved with the same state and result as the Thenable once it is itself - * resolved. - * - * If the given result is not a Thenable, the Promise will be fulfilled or - * rejected with that result based on the given state. - * - * @see http://promisesaplus.com/#the_promise_resolution_procedure - * - * @param {goog.Promise.State_} state - * @param {*} x The result to apply to the Promise. - * @private - */ -goog.Promise.prototype.resolve_ = function(state, x) { - if (this.state_ != goog.Promise.State_.PENDING) { - return; - } - - if (this == x) { - state = goog.Promise.State_.REJECTED; - x = new TypeError('Promise cannot resolve to itself'); - - } else if (goog.Thenable.isImplementedBy(x)) { - x = /** @type {!goog.Thenable} */ (x); - this.state_ = goog.Promise.State_.BLOCKED; - goog.Promise.maybeThenVoid_( - x, this.unblockAndFulfill_, this.unblockAndReject_, this); - return; - } else if (goog.isObject(x)) { - try { - var then = x['then']; - if (goog.isFunction(then)) { - this.tryThen_(x, then); - return; - } - } catch (e) { - state = goog.Promise.State_.REJECTED; - x = e; - } - } - - this.result_ = x; - this.state_ = state; - // Since we can no longer be cancelled, remove link to parent, so that the - // child promise does not keep the parent promise alive. - this.parent_ = null; - this.scheduleCallbacks_(); - - if (state == goog.Promise.State_.REJECTED && - !(x instanceof goog.Promise.CancellationError)) { - goog.Promise.addUnhandledRejection_(this, x); - } -}; - - -/** - * Attempts to call the {@code then} method on an object in the hopes that it is - * a Promise-compatible instance. This allows interoperation between different - * Promise implementations, however a non-compliant object may cause a Promise - * to hang indefinitely. If the {@code then} method throws an exception, the - * dependent Promise will be rejected with the thrown value. - * - * @see http://promisesaplus.com/#point-70 - * - * @param {Thenable} thenable An object with a {@code then} method that may be - * compatible with the Promise/A+ specification. - * @param {!Function} then The {@code then} method of the Thenable object. - * @private - */ -goog.Promise.prototype.tryThen_ = function(thenable, then) { - this.state_ = goog.Promise.State_.BLOCKED; - var promise = this; - var called = false; - - var resolve = function(value) { - if (!called) { - called = true; - promise.unblockAndFulfill_(value); - } - }; - - var reject = function(reason) { - if (!called) { - called = true; - promise.unblockAndReject_(reason); - } - }; - - try { - then.call(thenable, resolve, reject); - } catch (e) { - reject(e); - } -}; - - -/** - * Executes the pending callbacks of a resolved Promise after a timeout. - * - * Section 2.2.4 of the Promises/A+ specification requires that Promise - * callbacks must only be invoked from a call stack that only contains Promise - * implementation code, which we accomplish by invoking callback execution after - * a timeout. If {@code startExecution_} is called multiple times for the same - * Promise, the callback chain will be evaluated only once. Additional callbacks - * may be added during the evaluation phase, and will be executed in the same - * event loop. - * - * All Promises added to the waiting list during the same browser event loop - * will be executed in one batch to avoid using a separate timeout per Promise. - * - * @private - */ -goog.Promise.prototype.scheduleCallbacks_ = function() { - if (!this.executing_) { - this.executing_ = true; - goog.async.run(this.executeCallbacks_, this); - } -}; - - -/** - * @return {boolean} Whether there are any pending callbacks queued. - * @private - */ -goog.Promise.prototype.hasEntry_ = function() { - return !!this.callbackEntries_; -}; - - -/** - * @param {goog.Promise.CallbackEntry_} entry - * @private - */ -goog.Promise.prototype.queueEntry_ = function(entry) { - goog.asserts.assert(entry.onFulfilled != null); - - if (this.callbackEntriesTail_) { - this.callbackEntriesTail_.next = entry; - this.callbackEntriesTail_ = entry; - } else { - // It the work queue was empty set the head too. - this.callbackEntries_ = entry; - this.callbackEntriesTail_ = entry; - } -}; - - -/** - * @return {goog.Promise.CallbackEntry_} entry - * @private - */ -goog.Promise.prototype.popEntry_ = function() { - var entry = null; - if (this.callbackEntries_) { - entry = this.callbackEntries_; - this.callbackEntries_ = entry.next; - entry.next = null; - } - // It the work queue is empty clear the tail too. - if (!this.callbackEntries_) { - this.callbackEntriesTail_ = null; - } - - if (entry != null) { - goog.asserts.assert(entry.onFulfilled != null); - } - return entry; -}; - - -/** - * @param {goog.Promise.CallbackEntry_} previous - * @private - */ -goog.Promise.prototype.removeEntryAfter_ = function(previous) { - goog.asserts.assert(this.callbackEntries_); - goog.asserts.assert(previous != null); - // If the last entry is being removed, update the tail - if (previous.next == this.callbackEntriesTail_) { - this.callbackEntriesTail_ = previous; - } - - previous.next = previous.next.next; -}; - - -/** - * Executes all pending callbacks for this Promise. - * - * @private - */ -goog.Promise.prototype.executeCallbacks_ = function() { - var entry = null; - while (entry = this.popEntry_()) { - if (goog.Promise.LONG_STACK_TRACES) { - this.currentStep_++; - } - this.executeCallback_(entry, this.state_, this.result_); - } - this.executing_ = false; -}; - - -/** - * Executes a pending callback for this Promise. Invokes an {@code onFulfilled} - * or {@code onRejected} callback based on the resolved state of the Promise. - * - * @param {!goog.Promise.CallbackEntry_} callbackEntry An entry containing the - * onFulfilled and/or onRejected callbacks for this step. - * @param {goog.Promise.State_} state The resolution status of the Promise, - * either FULFILLED or REJECTED. - * @param {*} result The resolved result of the Promise. - * @private - */ -goog.Promise.prototype.executeCallback_ = function( - callbackEntry, state, result) { - // When the parent is resolved/rejected, the child no longer needs to hold - // on to it, as the parent can no longer be cancelled. - if (callbackEntry.child) { - callbackEntry.child.parent_ = null; - } - if (state == goog.Promise.State_.FULFILLED) { - callbackEntry.onFulfilled.call(callbackEntry.context, result); - } else if (callbackEntry.onRejected != null) { - if (!callbackEntry.always) { - this.removeUnhandledRejection_(); - } - callbackEntry.onRejected.call(callbackEntry.context, result); - } - goog.Promise.returnEntry_(callbackEntry); -}; - - -/** - * Records a stack trace entry for functions that call {@code then} or the - * Promise constructor. May be disabled by unsetting {@code LONG_STACK_TRACES}. - * - * @param {!Error} err An Error object created by the calling function for - * providing a stack trace. - * @private - */ -goog.Promise.prototype.addStackTrace_ = function(err) { - if (goog.Promise.LONG_STACK_TRACES && goog.isString(err.stack)) { - // Extract the third line of the stack trace, which is the entry for the - // user function that called into Promise code. - var trace = err.stack.split('\n', 4)[3]; - var message = err.message; - - // Pad the message to align the traces. - message += Array(11 - message.length).join(' '); - this.stack_.push(message + trace); - } -}; - - -/** - * Adds extra stack trace information to an exception for the list of - * asynchronous {@code then} calls that have been run for this Promise. Stack - * trace information is recorded in {@see #addStackTrace_}, and appended to - * rethrown errors when {@code LONG_STACK_TRACES} is enabled. - * - * @param {*} err An unhandled exception captured during callback execution. - * @private - */ -goog.Promise.prototype.appendLongStack_ = function(err) { - if (goog.Promise.LONG_STACK_TRACES && - err && goog.isString(err.stack) && this.stack_.length) { - var longTrace = ['Promise trace:']; - - for (var promise = this; promise; promise = promise.parent_) { - for (var i = this.currentStep_; i >= 0; i--) { - longTrace.push(promise.stack_[i]); - } - longTrace.push('Value: ' + - '[' + (promise.state_ == goog.Promise.State_.REJECTED ? - 'REJECTED' : 'FULFILLED') + '] ' + - '<' + String(promise.result_) + '>'); - } - err.stack += '\n\n' + longTrace.join('\n'); - } -}; - - -/** - * Marks this rejected Promise as having being handled. Also marks any parent - * Promises in the rejected state as handled. The rejection handler will no - * longer be invoked for this Promise (if it has not been called already). - * - * @private - */ -goog.Promise.prototype.removeUnhandledRejection_ = function() { - if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) { - for (var p = this; p && p.unhandledRejectionId_; p = p.parent_) { - goog.global.clearTimeout(p.unhandledRejectionId_); - p.unhandledRejectionId_ = 0; - } - } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) { - for (var p = this; p && p.hadUnhandledRejection_; p = p.parent_) { - p.hadUnhandledRejection_ = false; - } - } -}; - - -/** - * Marks this rejected Promise as unhandled. If no {@code onRejected} callback - * is called for this Promise before the {@code UNHANDLED_REJECTION_DELAY} - * expires, the reason will be passed to the unhandled rejection handler. The - * handler typically rethrows the rejection reason so that it becomes visible in - * the developer console. - * - * @param {!goog.Promise} promise The rejected Promise. - * @param {*} reason The Promise rejection reason. - * @private - */ -goog.Promise.addUnhandledRejection_ = function(promise, reason) { - if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) { - promise.unhandledRejectionId_ = goog.global.setTimeout(function() { - promise.appendLongStack_(reason); - goog.Promise.handleRejection_.call(null, reason); - }, goog.Promise.UNHANDLED_REJECTION_DELAY); - - } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) { - promise.hadUnhandledRejection_ = true; - goog.async.run(function() { - if (promise.hadUnhandledRejection_) { - promise.appendLongStack_(reason); - goog.Promise.handleRejection_.call(null, reason); - } - }); - } -}; - - -/** - * A method that is invoked with the rejection reasons for Promises that are - * rejected but have no {@code onRejected} callbacks registered yet. - * @type {function(*)} - * @private - */ -goog.Promise.handleRejection_ = goog.async.throwException; - - -/** - * Sets a handler that will be called with reasons from unhandled rejected - * Promises. If the rejected Promise (or one of its descendants) has an - * {@code onRejected} callback registered, the rejection will be considered - * handled, and the rejection handler will not be called. - * - * By default, unhandled rejections are rethrown so that the error may be - * captured by the developer console or a {@code window.onerror} handler. - * - * @param {function(*)} handler A function that will be called with reasons from - * rejected Promises. Defaults to {@code goog.async.throwException}. - */ -goog.Promise.setUnhandledRejectionHandler = function(handler) { - goog.Promise.handleRejection_ = handler; -}; - - - -/** - * Error used as a rejection reason for canceled Promises. - * - * @param {string=} opt_message - * @constructor - * @extends {goog.debug.Error} - * @final - */ -goog.Promise.CancellationError = function(opt_message) { - goog.Promise.CancellationError.base(this, 'constructor', opt_message); -}; -goog.inherits(goog.Promise.CancellationError, goog.debug.Error); - - -/** @override */ -goog.Promise.CancellationError.prototype.name = 'cancel'; - - - -/** - * Internal implementation of the resolver interface. - * - * @param {!goog.Promise<TYPE>} promise - * @param {function((TYPE|goog.Promise<TYPE>|Thenable)=)} resolve - * @param {function(*): void} reject - * @implements {goog.promise.Resolver<TYPE>} - * @final @struct - * @constructor - * @private - * @template TYPE - */ -goog.Promise.Resolver_ = function(promise, resolve, reject) { - /** @const */ - this.promise = promise; - - /** @const */ - this.resolve = resolve; - - /** @const */ - this.reject = reject; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/resolver.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/resolver.js deleted file mode 100644 index 06ee2e5..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/resolver.js +++ /dev/null @@ -1,48 +0,0 @@ -// 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. - -goog.provide('goog.promise.Resolver'); - - - -/** - * Resolver interface for promises. The resolver is a convenience interface that - * bundles the promise and its associated resolve and reject functions together, - * for cases where the resolver needs to be persisted internally. - * - * @interface - * @template TYPE - */ -goog.promise.Resolver = function() {}; - - -/** - * The promise that created this resolver. - * @type {!goog.Promise<TYPE>} - */ -goog.promise.Resolver.prototype.promise; - - -/** - * Resolves this resolver with the specified value. - * @type {function((TYPE|goog.Promise<TYPE>|Thenable)=)} - */ -goog.promise.Resolver.prototype.resolve; - - -/** - * Rejects this resolver with the specified reason. - * @type {function(*): void} - */ -goog.promise.Resolver.prototype.reject; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/thenable.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/thenable.js deleted file mode 100644 index 96bbf95..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/promise/thenable.js +++ /dev/null @@ -1,111 +0,0 @@ -// 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. - -goog.provide('goog.Thenable'); - - - -/** - * Provides a more strict interface for Thenables in terms of - * http://promisesaplus.com for interop with {@see goog.Promise}. - * - * @interface - * @extends {IThenable<TYPE>} - * @template TYPE - */ -goog.Thenable = function() {}; - - -/** - * Adds callbacks that will operate on the result of the Thenable, returning a - * new child Promise. - * - * If the Thenable is fulfilled, the {@code onFulfilled} callback will be - * invoked with the fulfillment value as argument, and the child Promise will - * be fulfilled with the return value of the callback. If the callback throws - * an exception, the child Promise will be rejected with the thrown value - * instead. - * - * If the Thenable is rejected, the {@code onRejected} callback will be invoked - * with the rejection reason as argument, and the child Promise will be rejected - * with the return value of the callback or thrown value. - * - * @param {?(function(this:THIS, TYPE): - * (RESULT|IThenable<RESULT>|Thenable))=} opt_onFulfilled A - * function that will be invoked with the fulfillment value if the Promise - * is fullfilled. - * @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will - * be invoked with the rejection reason if the Promise is rejected. - * @param {THIS=} opt_context An optional context object that will be the - * execution context for the callbacks. By default, functions are executed - * with the default this. - * @return {!goog.Promise<RESULT>} A new Promise that will receive the result - * of the fulfillment or rejection callback. - * @template RESULT,THIS - */ -goog.Thenable.prototype.then = function(opt_onFulfilled, opt_onRejected, - opt_context) {}; - - -/** - * An expando property to indicate that an object implements - * {@code goog.Thenable}. - * - * {@see addImplementation}. - * - * @const - */ -goog.Thenable.IMPLEMENTED_BY_PROP = '$goog_Thenable'; - - -/** - * Marks a given class (constructor) as an implementation of Thenable, so - * that we can query that fact at runtime. The class must have already - * implemented the interface. - * Exports a 'then' method on the constructor prototype, so that the objects - * also implement the extern {@see goog.Thenable} interface for interop with - * other Promise implementations. - * @param {function(new:goog.Thenable,...?)} ctor The class constructor. The - * corresponding class must have already implemented the interface. - */ -goog.Thenable.addImplementation = function(ctor) { - goog.exportProperty(ctor.prototype, 'then', ctor.prototype.then); - if (COMPILED) { - ctor.prototype[goog.Thenable.IMPLEMENTED_BY_PROP] = true; - } else { - // Avoids dictionary access in uncompiled mode. - ctor.prototype.$goog_Thenable = true; - } -}; - - -/** - * @param {*} object - * @return {boolean} Whether a given instance implements {@code goog.Thenable}. - * The class/superclass of the instance must call {@code addImplementation}. - */ -goog.Thenable.isImplementedBy = function(object) { - if (!object) { - return false; - } - try { - if (COMPILED) { - return !!object[goog.Thenable.IMPLEMENTED_BY_PROP]; - } - return !!object.$goog_Thenable; - } catch (e) { - // Property access seems to be forbidden. - return false; - } -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/reflect/reflect.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/reflect/reflect.js deleted file mode 100644 index c49050f..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/reflect/reflect.js +++ /dev/null @@ -1,78 +0,0 @@ -// 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 Useful compiler idioms. - * - * @author johnlenz@google.com (John Lenz) - */ - -goog.provide('goog.reflect'); - - -/** - * Syntax for object literal casts. - * @see http://go/jscompiler-renaming - * @see http://code.google.com/p/closure-compiler/wiki/ - * ExperimentalTypeBasedPropertyRenaming - * - * Use this if you have an object literal whose keys need to have the same names - * as the properties of some class even after they are renamed by the compiler. - * - * @param {!Function} type Type to cast to. - * @param {Object} object Object literal to cast. - * @return {Object} The object literal. - */ -goog.reflect.object = function(type, object) { - return object; -}; - - -/** - * To assert to the compiler that an operation is needed when it would - * otherwise be stripped. For example: - * <code> - * // Force a layout - * goog.reflect.sinkValue(dialog.offsetHeight); - * </code> - * @type {!Function} - */ -goog.reflect.sinkValue = function(x) { - goog.reflect.sinkValue[' '](x); - return x; -}; - - -/** - * The compiler should optimize this function away iff no one ever uses - * goog.reflect.sinkValue. - */ -goog.reflect.sinkValue[' '] = goog.nullFunction; - - -/** - * Check if a property can be accessed without throwing an exception. - * @param {Object} obj The owner of the property. - * @param {string} prop The property name. - * @return {boolean} Whether the property is accessible. Will also return true - * if obj is null. - */ -goog.reflect.canAccessProperty = function(obj, prop) { - /** @preserveTry */ - try { - goog.reflect.sinkValue(obj[prop]); - return true; - } catch (e) {} - return false; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/const.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/const.js deleted file mode 100644 index 76cac4f..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/const.js +++ /dev/null @@ -1,182 +0,0 @@ -// 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. - -goog.provide('goog.string.Const'); - -goog.require('goog.asserts'); -goog.require('goog.string.TypedString'); - - - -/** - * Wrapper for compile-time-constant strings. - * - * Const is a wrapper for strings that can only be created from program - * constants (i.e., string literals). This property relies on a custom Closure - * compiler check that {@code goog.string.Const.from} is only invoked on - * compile-time-constant expressions. - * - * Const is useful in APIs whose correct and secure use requires that certain - * arguments are not attacker controlled: Compile-time constants are inherently - * under the control of the application and not under control of external - * attackers, and hence are safe to use in such contexts. - * - * Instances of this type must be created via its factory method - * {@code goog.string.Const.from} and not by invoking its constructor. The - * constructor intentionally takes no parameters and the type is immutable; - * hence only a default instance corresponding to the empty string can be - * obtained via constructor invocation. - * - * @see goog.string.Const#from - * @constructor - * @final - * @struct - * @implements {goog.string.TypedString} - */ -goog.string.Const = function() { - /** - * The wrapped value of this Const object. The field has a purposely ugly - * name to make (non-compiled) code that attempts to directly access this - * field stand out. - * @private {string} - */ - this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ = ''; - - /** - * A type marker used to implement additional run-time type checking. - * @see goog.string.Const#unwrap - * @const - * @private - */ - this.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ = - goog.string.Const.TYPE_MARKER_; -}; - - -/** - * @override - * @const - */ -goog.string.Const.prototype.implementsGoogStringTypedString = true; - - -/** - * Returns this Const's value a string. - * - * IMPORTANT: In code where it is security-relevant that an object's type is - * indeed {@code goog.string.Const}, use {@code goog.string.Const.unwrap} - * instead of this method. - * - * @see goog.string.Const#unwrap - * @override - */ -goog.string.Const.prototype.getTypedStringValue = function() { - return this.stringConstValueWithSecurityContract__googStringSecurityPrivate_; -}; - - -/** - * Returns a debug-string representation of this value. - * - * To obtain the actual string value wrapped inside an object of this type, - * use {@code goog.string.Const.unwrap}. - * - * @see goog.string.Const#unwrap - * @override - */ -goog.string.Const.prototype.toString = function() { - return 'Const{' + - this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ + - '}'; -}; - - -/** - * Performs a runtime check that the provided object is indeed an instance - * of {@code goog.string.Const}, and returns its value. - * @param {!goog.string.Const} stringConst The object to extract from. - * @return {string} The Const object's contained string, unless the run-time - * type check fails. In that case, {@code unwrap} returns an innocuous - * string, or, if assertions are enabled, throws - * {@code goog.asserts.AssertionError}. - */ -goog.string.Const.unwrap = function(stringConst) { - // Perform additional run-time type-checking to ensure that stringConst is - // indeed an instance of the expected type. This provides some additional - // protection against security bugs due to application code that disables type - // checks. - if (stringConst instanceof goog.string.Const && - stringConst.constructor === goog.string.Const && - stringConst.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ === - goog.string.Const.TYPE_MARKER_) { - return stringConst. - stringConstValueWithSecurityContract__googStringSecurityPrivate_; - } else { - goog.asserts.fail('expected object of type Const, got \'' + - stringConst + '\''); - return 'type_error:Const'; - } -}; - - -/** - * Creates a Const object from a compile-time constant string. - * - * It is illegal to invoke this function on an expression whose - * compile-time-contant value cannot be determined by the Closure compiler. - * - * Correct invocations include, - * <pre> - * var s = goog.string.Const.from('hello'); - * var t = goog.string.Const.from('hello' + 'world'); - * </pre> - * - * In contrast, the following are illegal: - * <pre> - * var s = goog.string.Const.from(getHello()); - * var t = goog.string.Const.from('hello' + world); - * </pre> - * - * TODO(user): Compile-time checks that this function is only called - * with compile-time constant expressions. - * - * @param {string} s A constant string from which to create a Const. - * @return {!goog.string.Const} A Const object initialized to stringConst. - */ -goog.string.Const.from = function(s) { - return goog.string.Const.create__googStringSecurityPrivate_(s); -}; - - -/** - * Type marker for the Const type, used to implement additional run-time - * type checking. - * @const - * @private - */ -goog.string.Const.TYPE_MARKER_ = {}; - - -/** - * Utility method to create Const instances. - * @param {string} s The string to initialize the Const object with. - * @return {!goog.string.Const} The initialized Const object. - * @private - */ -goog.string.Const.create__googStringSecurityPrivate_ = function(s) { - var stringConst = new goog.string.Const(); - stringConst.stringConstValueWithSecurityContract__googStringSecurityPrivate_ = - s; - return stringConst; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/string.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/string.js deleted file mode 100644 index 065a1a8..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/string.js +++ /dev/null @@ -1,1565 +0,0 @@ -// 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 for string manipulation. - * @author arv@google.com (Erik Arvidsson) - */ - - -/** - * Namespace for string utilities - */ -goog.provide('goog.string'); -goog.provide('goog.string.Unicode'); - - -/** - * @define {boolean} Enables HTML escaping of lowercase letter "e" which helps - * with detection of double-escaping as this letter is frequently used. - */ -goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false); - - -/** - * @define {boolean} Whether to force non-dom html unescaping. - */ -goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false); - - -/** - * Common Unicode string characters. - * @enum {string} - */ -goog.string.Unicode = { - NBSP: '\xa0' -}; - - -/** - * Fast prefix-checker. - * @param {string} str The string to check. - * @param {string} prefix A string to look for at the start of {@code str}. - * @return {boolean} True if {@code str} begins with {@code prefix}. - */ -goog.string.startsWith = function(str, prefix) { - return str.lastIndexOf(prefix, 0) == 0; -}; - - -/** - * Fast suffix-checker. - * @param {string} str The string to check. - * @param {string} suffix A string to look for at the end of {@code str}. - * @return {boolean} True if {@code str} ends with {@code suffix}. - */ -goog.string.endsWith = function(str, suffix) { - var l = str.length - suffix.length; - return l >= 0 && str.indexOf(suffix, l) == l; -}; - - -/** - * Case-insensitive prefix-checker. - * @param {string} str The string to check. - * @param {string} prefix A string to look for at the end of {@code str}. - * @return {boolean} True if {@code str} begins with {@code prefix} (ignoring - * case). - */ -goog.string.caseInsensitiveStartsWith = function(str, prefix) { - return goog.string.caseInsensitiveCompare( - prefix, str.substr(0, prefix.length)) == 0; -}; - - -/** - * Case-insensitive suffix-checker. - * @param {string} str The string to check. - * @param {string} suffix A string to look for at the end of {@code str}. - * @return {boolean} True if {@code str} ends with {@code suffix} (ignoring - * case). - */ -goog.string.caseInsensitiveEndsWith = function(str, suffix) { - return goog.string.caseInsensitiveCompare( - suffix, str.substr(str.length - suffix.length, suffix.length)) == 0; -}; - - -/** - * Case-insensitive equality checker. - * @param {string} str1 First string to check. - * @param {string} str2 Second string to check. - * @return {boolean} True if {@code str1} and {@code str2} are the same string, - * ignoring case. - */ -goog.string.caseInsensitiveEquals = function(str1, str2) { - return str1.toLowerCase() == str2.toLowerCase(); -}; - - -/** - * Does simple python-style string substitution. - * subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog". - * @param {string} str The string containing the pattern. - * @param {...*} var_args The items to substitute into the pattern. - * @return {string} A copy of {@code str} in which each occurrence of - * {@code %s} has been replaced an argument from {@code var_args}. - */ -goog.string.subs = function(str, var_args) { - var splitParts = str.split('%s'); - var returnString = ''; - - var subsArguments = Array.prototype.slice.call(arguments, 1); - while (subsArguments.length && - // Replace up to the last split part. We are inserting in the - // positions between split parts. - splitParts.length > 1) { - returnString += splitParts.shift() + subsArguments.shift(); - } - - return returnString + splitParts.join('%s'); // Join unused '%s' -}; - - -/** - * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines - * and tabs) to a single space, and strips leading and trailing whitespace. - * @param {string} str Input string. - * @return {string} A copy of {@code str} with collapsed whitespace. - */ -goog.string.collapseWhitespace = function(str) { - // Since IE doesn't include non-breaking-space (0xa0) in their \s character - // class (as required by section 7.2 of the ECMAScript spec), we explicitly - // include it in the regexp to enforce consistent cross-browser behavior. - return str.replace(/[\s\xa0]+/g, ' ').replace(/^\s+|\s+$/g, ''); -}; - - -/** - * Checks if a string is empty or contains only whitespaces. - * @param {string} str The string to check. - * @return {boolean} Whether {@code str} is empty or whitespace only. - */ -goog.string.isEmptyOrWhitespace = function(str) { - // testing length == 0 first is actually slower in all browsers (about the - // same in Opera). - // Since IE doesn't include non-breaking-space (0xa0) in their \s character - // class (as required by section 7.2 of the ECMAScript spec), we explicitly - // include it in the regexp to enforce consistent cross-browser behavior. - return /^[\s\xa0]*$/.test(str); -}; - - -/** - * Checks if a string is empty. - * @param {string} str The string to check. - * @return {boolean} Whether {@code str} is empty. - */ -goog.string.isEmptyString = function(str) { - return str.length == 0; -}; - - -/** - * Checks if a string is empty or contains only whitespaces. - * - * TODO(user): Deprecate this when clients have been switched over to - * goog.string.isEmptyOrWhitespace. - * - * @param {string} str The string to check. - * @return {boolean} Whether {@code str} is empty or whitespace only. - */ -goog.string.isEmpty = goog.string.isEmptyOrWhitespace; - - -/** - * Checks if a string is null, undefined, empty or contains only whitespaces. - * @param {*} str The string to check. - * @return {boolean} Whether {@code str} is null, undefined, empty, or - * whitespace only. - * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str)) - * instead. - */ -goog.string.isEmptyOrWhitespaceSafe = function(str) { - return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str)); -}; - - -/** - * Checks if a string is null, undefined, empty or contains only whitespaces. - * - * TODO(user): Deprecate this when clients have been switched over to - * goog.string.isEmptyOrWhitespaceSafe. - * - * @param {*} str The string to check. - * @return {boolean} Whether {@code str} is null, undefined, empty, or - * whitespace only. - */ -goog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe; - - -/** - * Checks if a string is all breaking whitespace. - * @param {string} str The string to check. - * @return {boolean} Whether the string is all breaking whitespace. - */ -goog.string.isBreakingWhitespace = function(str) { - return !/[^\t\n\r ]/.test(str); -}; - - -/** - * Checks if a string contains all letters. - * @param {string} str string to check. - * @return {boolean} True if {@code str} consists entirely of letters. - */ -goog.string.isAlpha = function(str) { - return !/[^a-zA-Z]/.test(str); -}; - - -/** - * Checks if a string contains only numbers. - * @param {*} str string to check. If not a string, it will be - * casted to one. - * @return {boolean} True if {@code str} is numeric. - */ -goog.string.isNumeric = function(str) { - return !/[^0-9]/.test(str); -}; - - -/** - * Checks if a string contains only numbers or letters. - * @param {string} str string to check. - * @return {boolean} True if {@code str} is alphanumeric. - */ -goog.string.isAlphaNumeric = function(str) { - return !/[^a-zA-Z0-9]/.test(str); -}; - - -/** - * Checks if a character is a space character. - * @param {string} ch Character to check. - * @return {boolean} True if {@code ch} is a space. - */ -goog.string.isSpace = function(ch) { - return ch == ' '; -}; - - -/** - * Checks if a character is a valid unicode character. - * @param {string} ch Character to check. - * @return {boolean} True if {@code ch} is a valid unicode character. - */ -goog.string.isUnicodeChar = function(ch) { - return ch.length == 1 && ch >= ' ' && ch <= '~' || - ch >= '\u0080' && ch <= '\uFFFD'; -}; - - -/** - * Takes a string and replaces newlines with a space. Multiple lines are - * replaced with a single space. - * @param {string} str The string from which to strip newlines. - * @return {string} A copy of {@code str} stripped of newlines. - */ -goog.string.stripNewlines = function(str) { - return str.replace(/(\r\n|\r|\n)+/g, ' '); -}; - - -/** - * Replaces Windows and Mac new lines with unix style: \r or \r\n with \n. - * @param {string} str The string to in which to canonicalize newlines. - * @return {string} {@code str} A copy of {@code} with canonicalized newlines. - */ -goog.string.canonicalizeNewlines = function(str) { - return str.replace(/(\r\n|\r|\n)/g, '\n'); -}; - - -/** - * Normalizes whitespace in a string, replacing all whitespace chars with - * a space. - * @param {string} str The string in which to normalize whitespace. - * @return {string} A copy of {@code str} with all whitespace normalized. - */ -goog.string.normalizeWhitespace = function(str) { - return str.replace(/\xa0|\s/g, ' '); -}; - - -/** - * Normalizes spaces in a string, replacing all consecutive spaces and tabs - * with a single space. Replaces non-breaking space with a space. - * @param {string} str The string in which to normalize spaces. - * @return {string} A copy of {@code str} with all consecutive spaces and tabs - * replaced with a single space. - */ -goog.string.normalizeSpaces = function(str) { - return str.replace(/\xa0|[ \t]+/g, ' '); -}; - - -/** - * Removes the breaking spaces from the left and right of the string and - * collapses the sequences of breaking spaces in the middle into single spaces. - * The original and the result strings render the same way in HTML. - * @param {string} str A string in which to collapse spaces. - * @return {string} Copy of the string with normalized breaking spaces. - */ -goog.string.collapseBreakingSpaces = function(str) { - return str.replace(/[\t\r\n ]+/g, ' ').replace( - /^[\t\r\n ]+|[\t\r\n ]+$/g, ''); -}; - - -/** - * Trims white spaces to the left and right of a string. - * @param {string} str The string to trim. - * @return {string} A trimmed copy of {@code str}. - */ -goog.string.trim = (goog.TRUSTED_SITE && String.prototype.trim) ? - function(str) { - return str.trim(); - } : - function(str) { - // Since IE doesn't include non-breaking-space (0xa0) in their \s - // character class (as required by section 7.2 of the ECMAScript spec), - // we explicitly include it in the regexp to enforce consistent - // cross-browser behavior. - return str.replace(/^[\s\xa0]+|[\s\xa0]+$/g, ''); - }; - - -/** - * Trims whitespaces at the left end of a string. - * @param {string} str The string to left trim. - * @return {string} A trimmed copy of {@code str}. - */ -goog.string.trimLeft = function(str) { - // Since IE doesn't include non-breaking-space (0xa0) in their \s character - // class (as required by section 7.2 of the ECMAScript spec), we explicitly - // include it in the regexp to enforce consistent cross-browser behavior. - return str.replace(/^[\s\xa0]+/, ''); -}; - - -/** - * Trims whitespaces at the right end of a string. - * @param {string} str The string to right trim. - * @return {string} A trimmed copy of {@code str}. - */ -goog.string.trimRight = function(str) { - // Since IE doesn't include non-breaking-space (0xa0) in their \s character - // class (as required by section 7.2 of the ECMAScript spec), we explicitly - // include it in the regexp to enforce consistent cross-browser behavior. - return str.replace(/[\s\xa0]+$/, ''); -}; - - -/** - * A string comparator that ignores case. - * -1 = str1 less than str2 - * 0 = str1 equals str2 - * 1 = str1 greater than str2 - * - * @param {string} str1 The string to compare. - * @param {string} str2 The string to compare {@code str1} to. - * @return {number} The comparator result, as described above. - */ -goog.string.caseInsensitiveCompare = function(str1, str2) { - var test1 = String(str1).toLowerCase(); - var test2 = String(str2).toLowerCase(); - - if (test1 < test2) { - return -1; - } else if (test1 == test2) { - return 0; - } else { - return 1; - } -}; - - -/** - * Regular expression used for splitting a string into substrings of fractional - * numbers, integers, and non-numeric characters. - * @type {RegExp} - * @private - */ -goog.string.numerateCompareRegExp_ = /(\.\d+)|(\d+)|(\D+)/g; - - -/** - * String comparison function that handles numbers in a way humans might expect. - * Using this function, the string "File 2.jpg" sorts before "File 10.jpg". The - * comparison is mostly case-insensitive, though strings that are identical - * except for case are sorted with the upper-case strings before lower-case. - * - * This comparison function is significantly slower (about 500x) than either - * the default or the case-insensitive compare. It should not be used in - * time-critical code, but should be fast enough to sort several hundred short - * strings (like filenames) with a reasonable delay. - * - * @param {string} str1 The string to compare in a numerically sensitive way. - * @param {string} str2 The string to compare {@code str1} to. - * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than - * 0 if str1 > str2. - */ -goog.string.numerateCompare = function(str1, str2) { - if (str1 == str2) { - return 0; - } - if (!str1) { - return -1; - } - if (!str2) { - return 1; - } - - // Using match to split the entire string ahead of time turns out to be faster - // for most inputs than using RegExp.exec or iterating over each character. - var tokens1 = str1.toLowerCase().match(goog.string.numerateCompareRegExp_); - var tokens2 = str2.toLowerCase().match(goog.string.numerateCompareRegExp_); - - var count = Math.min(tokens1.length, tokens2.length); - - for (var i = 0; i < count; i++) { - var a = tokens1[i]; - var b = tokens2[i]; - - // Compare pairs of tokens, returning if one token sorts before the other. - if (a != b) { - - // Only if both tokens are integers is a special comparison required. - // Decimal numbers are sorted as strings (e.g., '.09' < '.1'). - var num1 = parseInt(a, 10); - if (!isNaN(num1)) { - var num2 = parseInt(b, 10); - if (!isNaN(num2) && num1 - num2) { - return num1 - num2; - } - } - return a < b ? -1 : 1; - } - } - - // If one string is a substring of the other, the shorter string sorts first. - if (tokens1.length != tokens2.length) { - return tokens1.length - tokens2.length; - } - - // The two strings must be equivalent except for case (perfect equality is - // tested at the head of the function.) Revert to default ASCII-betical string - // comparison to stablize the sort. - return str1 < str2 ? -1 : 1; -}; - - -/** - * URL-encodes a string - * @param {*} str The string to url-encode. - * @return {string} An encoded copy of {@code str} that is safe for urls. - * Note that '#', ':', and other characters used to delimit portions - * of URLs *will* be encoded. - */ -goog.string.urlEncode = function(str) { - return encodeURIComponent(String(str)); -}; - - -/** - * URL-decodes the string. We need to specially handle '+'s because - * the javascript library doesn't convert them to spaces. - * @param {string} str The string to url decode. - * @return {string} The decoded {@code str}. - */ -goog.string.urlDecode = function(str) { - return decodeURIComponent(str.replace(/\+/g, ' ')); -}; - - -/** - * Converts \n to <br>s or <br />s. - * @param {string} str The string in which to convert newlines. - * @param {boolean=} opt_xml Whether to use XML compatible tags. - * @return {string} A copy of {@code str} with converted newlines. - */ -goog.string.newLineToBr = function(str, opt_xml) { - return str.replace(/(\r\n|\r|\n)/g, opt_xml ? '<br />' : '<br>'); -}; - - -/** - * Escapes double quote '"' and single quote '\'' characters in addition to - * '&', '<', and '>' so that a string can be included in an HTML tag attribute - * value within double or single quotes. - * - * It should be noted that > doesn't need to be escaped for the HTML or XML to - * be valid, but it has been decided to escape it for consistency with other - * implementations. - * - * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the - * lowercase letter "e". - * - * NOTE(user): - * HtmlEscape is often called during the generation of large blocks of HTML. - * Using statics for the regular expressions and strings is an optimization - * that can more than half the amount of time IE spends in this function for - * large apps, since strings and regexes both contribute to GC allocations. - * - * Testing for the presence of a character before escaping increases the number - * of function calls, but actually provides a speed increase for the average - * case -- since the average case often doesn't require the escaping of all 4 - * characters and indexOf() is much cheaper than replace(). - * The worst case does suffer slightly from the additional calls, therefore the - * opt_isLikelyToContainHtmlChars option has been included for situations - * where all 4 HTML entities are very likely to be present and need escaping. - * - * Some benchmarks (times tended to fluctuate +-0.05ms): - * FireFox IE6 - * (no chars / average (mix of cases) / all 4 chars) - * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80 - * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84 - * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85 - * - * An additional advantage of checking if replace actually needs to be called - * is a reduction in the number of object allocations, so as the size of the - * application grows the difference between the various methods would increase. - * - * @param {string} str string to be escaped. - * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see - * if the character needs replacing - use this option if you expect each of - * the characters to appear often. Leave false if you expect few html - * characters to occur in your strings, such as if you are escaping HTML. - * @return {string} An escaped copy of {@code str}. - */ -goog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) { - - if (opt_isLikelyToContainHtmlChars) { - str = str.replace(goog.string.AMP_RE_, '&') - .replace(goog.string.LT_RE_, '<') - .replace(goog.string.GT_RE_, '>') - .replace(goog.string.QUOT_RE_, '"') - .replace(goog.string.SINGLE_QUOTE_RE_, ''') - .replace(goog.string.NULL_RE_, '�'); - if (goog.string.DETECT_DOUBLE_ESCAPING) { - str = str.replace(goog.string.E_RE_, 'e'); - } - return str; - - } else { - // quick test helps in the case when there are no chars to replace, in - // worst case this makes barely a difference to the time taken - if (!goog.string.ALL_RE_.test(str)) return str; - - // str.indexOf is faster than regex.test in this case - if (str.indexOf('&') != -1) { - str = str.replace(goog.string.AMP_RE_, '&'); - } - if (str.indexOf('<') != -1) { - str = str.replace(goog.string.LT_RE_, '<'); - } - if (str.indexOf('>') != -1) { - str = str.replace(goog.string.GT_RE_, '>'); - } - if (str.indexOf('"') != -1) { - str = str.replace(goog.string.QUOT_RE_, '"'); - } - if (str.indexOf('\'') != -1) { - str = str.replace(goog.string.SINGLE_QUOTE_RE_, '''); - } - if (str.indexOf('\x00') != -1) { - str = str.replace(goog.string.NULL_RE_, '�'); - } - if (goog.string.DETECT_DOUBLE_ESCAPING && str.indexOf('e') != -1) { - str = str.replace(goog.string.E_RE_, 'e'); - } - return str; - } -}; - - -/** - * Regular expression that matches an ampersand, for use in escaping. - * @const {!RegExp} - * @private - */ -goog.string.AMP_RE_ = /&/g; - - -/** - * Regular expression that matches a less than sign, for use in escaping. - * @const {!RegExp} - * @private - */ -goog.string.LT_RE_ = /</g; - - -/** - * Regular expression that matches a greater than sign, for use in escaping. - * @const {!RegExp} - * @private - */ -goog.string.GT_RE_ = />/g; - - -/** - * Regular expression that matches a double quote, for use in escaping. - * @const {!RegExp} - * @private - */ -goog.string.QUOT_RE_ = /"/g; - - -/** - * Regular expression that matches a single quote, for use in escaping. - * @const {!RegExp} - * @private - */ -goog.string.SINGLE_QUOTE_RE_ = /'/g; - - -/** - * Regular expression that matches null character, for use in escaping. - * @const {!RegExp} - * @private - */ -goog.string.NULL_RE_ = /\x00/g; - - -/** - * Regular expression that matches a lowercase letter "e", for use in escaping. - * @const {!RegExp} - * @private - */ -goog.string.E_RE_ = /e/g; - - -/** - * Regular expression that matches any character that needs to be escaped. - * @const {!RegExp} - * @private - */ -goog.string.ALL_RE_ = (goog.string.DETECT_DOUBLE_ESCAPING ? - /[\x00&<>"'e]/ : - /[\x00&<>"']/); - - -/** - * Unescapes an HTML string. - * - * @param {string} str The string to unescape. - * @return {string} An unescaped copy of {@code str}. - */ -goog.string.unescapeEntities = function(str) { - if (goog.string.contains(str, '&')) { - // We are careful not to use a DOM if we do not have one or we explicitly - // requested non-DOM html unescaping. - if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING && - 'document' in goog.global) { - return goog.string.unescapeEntitiesUsingDom_(str); - } else { - // Fall back on pure XML entities - return goog.string.unescapePureXmlEntities_(str); - } - } - return str; -}; - - -/** - * Unescapes a HTML string using the provided document. - * - * @param {string} str The string to unescape. - * @param {!Document} document A document to use in escaping the string. - * @return {string} An unescaped copy of {@code str}. - */ -goog.string.unescapeEntitiesWithDocument = function(str, document) { - if (goog.string.contains(str, '&')) { - return goog.string.unescapeEntitiesUsingDom_(str, document); - } - return str; -}; - - -/** - * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric - * entities. This function is XSS-safe and whitespace-preserving. - * @private - * @param {string} str The string to unescape. - * @param {Document=} opt_document An optional document to use for creating - * elements. If this is not specified then the default window.document - * will be used. - * @return {string} The unescaped {@code str} string. - */ -goog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) { - /** @type {!Object<string, string>} */ - var seen = {'&': '&', '<': '<', '>': '>', '"': '"'}; - var div; - if (opt_document) { - div = opt_document.createElement('div'); - } else { - div = goog.global.document.createElement('div'); - } - // Match as many valid entity characters as possible. If the actual entity - // happens to be shorter, it will still work as innerHTML will return the - // trailing characters unchanged. Since the entity characters do not include - // open angle bracket, there is no chance of XSS from the innerHTML use. - // Since no whitespace is passed to innerHTML, whitespace is preserved. - return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) { - // Check for cached entity. - var value = seen[s]; - if (value) { - return value; - } - // Check for numeric entity. - if (entity.charAt(0) == '#') { - // Prefix with 0 so that hex entities (e.g. ) parse as hex numbers. - var n = Number('0' + entity.substr(1)); - if (!isNaN(n)) { - value = String.fromCharCode(n); - } - } - // Fall back to innerHTML otherwise. - if (!value) { - // Append a non-entity character to avoid a bug in Webkit that parses - // an invalid entity at the end of innerHTML text as the empty string. - div.innerHTML = s + ' '; - // Then remove the trailing character from the result. - value = div.firstChild.nodeValue.slice(0, -1); - } - // Cache and return. - return seen[s] = value; - }); -}; - - -/** - * Unescapes XML entities. - * @private - * @param {string} str The string to unescape. - * @return {string} An unescaped copy of {@code str}. - */ -goog.string.unescapePureXmlEntities_ = function(str) { - return str.replace(/&([^;]+);/g, function(s, entity) { - switch (entity) { - case 'amp': - return '&'; - case 'lt': - return '<'; - case 'gt': - return '>'; - case 'quot': - return '"'; - default: - if (entity.charAt(0) == '#') { - // Prefix with 0 so that hex entities (e.g. ) parse as hex. - var n = Number('0' + entity.substr(1)); - if (!isNaN(n)) { - return String.fromCharCode(n); - } - } - // For invalid entities we just return the entity - return s; - } - }); -}; - - -/** - * Regular expression that matches an HTML entity. - * See also HTML5: Tokenization / Tokenizing character references. - * @private - * @type {!RegExp} - */ -goog.string.HTML_ENTITY_PATTERN_ = /&([^;\s<&]+);?/g; - - -/** - * Do escaping of whitespace to preserve spatial formatting. We use character - * entity #160 to make it safer for xml. - * @param {string} str The string in which to escape whitespace. - * @param {boolean=} opt_xml Whether to use XML compatible tags. - * @return {string} An escaped copy of {@code str}. - */ -goog.string.whitespaceEscape = function(str, opt_xml) { - // This doesn't use goog.string.preserveSpaces for backwards compatibility. - return goog.string.newLineToBr(str.replace(/ /g, '  '), opt_xml); -}; - - -/** - * Preserve spaces that would be otherwise collapsed in HTML by replacing them - * with non-breaking space Unicode characters. - * @param {string} str The string in which to preserve whitespace. - * @return {string} A copy of {@code str} with preserved whitespace. - */ -goog.string.preserveSpaces = function(str) { - return str.replace(/(^|[\n ]) /g, '$1' + goog.string.Unicode.NBSP); -}; - - -/** - * Strip quote characters around a string. The second argument is a string of - * characters to treat as quotes. This can be a single character or a string of - * multiple character and in that case each of those are treated as possible - * quote characters. For example: - * - * <pre> - * goog.string.stripQuotes('"abc"', '"`') --> 'abc' - * goog.string.stripQuotes('`abc`', '"`') --> 'abc' - * </pre> - * - * @param {string} str The string to strip. - * @param {string} quoteChars The quote characters to strip. - * @return {string} A copy of {@code str} without the quotes. - */ -goog.string.stripQuotes = function(str, quoteChars) { - var length = quoteChars.length; - for (var i = 0; i < length; i++) { - var quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i); - if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) { - return str.substring(1, str.length - 1); - } - } - return str; -}; - - -/** - * Truncates a string to a certain length and adds '...' if necessary. The - * length also accounts for the ellipsis, so a maximum length of 10 and a string - * 'Hello World!' produces 'Hello W...'. - * @param {string} str The string to truncate. - * @param {number} chars Max number of characters. - * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped - * characters from being cut off in the middle. - * @return {string} The truncated {@code str} string. - */ -goog.string.truncate = function(str, chars, opt_protectEscapedCharacters) { - if (opt_protectEscapedCharacters) { - str = goog.string.unescapeEntities(str); - } - - if (str.length > chars) { - str = str.substring(0, chars - 3) + '...'; - } - - if (opt_protectEscapedCharacters) { - str = goog.string.htmlEscape(str); - } - - return str; -}; - - -/** - * Truncate a string in the middle, adding "..." if necessary, - * and favoring the beginning of the string. - * @param {string} str The string to truncate the middle of. - * @param {number} chars Max number of characters. - * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped - * characters from being cutoff in the middle. - * @param {number=} opt_trailingChars Optional number of trailing characters to - * leave at the end of the string, instead of truncating as close to the - * middle as possible. - * @return {string} A truncated copy of {@code str}. - */ -goog.string.truncateMiddle = function(str, chars, - opt_protectEscapedCharacters, opt_trailingChars) { - if (opt_protectEscapedCharacters) { - str = goog.string.unescapeEntities(str); - } - - if (opt_trailingChars && str.length > chars) { - if (opt_trailingChars > chars) { - opt_trailingChars = chars; - } - var endPoint = str.length - opt_trailingChars; - var startPoint = chars - opt_trailingChars; - str = str.substring(0, startPoint) + '...' + str.substring(endPoint); - } else if (str.length > chars) { - // Favor the beginning of the string: - var half = Math.floor(chars / 2); - var endPos = str.length - half; - half += chars % 2; - str = str.substring(0, half) + '...' + str.substring(endPos); - } - - if (opt_protectEscapedCharacters) { - str = goog.string.htmlEscape(str); - } - - return str; -}; - - -/** - * Special chars that need to be escaped for goog.string.quote. - * @private {!Object<string, string>} - */ -goog.string.specialEscapeChars_ = { - '\0': '\\0', - '\b': '\\b', - '\f': '\\f', - '\n': '\\n', - '\r': '\\r', - '\t': '\\t', - '\x0B': '\\x0B', // '\v' is not supported in JScript - '"': '\\"', - '\\': '\\\\' -}; - - -/** - * Character mappings used internally for goog.string.escapeChar. - * @private {!Object<string, string>} - */ -goog.string.jsEscapeCache_ = { - '\'': '\\\'' -}; - - -/** - * Encloses a string in double quotes and escapes characters so that the - * string is a valid JS string. - * @param {string} s The string to quote. - * @return {string} A copy of {@code s} surrounded by double quotes. - */ -goog.string.quote = function(s) { - s = String(s); - if (s.quote) { - return s.quote(); - } else { - var sb = ['"']; - for (var i = 0; i < s.length; i++) { - var ch = s.charAt(i); - var cc = ch.charCodeAt(0); - sb[i + 1] = goog.string.specialEscapeChars_[ch] || - ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch)); - } - sb.push('"'); - return sb.join(''); - } -}; - - -/** - * Takes a string and returns the escaped string for that character. - * @param {string} str The string to escape. - * @return {string} An escaped string representing {@code str}. - */ -goog.string.escapeString = function(str) { - var sb = []; - for (var i = 0; i < str.length; i++) { - sb[i] = goog.string.escapeChar(str.charAt(i)); - } - return sb.join(''); -}; - - -/** - * Takes a character and returns the escaped string for that character. For - * example escapeChar(String.fromCharCode(15)) -> "\\x0E". - * @param {string} c The character to escape. - * @return {string} An escaped string representing {@code c}. - */ -goog.string.escapeChar = function(c) { - if (c in goog.string.jsEscapeCache_) { - return goog.string.jsEscapeCache_[c]; - } - - if (c in goog.string.specialEscapeChars_) { - return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c]; - } - - var rv = c; - var cc = c.charCodeAt(0); - if (cc > 31 && cc < 127) { - rv = c; - } else { - // tab is 9 but handled above - if (cc < 256) { - rv = '\\x'; - if (cc < 16 || cc > 256) { - rv += '0'; - } - } else { - rv = '\\u'; - if (cc < 4096) { // \u1000 - rv += '0'; - } - } - rv += cc.toString(16).toUpperCase(); - } - - return goog.string.jsEscapeCache_[c] = rv; -}; - - -/** - * Determines whether a string contains a substring. - * @param {string} str The string to search. - * @param {string} subString The substring to search for. - * @return {boolean} Whether {@code str} contains {@code subString}. - */ -goog.string.contains = function(str, subString) { - return str.indexOf(subString) != -1; -}; - - -/** - * Determines whether a string contains a substring, ignoring case. - * @param {string} str The string to search. - * @param {string} subString The substring to search for. - * @return {boolean} Whether {@code str} contains {@code subString}. - */ -goog.string.caseInsensitiveContains = function(str, subString) { - return goog.string.contains(str.toLowerCase(), subString.toLowerCase()); -}; - - -/** - * Returns the non-overlapping occurrences of ss in s. - * If either s or ss evalutes to false, then returns zero. - * @param {string} s The string to look in. - * @param {string} ss The string to look for. - * @return {number} Number of occurrences of ss in s. - */ -goog.string.countOf = function(s, ss) { - return s && ss ? s.split(ss).length - 1 : 0; -}; - - -/** - * Removes a substring of a specified length at a specific - * index in a string. - * @param {string} s The base string from which to remove. - * @param {number} index The index at which to remove the substring. - * @param {number} stringLength The length of the substring to remove. - * @return {string} A copy of {@code s} with the substring removed or the full - * string if nothing is removed or the input is invalid. - */ -goog.string.removeAt = function(s, index, stringLength) { - var resultStr = s; - // If the index is greater or equal to 0 then remove substring - if (index >= 0 && index < s.length && stringLength > 0) { - resultStr = s.substr(0, index) + - s.substr(index + stringLength, s.length - index - stringLength); - } - return resultStr; -}; - - -/** - * Removes the first occurrence of a substring from a string. - * @param {string} s The base string from which to remove. - * @param {string} ss The string to remove. - * @return {string} A copy of {@code s} with {@code ss} removed or the full - * string if nothing is removed. - */ -goog.string.remove = function(s, ss) { - var re = new RegExp(goog.string.regExpEscape(ss), ''); - return s.replace(re, ''); -}; - - -/** - * Removes all occurrences of a substring from a string. - * @param {string} s The base string from which to remove. - * @param {string} ss The string to remove. - * @return {string} A copy of {@code s} with {@code ss} removed or the full - * string if nothing is removed. - */ -goog.string.removeAll = function(s, ss) { - var re = new RegExp(goog.string.regExpEscape(ss), 'g'); - return s.replace(re, ''); -}; - - -/** - * Escapes characters in the string that are not safe to use in a RegExp. - * @param {*} s The string to escape. If not a string, it will be casted - * to one. - * @return {string} A RegExp safe, escaped copy of {@code s}. - */ -goog.string.regExpEscape = function(s) { - return String(s).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). - replace(/\x08/g, '\\x08'); -}; - - -/** - * Repeats a string n times. - * @param {string} string The string to repeat. - * @param {number} length The number of times to repeat. - * @return {string} A string containing {@code length} repetitions of - * {@code string}. - */ -goog.string.repeat = function(string, length) { - return new Array(length + 1).join(string); -}; - - -/** - * Pads number to given length and optionally rounds it to a given precision. - * For example: - * <pre>padNumber(1.25, 2, 3) -> '01.250' - * padNumber(1.25, 2) -> '01.25' - * padNumber(1.25, 2, 1) -> '01.3' - * padNumber(1.25, 0) -> '1.25'</pre> - * - * @param {number} num The number to pad. - * @param {number} length The desired length. - * @param {number=} opt_precision The desired precision. - * @return {string} {@code num} as a string with the given options. - */ -goog.string.padNumber = function(num, length, opt_precision) { - var s = goog.isDef(opt_precision) ? num.toFixed(opt_precision) : String(num); - var index = s.indexOf('.'); - if (index == -1) { - index = s.length; - } - return goog.string.repeat('0', Math.max(0, length - index)) + s; -}; - - -/** - * Returns a string representation of the given object, with - * null and undefined being returned as the empty string. - * - * @param {*} obj The object to convert. - * @return {string} A string representation of the {@code obj}. - */ -goog.string.makeSafe = function(obj) { - return obj == null ? '' : String(obj); -}; - - -/** - * Concatenates string expressions. This is useful - * since some browsers are very inefficient when it comes to using plus to - * concat strings. Be careful when using null and undefined here since - * these will not be included in the result. If you need to represent these - * be sure to cast the argument to a String first. - * For example: - * <pre>buildString('a', 'b', 'c', 'd') -> 'abcd' - * buildString(null, undefined) -> '' - * </pre> - * @param {...*} var_args A list of strings to concatenate. If not a string, - * it will be casted to one. - * @return {string} The concatenation of {@code var_args}. - */ -goog.string.buildString = function(var_args) { - return Array.prototype.join.call(arguments, ''); -}; - - -/** - * Returns a string with at least 64-bits of randomness. - * - * Doesn't trust Javascript's random function entirely. Uses a combination of - * random and current timestamp, and then encodes the string in base-36 to - * make it shorter. - * - * @return {string} A random string, e.g. sn1s7vb4gcic. - */ -goog.string.getRandomString = function() { - var x = 2147483648; - return Math.floor(Math.random() * x).toString(36) + - Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36); -}; - - -/** - * Compares two version numbers. - * - * @param {string|number} version1 Version of first item. - * @param {string|number} version2 Version of second item. - * - * @return {number} 1 if {@code version1} is higher. - * 0 if arguments are equal. - * -1 if {@code version2} is higher. - */ -goog.string.compareVersions = function(version1, version2) { - var order = 0; - // Trim leading and trailing whitespace and split the versions into - // subversions. - var v1Subs = goog.string.trim(String(version1)).split('.'); - var v2Subs = goog.string.trim(String(version2)).split('.'); - var subCount = Math.max(v1Subs.length, v2Subs.length); - - // Iterate over the subversions, as long as they appear to be equivalent. - for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) { - var v1Sub = v1Subs[subIdx] || ''; - var v2Sub = v2Subs[subIdx] || ''; - - // Split the subversions into pairs of numbers and qualifiers (like 'b'). - // Two different RegExp objects are needed because they are both using - // the 'g' flag. - var v1CompParser = new RegExp('(\\d*)(\\D*)', 'g'); - var v2CompParser = new RegExp('(\\d*)(\\D*)', 'g'); - do { - var v1Comp = v1CompParser.exec(v1Sub) || ['', '', '']; - var v2Comp = v2CompParser.exec(v2Sub) || ['', '', '']; - // Break if there are no more matches. - if (v1Comp[0].length == 0 && v2Comp[0].length == 0) { - break; - } - - // Parse the numeric part of the subversion. A missing number is - // equivalent to 0. - var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10); - var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10); - - // Compare the subversion components. The number has the highest - // precedence. Next, if the numbers are equal, a subversion without any - // qualifier is always higher than a subversion with any qualifier. Next, - // the qualifiers are compared as strings. - order = goog.string.compareElements_(v1CompNum, v2CompNum) || - goog.string.compareElements_(v1Comp[2].length == 0, - v2Comp[2].length == 0) || - goog.string.compareElements_(v1Comp[2], v2Comp[2]); - // Stop as soon as an inequality is discovered. - } while (order == 0); - } - - return order; -}; - - -/** - * Compares elements of a version number. - * - * @param {string|number|boolean} left An element from a version number. - * @param {string|number|boolean} right An element from a version number. - * - * @return {number} 1 if {@code left} is higher. - * 0 if arguments are equal. - * -1 if {@code right} is higher. - * @private - */ -goog.string.compareElements_ = function(left, right) { - if (left < right) { - return -1; - } else if (left > right) { - return 1; - } - return 0; -}; - - -/** - * Maximum value of #goog.string.hashCode, exclusive. 2^32. - * @type {number} - * @private - */ -goog.string.HASHCODE_MAX_ = 0x100000000; - - -/** - * String hash function similar to java.lang.String.hashCode(). - * The hash code for a string is computed as - * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], - * where s[i] is the ith character of the string and n is the length of - * the string. We mod the result to make it between 0 (inclusive) and 2^32 - * (exclusive). - * @param {string} str A string. - * @return {number} Hash value for {@code str}, between 0 (inclusive) and 2^32 - * (exclusive). The empty string returns 0. - */ -goog.string.hashCode = function(str) { - var result = 0; - for (var i = 0; i < str.length; ++i) { - result = 31 * result + str.charCodeAt(i); - // Normalize to 4 byte range, 0 ... 2^32. - result %= goog.string.HASHCODE_MAX_; - } - return result; -}; - - -/** - * The most recent unique ID. |0 is equivalent to Math.floor in this case. - * @type {number} - * @private - */ -goog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0; - - -/** - * Generates and returns a string which is unique in the current document. - * This is useful, for example, to create unique IDs for DOM elements. - * @return {string} A unique id. - */ -goog.string.createUniqueString = function() { - return 'goog_' + goog.string.uniqueStringCounter_++; -}; - - -/** - * Converts the supplied string to a number, which may be Infinity or NaN. - * This function strips whitespace: (toNumber(' 123') === 123) - * This function accepts scientific notation: (toNumber('1e1') === 10) - * - * This is better than Javascript's built-in conversions because, sadly: - * (Number(' ') === 0) and (parseFloat('123a') === 123) - * - * @param {string} str The string to convert. - * @return {number} The number the supplied string represents, or NaN. - */ -goog.string.toNumber = function(str) { - var num = Number(str); - if (num == 0 && goog.string.isEmptyOrWhitespace(str)) { - return NaN; - } - return num; -}; - - -/** - * Returns whether the given string is lower camel case (e.g. "isFooBar"). - * - * Note that this assumes the string is entirely letters. - * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms - * - * @param {string} str String to test. - * @return {boolean} Whether the string is lower camel case. - */ -goog.string.isLowerCamelCase = function(str) { - return /^[a-z]+([A-Z][a-z]*)*$/.test(str); -}; - - -/** - * Returns whether the given string is upper camel case (e.g. "FooBarBaz"). - * - * Note that this assumes the string is entirely letters. - * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms - * - * @param {string} str String to test. - * @return {boolean} Whether the string is upper camel case. - */ -goog.string.isUpperCamelCase = function(str) { - return /^([A-Z][a-z]*)+$/.test(str); -}; - - -/** - * Converts a string from selector-case to camelCase (e.g. from - * "multi-part-string" to "multiPartString"), useful for converting - * CSS selectors and HTML dataset keys to their equivalent JS properties. - * @param {string} str The string in selector-case form. - * @return {string} The string in camelCase form. - */ -goog.string.toCamelCase = function(str) { - return String(str).replace(/\-([a-z])/g, function(all, match) { - return match.toUpperCase(); - }); -}; - - -/** - * Converts a string from camelCase to selector-case (e.g. from - * "multiPartString" to "multi-part-string"), useful for converting JS - * style and dataset properties to equivalent CSS selectors and HTML keys. - * @param {string} str The string in camelCase form. - * @return {string} The string in selector-case form. - */ -goog.string.toSelectorCase = function(str) { - return String(str).replace(/([A-Z])/g, '-$1').toLowerCase(); -}; - - -/** - * Converts a string into TitleCase. First character of the string is always - * capitalized in addition to the first letter of every subsequent word. - * Words are delimited by one or more whitespaces by default. Custom delimiters - * can optionally be specified to replace the default, which doesn't preserve - * whitespace delimiters and instead must be explicitly included if needed. - * - * Default delimiter => " ": - * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree' - * goog.string.toTitleCase('one two three') => 'One Two Three' - * goog.string.toTitleCase(' one two ') => ' One Two ' - * goog.string.toTitleCase('one_two_three') => 'One_two_three' - * goog.string.toTitleCase('one-two-three') => 'One-two-three' - * - * Custom delimiter => "_-.": - * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree' - * goog.string.toTitleCase('one two three', '_-.') => 'One two three' - * goog.string.toTitleCase(' one two ', '_-.') => ' one two ' - * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three' - * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three' - * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three' - * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three' - * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three' - * - * @param {string} str String value in camelCase form. - * @param {string=} opt_delimiters Custom delimiter character set used to - * distinguish words in the string value. Each character represents a - * single delimiter. When provided, default whitespace delimiter is - * overridden and must be explicitly included if needed. - * @return {string} String value in TitleCase form. - */ -goog.string.toTitleCase = function(str, opt_delimiters) { - var delimiters = goog.isString(opt_delimiters) ? - goog.string.regExpEscape(opt_delimiters) : '\\s'; - - // For IE8, we need to prevent using an empty character set. Otherwise, - // incorrect matching will occur. - delimiters = delimiters ? '|[' + delimiters + ']+' : ''; - - var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g'); - return str.replace(regexp, function(all, p1, p2) { - return p1 + p2.toUpperCase(); - }); -}; - - -/** - * Capitalizes a string, i.e. converts the first letter to uppercase - * and all other letters to lowercase, e.g.: - * - * goog.string.capitalize('one') => 'One' - * goog.string.capitalize('ONE') => 'One' - * goog.string.capitalize('one two') => 'One two' - * - * Note that this function does not trim initial whitespace. - * - * @param {string} str String value to capitalize. - * @return {string} String value with first letter in uppercase. - */ -goog.string.capitalize = function(str) { - return String(str.charAt(0)).toUpperCase() + - String(str.substr(1)).toLowerCase(); -}; - - -/** - * Parse a string in decimal or hexidecimal ('0xFFFF') form. - * - * To parse a particular radix, please use parseInt(string, radix) directly. See - * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt - * - * This is a wrapper for the built-in parseInt function that will only parse - * numbers as base 10 or base 16. Some JS implementations assume strings - * starting with "0" are intended to be octal. ES3 allowed but discouraged - * this behavior. ES5 forbids it. This function emulates the ES5 behavior. - * - * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj - * - * @param {string|number|null|undefined} value The value to be parsed. - * @return {number} The number, parsed. If the string failed to parse, this - * will be NaN. - */ -goog.string.parseInt = function(value) { - // Force finite numbers to strings. - if (isFinite(value)) { - value = String(value); - } - - if (goog.isString(value)) { - // If the string starts with '0x' or '-0x', parse as hex. - return /^\s*-?0x/i.test(value) ? - parseInt(value, 16) : parseInt(value, 10); - } - - return NaN; -}; - - -/** - * Splits a string on a separator a limited number of times. - * - * This implementation is more similar to Python or Java, where the limit - * parameter specifies the maximum number of splits rather than truncating - * the number of results. - * - * See http://docs.python.org/2/library/stdtypes.html#str.split - * See JavaDoc: http://goo.gl/F2AsY - * See Mozilla reference: http://goo.gl/dZdZs - * - * @param {string} str String to split. - * @param {string} separator The separator. - * @param {number} limit The limit to the number of splits. The resulting array - * will have a maximum length of limit+1. Negative numbers are the same - * as zero. - * @return {!Array<string>} The string, split. - */ - -goog.string.splitLimit = function(str, separator, limit) { - var parts = str.split(separator); - var returnVal = []; - - // Only continue doing this while we haven't hit the limit and we have - // parts left. - while (limit > 0 && parts.length) { - returnVal.push(parts.shift()); - limit--; - } - - // If there are remaining parts, append them to the end. - if (parts.length) { - returnVal.push(parts.join(separator)); - } - - return returnVal; -}; - - -/** - * Computes the Levenshtein edit distance between two strings. - * @param {string} a - * @param {string} b - * @return {number} The edit distance between the two strings. - */ -goog.string.editDistance = function(a, b) { - var v0 = []; - var v1 = []; - - if (a == b) { - return 0; - } - - if (!a.length || !b.length) { - return Math.max(a.length, b.length); - } - - for (var i = 0; i < b.length + 1; i++) { - v0[i] = i; - } - - for (var i = 0; i < a.length; i++) { - v1[0] = i + 1; - - for (var j = 0; j < b.length; j++) { - var cost = a[i] != b[j]; - // Cost for the substring is the minimum of adding one character, removing - // one character, or a swap. - v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); - } - - for (var j = 0; j < v0.length; j++) { - v0[j] = v1[j]; - } - } - - return v1[b.length]; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/typedstring.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/typedstring.js deleted file mode 100644 index 075115f..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/string/typedstring.js +++ /dev/null @@ -1,48 +0,0 @@ -// 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. - -goog.provide('goog.string.TypedString'); - - - -/** - * Wrapper for strings that conform to a data type or language. - * - * Implementations of this interface are wrappers for strings, and typically - * associate a type contract with the wrapped string. Concrete implementations - * of this interface may choose to implement additional run-time type checking, - * see for example {@code goog.html.SafeHtml}. If available, client code that - * needs to ensure type membership of an object should use the type's function - * to assert type membership, such as {@code goog.html.SafeHtml.unwrap}. - * @interface - */ -goog.string.TypedString = function() {}; - - -/** - * Interface marker of the TypedString interface. - * - * This property can be used to determine at runtime whether or not an object - * implements this interface. All implementations of this interface set this - * property to {@code true}. - * @type {boolean} - */ -goog.string.TypedString.prototype.implementsGoogStringTypedString; - - -/** - * Retrieves this wrapped string's value. - * @return {!string} The wrapped string's value. - */ -goog.string.TypedString.prototype.getTypedStringValue; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/collection.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/collection.js deleted file mode 100644 index 86d008d..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/collection.js +++ /dev/null @@ -1,56 +0,0 @@ -// 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 the collection interface. - * - * @author nnaze@google.com (Nathan Naze) - */ - -goog.provide('goog.structs.Collection'); - - - -/** - * An interface for a collection of values. - * @interface - * @template T - */ -goog.structs.Collection = function() {}; - - -/** - * @param {T} value Value to add to the collection. - */ -goog.structs.Collection.prototype.add; - - -/** - * @param {T} value Value to remove from the collection. - */ -goog.structs.Collection.prototype.remove; - - -/** - * @param {T} value Value to find in the collection. - * @return {boolean} Whether the collection contains the specified value. - */ -goog.structs.Collection.prototype.contains; - - -/** - * @return {number} The number of values stored in the collection. - */ -goog.structs.Collection.prototype.getCount; - diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/map.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/map.js deleted file mode 100644 index 330bb7d..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/map.js +++ /dev/null @@ -1,460 +0,0 @@ -// 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 Datastructure: Hash Map. - * - * @author arv@google.com (Erik Arvidsson) - * - * This file contains an implementation of a Map structure. It implements a lot - * of the methods used in goog.structs so those functions work on hashes. This - * is best suited for complex key types. For simple keys such as numbers and - * strings, and where special names like __proto__ are not a concern, consider - * using the lighter-weight utilities in goog.object. - */ - - -goog.provide('goog.structs.Map'); - -goog.require('goog.iter.Iterator'); -goog.require('goog.iter.StopIteration'); -goog.require('goog.object'); - - - -/** - * Class for Hash Map datastructure. - * @param {*=} opt_map Map or Object to initialize the map with. - * @param {...*} var_args If 2 or more arguments are present then they - * will be used as key-value pairs. - * @constructor - * @template K, V - */ -goog.structs.Map = function(opt_map, var_args) { - - /** - * Underlying JS object used to implement the map. - * @private {!Object} - */ - this.map_ = {}; - - /** - * An array of keys. This is necessary for two reasons: - * 1. Iterating the keys using for (var key in this.map_) allocates an - * object for every key in IE which is really bad for IE6 GC perf. - * 2. Without a side data structure, we would need to escape all the keys - * as that would be the only way we could tell during iteration if the - * key was an internal key or a property of the object. - * - * This array can contain deleted keys so it's necessary to check the map - * as well to see if the key is still in the map (this doesn't require a - * memory allocation in IE). - * @private {!Array<string>} - */ - this.keys_ = []; - - /** - * The number of key value pairs in the map. - * @private {number} - */ - this.count_ = 0; - - /** - * Version used to detect changes while iterating. - * @private {number} - */ - this.version_ = 0; - - var argLength = arguments.length; - - if (argLength > 1) { - if (argLength % 2) { - throw Error('Uneven number of arguments'); - } - for (var i = 0; i < argLength; i += 2) { - this.set(arguments[i], arguments[i + 1]); - } - } else if (opt_map) { - this.addAll(/** @type {Object} */ (opt_map)); - } -}; - - -/** - * @return {number} The number of key-value pairs in the map. - */ -goog.structs.Map.prototype.getCount = function() { - return this.count_; -}; - - -/** - * Returns the values of the map. - * @return {!Array<V>} The values in the map. - */ -goog.structs.Map.prototype.getValues = function() { - this.cleanupKeysArray_(); - - var rv = []; - for (var i = 0; i < this.keys_.length; i++) { - var key = this.keys_[i]; - rv.push(this.map_[key]); - } - return rv; -}; - - -/** - * Returns the keys of the map. - * @return {!Array<string>} Array of string values. - */ -goog.structs.Map.prototype.getKeys = function() { - this.cleanupKeysArray_(); - return /** @type {!Array<string>} */ (this.keys_.concat()); -}; - - -/** - * Whether the map contains the given key. - * @param {*} key The key to check for. - * @return {boolean} Whether the map contains the key. - */ -goog.structs.Map.prototype.containsKey = function(key) { - return goog.structs.Map.hasKey_(this.map_, key); -}; - - -/** - * Whether the map contains the given value. This is O(n). - * @param {V} val The value to check for. - * @return {boolean} Whether the map contains the value. - */ -goog.structs.Map.prototype.containsValue = function(val) { - for (var i = 0; i < this.keys_.length; i++) { - var key = this.keys_[i]; - if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) { - return true; - } - } - return false; -}; - - -/** - * Whether this map is equal to the argument map. - * @param {goog.structs.Map} otherMap The map against which to test equality. - * @param {function(V, V): boolean=} opt_equalityFn Optional equality function - * to test equality of values. If not specified, this will test whether - * the values contained in each map are identical objects. - * @return {boolean} Whether the maps are equal. - */ -goog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) { - if (this === otherMap) { - return true; - } - - if (this.count_ != otherMap.getCount()) { - return false; - } - - var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals; - - this.cleanupKeysArray_(); - for (var key, i = 0; key = this.keys_[i]; i++) { - if (!equalityFn(this.get(key), otherMap.get(key))) { - return false; - } - } - - return true; -}; - - -/** - * Default equality test for values. - * @param {*} a The first value. - * @param {*} b The second value. - * @return {boolean} Whether a and b reference the same object. - */ -goog.structs.Map.defaultEquals = function(a, b) { - return a === b; -}; - - -/** - * @return {boolean} Whether the map is empty. - */ -goog.structs.Map.prototype.isEmpty = function() { - return this.count_ == 0; -}; - - -/** - * Removes all key-value pairs from the map. - */ -goog.structs.Map.prototype.clear = function() { - this.map_ = {}; - this.keys_.length = 0; - this.count_ = 0; - this.version_ = 0; -}; - - -/** - * Removes a key-value pair based on the key. This is O(logN) amortized due to - * updating the keys array whenever the count becomes half the size of the keys - * in the keys array. - * @param {*} key The key to remove. - * @return {boolean} Whether object was removed. - */ -goog.structs.Map.prototype.remove = function(key) { - if (goog.structs.Map.hasKey_(this.map_, key)) { - delete this.map_[key]; - this.count_--; - this.version_++; - - // clean up the keys array if the threshhold is hit - if (this.keys_.length > 2 * this.count_) { - this.cleanupKeysArray_(); - } - - return true; - } - return false; -}; - - -/** - * Cleans up the temp keys array by removing entries that are no longer in the - * map. - * @private - */ -goog.structs.Map.prototype.cleanupKeysArray_ = function() { - if (this.count_ != this.keys_.length) { - // First remove keys that are no longer in the map. - var srcIndex = 0; - var destIndex = 0; - while (srcIndex < this.keys_.length) { - var key = this.keys_[srcIndex]; - if (goog.structs.Map.hasKey_(this.map_, key)) { - this.keys_[destIndex++] = key; - } - srcIndex++; - } - this.keys_.length = destIndex; - } - - if (this.count_ != this.keys_.length) { - // If the count still isn't correct, that means we have duplicates. This can - // happen when the same key is added and removed multiple times. Now we have - // to allocate one extra Object to remove the duplicates. This could have - // been done in the first pass, but in the common case, we can avoid - // allocating an extra object by only doing this when necessary. - var seen = {}; - var srcIndex = 0; - var destIndex = 0; - while (srcIndex < this.keys_.length) { - var key = this.keys_[srcIndex]; - if (!(goog.structs.Map.hasKey_(seen, key))) { - this.keys_[destIndex++] = key; - seen[key] = 1; - } - srcIndex++; - } - this.keys_.length = destIndex; - } -}; - - -/** - * Returns the value for the given key. If the key is not found and the default - * value is not given this will return {@code undefined}. - * @param {*} key The key to get the value for. - * @param {DEFAULT=} opt_val The value to return if no item is found for the - * given key, defaults to undefined. - * @return {V|DEFAULT} The value for the given key. - * @template DEFAULT - */ -goog.structs.Map.prototype.get = function(key, opt_val) { - if (goog.structs.Map.hasKey_(this.map_, key)) { - return this.map_[key]; - } - return opt_val; -}; - - -/** - * Adds a key-value pair to the map. - * @param {*} key The key. - * @param {V} value The value to add. - * @return {*} Some subclasses return a value. - */ -goog.structs.Map.prototype.set = function(key, value) { - if (!(goog.structs.Map.hasKey_(this.map_, key))) { - this.count_++; - this.keys_.push(key); - // Only change the version if we add a new key. - this.version_++; - } - this.map_[key] = value; -}; - - -/** - * Adds multiple key-value pairs from another goog.structs.Map or Object. - * @param {Object} map Object containing the data to add. - */ -goog.structs.Map.prototype.addAll = function(map) { - var keys, values; - if (map instanceof goog.structs.Map) { - keys = map.getKeys(); - values = map.getValues(); - } else { - keys = goog.object.getKeys(map); - values = goog.object.getValues(map); - } - // we could use goog.array.forEach here but I don't want to introduce that - // dependency just for this. - for (var i = 0; i < keys.length; i++) { - this.set(keys[i], values[i]); - } -}; - - -/** - * Calls the given function on each entry in the map. - * @param {function(this:T, V, K, goog.structs.Map<K,V>)} f - * @param {T=} opt_obj The value of "this" inside f. - * @template T - */ -goog.structs.Map.prototype.forEach = function(f, opt_obj) { - var keys = this.getKeys(); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = this.get(key); - f.call(opt_obj, value, key, this); - } -}; - - -/** - * Clones a map and returns a new map. - * @return {!goog.structs.Map} A new map with the same key-value pairs. - */ -goog.structs.Map.prototype.clone = function() { - return new goog.structs.Map(this); -}; - - -/** - * Returns a new map in which all the keys and values are interchanged - * (keys become values and values become keys). If multiple keys map to the - * same value, the chosen transposed value is implementation-dependent. - * - * It acts very similarly to {goog.object.transpose(Object)}. - * - * @return {!goog.structs.Map} The transposed map. - */ -goog.structs.Map.prototype.transpose = function() { - var transposed = new goog.structs.Map(); - for (var i = 0; i < this.keys_.length; i++) { - var key = this.keys_[i]; - var value = this.map_[key]; - transposed.set(value, key); - } - - return transposed; -}; - - -/** - * @return {!Object} Object representation of the map. - */ -goog.structs.Map.prototype.toObject = function() { - this.cleanupKeysArray_(); - var obj = {}; - for (var i = 0; i < this.keys_.length; i++) { - var key = this.keys_[i]; - obj[key] = this.map_[key]; - } - return obj; -}; - - -/** - * Returns an iterator that iterates over the keys in the map. Removal of keys - * while iterating might have undesired side effects. - * @return {!goog.iter.Iterator} An iterator over the keys in the map. - */ -goog.structs.Map.prototype.getKeyIterator = function() { - return this.__iterator__(true); -}; - - -/** - * Returns an iterator that iterates over the values in the map. Removal of - * keys while iterating might have undesired side effects. - * @return {!goog.iter.Iterator} An iterator over the values in the map. - */ -goog.structs.Map.prototype.getValueIterator = function() { - return this.__iterator__(false); -}; - - -/** - * Returns an iterator that iterates over the values or the keys in the map. - * This throws an exception if the map was mutated since the iterator was - * created. - * @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} An iterator over the values or keys in the map. - */ -goog.structs.Map.prototype.__iterator__ = function(opt_keys) { - // Clean up keys to minimize the risk of iterating over dead keys. - this.cleanupKeysArray_(); - - var i = 0; - var keys = this.keys_; - var map = this.map_; - var version = this.version_; - var selfObj = this; - - var newIter = new goog.iter.Iterator; - newIter.next = function() { - while (true) { - if (version != selfObj.version_) { - throw Error('The map has changed since the iterator was created'); - } - if (i >= keys.length) { - throw goog.iter.StopIteration; - } - var key = keys[i++]; - return opt_keys ? key : map[key]; - } - }; - return newIter; -}; - - -/** - * Safe way to test for hasOwnProperty. It even allows testing for - * 'hasOwnProperty'. - * @param {Object} obj The object to test for presence of the given key. - * @param {*} key The key to check for. - * @return {boolean} Whether the object has the key. - * @private - */ -goog.structs.Map.hasKey_ = function(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/set.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/set.js deleted file mode 100644 index 334ecae..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/set.js +++ /dev/null @@ -1,279 +0,0 @@ -// 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 Datastructure: Set. - * - * @author arv@google.com (Erik Arvidsson) - * - * This class implements a set data structure. Adding and removing is O(1). It - * supports both object and primitive values. Be careful because you can add - * both 1 and new Number(1), because these are not the same. You can even add - * multiple new Number(1) because these are not equal. - */ - - -goog.provide('goog.structs.Set'); - -goog.require('goog.structs'); -goog.require('goog.structs.Collection'); -goog.require('goog.structs.Map'); - - - -/** - * A set that can contain both primitives and objects. Adding and removing - * elements is O(1). Primitives are treated as identical if they have the same - * type and convert to the same string. Objects are treated as identical only - * if they are references to the same object. WARNING: A goog.structs.Set can - * contain both 1 and (new Number(1)), because they are not the same. WARNING: - * Adding (new Number(1)) twice will yield two distinct elements, because they - * are two different objects. WARNING: Any object that is added to a - * goog.structs.Set will be modified! Because goog.getUid() is used to - * identify objects, every object in the set will be mutated. - * @param {Array<T>|Object<?,T>=} opt_values Initial values to start with. - * @constructor - * @implements {goog.structs.Collection<T>} - * @final - * @template T - */ -goog.structs.Set = function(opt_values) { - this.map_ = new goog.structs.Map; - if (opt_values) { - this.addAll(opt_values); - } -}; - - -/** - * Obtains a unique key for an element of the set. Primitives will yield the - * same key if they have the same type and convert to the same string. Object - * references will yield the same key only if they refer to the same object. - * @param {*} val Object or primitive value to get a key for. - * @return {string} A unique key for this value/object. - * @private - */ -goog.structs.Set.getKey_ = function(val) { - var type = typeof val; - if (type == 'object' && val || type == 'function') { - return 'o' + goog.getUid(/** @type {Object} */ (val)); - } else { - return type.substr(0, 1) + val; - } -}; - - -/** - * @return {number} The number of elements in the set. - * @override - */ -goog.structs.Set.prototype.getCount = function() { - return this.map_.getCount(); -}; - - -/** - * Add a primitive or an object to the set. - * @param {T} element The primitive or object to add. - * @override - */ -goog.structs.Set.prototype.add = function(element) { - this.map_.set(goog.structs.Set.getKey_(element), element); -}; - - -/** - * Adds all the values in the given collection to this set. - * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection - * containing the elements to add. - */ -goog.structs.Set.prototype.addAll = function(col) { - var values = goog.structs.getValues(col); - var l = values.length; - for (var i = 0; i < l; i++) { - this.add(values[i]); - } -}; - - -/** - * Removes all values in the given collection from this set. - * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection - * containing the elements to remove. - */ -goog.structs.Set.prototype.removeAll = function(col) { - var values = goog.structs.getValues(col); - var l = values.length; - for (var i = 0; i < l; i++) { - this.remove(values[i]); - } -}; - - -/** - * Removes the given element from this set. - * @param {T} element The primitive or object to remove. - * @return {boolean} Whether the element was found and removed. - * @override - */ -goog.structs.Set.prototype.remove = function(element) { - return this.map_.remove(goog.structs.Set.getKey_(element)); -}; - - -/** - * Removes all elements from this set. - */ -goog.structs.Set.prototype.clear = function() { - this.map_.clear(); -}; - - -/** - * Tests whether this set is empty. - * @return {boolean} True if there are no elements in this set. - */ -goog.structs.Set.prototype.isEmpty = function() { - return this.map_.isEmpty(); -}; - - -/** - * Tests whether this set contains the given element. - * @param {T} element The primitive or object to test for. - * @return {boolean} True if this set contains the given element. - * @override - */ -goog.structs.Set.prototype.contains = function(element) { - return this.map_.containsKey(goog.structs.Set.getKey_(element)); -}; - - -/** - * Tests whether this set contains all the values in a given collection. - * Repeated elements in the collection are ignored, e.g. (new - * goog.structs.Set([1, 2])).containsAll([1, 1]) is True. - * @param {goog.structs.Collection<T>|Object} col A collection-like object. - * @return {boolean} True if the set contains all elements. - */ -goog.structs.Set.prototype.containsAll = function(col) { - return goog.structs.every(col, this.contains, this); -}; - - -/** - * Finds all values that are present in both this set and the given collection. - * @param {Array<S>|Object<?,S>} col A collection. - * @return {!goog.structs.Set<T|S>} A new set containing all the values - * (primitives or objects) present in both this set and the given - * collection. - * @template S - */ -goog.structs.Set.prototype.intersection = function(col) { - var result = new goog.structs.Set(); - - var values = goog.structs.getValues(col); - for (var i = 0; i < values.length; i++) { - var value = values[i]; - if (this.contains(value)) { - result.add(value); - } - } - - return result; -}; - - -/** - * Finds all values that are present in this set and not in the given - * collection. - * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection. - * @return {!goog.structs.Set} A new set containing all the values - * (primitives or objects) present in this set but not in the given - * collection. - */ -goog.structs.Set.prototype.difference = function(col) { - var result = this.clone(); - result.removeAll(col); - return result; -}; - - -/** - * Returns an array containing all the elements in this set. - * @return {!Array<T>} An array containing all the elements in this set. - */ -goog.structs.Set.prototype.getValues = function() { - return this.map_.getValues(); -}; - - -/** - * Creates a shallow clone of this set. - * @return {!goog.structs.Set<T>} A new set containing all the same elements as - * this set. - */ -goog.structs.Set.prototype.clone = function() { - return new goog.structs.Set(this); -}; - - -/** - * Tests whether the given collection consists of the same elements as this set, - * regardless of order, without repetition. Primitives are treated as equal if - * they have the same type and convert to the same string; objects are treated - * as equal if they are references to the same object. This operation is O(n). - * @param {goog.structs.Collection<T>|Object} col A collection. - * @return {boolean} True if the given collection consists of the same elements - * as this set, regardless of order, without repetition. - */ -goog.structs.Set.prototype.equals = function(col) { - return this.getCount() == goog.structs.getCount(col) && this.isSubsetOf(col); -}; - - -/** - * Tests whether the given collection contains all the elements in this set. - * Primitives are treated as equal if they have the same type and convert to the - * same string; objects are treated as equal if they are references to the same - * object. This operation is O(n). - * @param {goog.structs.Collection<T>|Object} col A collection. - * @return {boolean} True if this set is a subset of the given collection. - */ -goog.structs.Set.prototype.isSubsetOf = function(col) { - var colCount = goog.structs.getCount(col); - if (this.getCount() > colCount) { - return false; - } - // TODO(user) Find the minimal collection size where the conversion makes - // the contains() method faster. - if (!(col instanceof goog.structs.Set) && colCount > 5) { - // Convert to a goog.structs.Set so that goog.structs.contains runs in - // O(1) time instead of O(n) time. - col = new goog.structs.Set(col); - } - return goog.structs.every(this, function(value) { - return goog.structs.contains(col, value); - }); -}; - - -/** - * Returns an iterator that iterates over the elements in this set. - * @param {boolean=} opt_keys This argument is ignored. - * @return {!goog.iter.Iterator} An iterator over the elements in this set. - */ -goog.structs.Set.prototype.__iterator__ = function(opt_keys) { - return this.map_.__iterator__(false); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/simplepool.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/simplepool.js deleted file mode 100644 index ff400fc..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/simplepool.js +++ /dev/null @@ -1,200 +0,0 @@ -// 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 Datastructure: Pool. - * - * - * A generic class for handling pools of objects that is more efficient than - * goog.structs.Pool because it doesn't maintain a list of objects that are in - * use. See constructor comment. - */ - - -goog.provide('goog.structs.SimplePool'); - -goog.require('goog.Disposable'); - - - -/** - * A generic pool class. Simpler and more efficient than goog.structs.Pool - * because it doesn't maintain a list of objects that are in use. This class - * has constant overhead and doesn't create any additional objects as part of - * the pool management after construction time. - * - * IMPORTANT: If the objects being pooled are arrays or maps that can have - * unlimited number of properties, they need to be cleaned before being - * returned to the pool. - * - * Also note that {@see goog.object.clean} actually allocates an array to clean - * the object passed to it, so simply using this function would defy the - * purpose of using the pool. - * - * @param {number} initialCount Initial number of objects to populate the free - * pool at construction time. - * @param {number} maxCount Maximum number of objects to keep in the free pool. - * @constructor - * @extends {goog.Disposable} - * @template T - */ -goog.structs.SimplePool = function(initialCount, maxCount) { - goog.Disposable.call(this); - - /** - * Function for overriding createObject. The avoids a common case requiring - * subclassing this class. - * @private {Function} - */ - this.createObjectFn_ = null; - - /** - * Function for overriding disposeObject. The avoids a common case requiring - * subclassing this class. - * @private {Function} - */ - this.disposeObjectFn_ = null; - - /** - * Maximum number of objects allowed - * @private {number} - */ - this.maxCount_ = maxCount; - - /** - * Queue used to store objects that are currently in the pool and available - * to be used. - * @private {Array<T>} - */ - this.freeQueue_ = []; - - this.createInitial_(initialCount); -}; -goog.inherits(goog.structs.SimplePool, goog.Disposable); - - -/** - * Sets the {@code createObject} function which is used for creating a new - * object in the pool. - * @param {Function} createObjectFn Create object function which returns the - * newly created object. - */ -goog.structs.SimplePool.prototype.setCreateObjectFn = function(createObjectFn) { - this.createObjectFn_ = createObjectFn; -}; - - -/** - * Sets the {@code disposeObject} function which is used for disposing of an - * object in the pool. - * @param {Function} disposeObjectFn Dispose object function which takes the - * object to dispose as a parameter. - */ -goog.structs.SimplePool.prototype.setDisposeObjectFn = function( - disposeObjectFn) { - this.disposeObjectFn_ = disposeObjectFn; -}; - - -/** - * Gets an unused object from the the pool, if there is one available, - * otherwise creates a new one. - * @return {T} An object from the pool or a new one if necessary. - */ -goog.structs.SimplePool.prototype.getObject = function() { - if (this.freeQueue_.length) { - return this.freeQueue_.pop(); - } - return this.createObject(); -}; - - -/** - * Returns an object to the pool so that it can be reused. If the pool is - * already full, the object is disposed instead. - * @param {T} obj The object to release. - */ -goog.structs.SimplePool.prototype.releaseObject = function(obj) { - if (this.freeQueue_.length < this.maxCount_) { - this.freeQueue_.push(obj); - } else { - this.disposeObject(obj); - } -}; - - -/** - * Populates the pool with initialCount objects. - * @param {number} initialCount The number of objects to add to the pool. - * @private - */ -goog.structs.SimplePool.prototype.createInitial_ = function(initialCount) { - if (initialCount > this.maxCount_) { - throw Error('[goog.structs.SimplePool] Initial cannot be greater than max'); - } - for (var i = 0; i < initialCount; i++) { - this.freeQueue_.push(this.createObject()); - } -}; - - -/** - * Should be overridden by sub-classes to return an instance of the object type - * that is expected in the pool. - * @return {T} The created object. - */ -goog.structs.SimplePool.prototype.createObject = function() { - if (this.createObjectFn_) { - return this.createObjectFn_(); - } else { - return {}; - } -}; - - -/** - * Should be overrideen to dispose of an object. Default implementation is to - * remove all of the object's members, which should render it useless. Calls the - * object's dispose method, if available. - * @param {T} obj The object to dispose. - */ -goog.structs.SimplePool.prototype.disposeObject = function(obj) { - if (this.disposeObjectFn_) { - this.disposeObjectFn_(obj); - } else if (goog.isObject(obj)) { - if (goog.isFunction(obj.dispose)) { - obj.dispose(); - } else { - for (var i in obj) { - delete obj[i]; - } - } - } -}; - - -/** - * Disposes of the pool and all objects currently held in the pool. - * @override - * @protected - */ -goog.structs.SimplePool.prototype.disposeInternal = function() { - goog.structs.SimplePool.superClass_.disposeInternal.call(this); - // Call disposeObject on each object held by the pool. - var freeQueue = this.freeQueue_; - while (freeQueue.length) { - this.disposeObject(freeQueue.pop()); - } - delete this.freeQueue_; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/structs.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/structs.js deleted file mode 100644 index 2744f6f..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/structs/structs.js +++ /dev/null @@ -1,354 +0,0 @@ -// 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 Generics method for collection-like classes and objects. - * - * @author arv@google.com (Erik Arvidsson) - * - * This file contains functions to work with collections. It supports using - * Map, Set, Array and Object and other classes that implement collection-like - * methods. - */ - - -goog.provide('goog.structs'); - -goog.require('goog.array'); -goog.require('goog.object'); - - -// We treat an object as a dictionary if it has getKeys or it is an object that -// isn't arrayLike. - - -/** - * Returns the number of values in the collection-like object. - * @param {Object} col The collection-like object. - * @return {number} The number of values in the collection-like object. - */ -goog.structs.getCount = function(col) { - if (typeof col.getCount == 'function') { - return col.getCount(); - } - if (goog.isArrayLike(col) || goog.isString(col)) { - return col.length; - } - return goog.object.getCount(col); -}; - - -/** - * Returns the values of the collection-like object. - * @param {Object} col The collection-like object. - * @return {!Array<?>} The values in the collection-like object. - */ -goog.structs.getValues = function(col) { - if (typeof col.getValues == 'function') { - return col.getValues(); - } - if (goog.isString(col)) { - return col.split(''); - } - if (goog.isArrayLike(col)) { - var rv = []; - var l = col.length; - for (var i = 0; i < l; i++) { - rv.push(col[i]); - } - return rv; - } - return goog.object.getValues(col); -}; - - -/** - * Returns the keys of the collection. Some collections have no notion of - * keys/indexes and this function will return undefined in those cases. - * @param {Object} col The collection-like object. - * @return {!Array|undefined} The keys in the collection. - */ -goog.structs.getKeys = function(col) { - if (typeof col.getKeys == 'function') { - return col.getKeys(); - } - // if we have getValues but no getKeys we know this is a key-less collection - if (typeof col.getValues == 'function') { - return undefined; - } - if (goog.isArrayLike(col) || goog.isString(col)) { - var rv = []; - var l = col.length; - for (var i = 0; i < l; i++) { - rv.push(i); - } - return rv; - } - - return goog.object.getKeys(col); -}; - - -/** - * Whether the collection contains the given value. This is O(n) and uses - * equals (==) to test the existence. - * @param {Object} col The collection-like object. - * @param {*} val The value to check for. - * @return {boolean} True if the map contains the value. - */ -goog.structs.contains = function(col, val) { - if (typeof col.contains == 'function') { - return col.contains(val); - } - if (typeof col.containsValue == 'function') { - return col.containsValue(val); - } - if (goog.isArrayLike(col) || goog.isString(col)) { - return goog.array.contains(/** @type {!Array<?>} */ (col), val); - } - return goog.object.containsValue(col, val); -}; - - -/** - * Whether the collection is empty. - * @param {Object} col The collection-like object. - * @return {boolean} True if empty. - */ -goog.structs.isEmpty = function(col) { - if (typeof col.isEmpty == 'function') { - return col.isEmpty(); - } - - // We do not use goog.string.isEmptyOrWhitespace because here we treat the string as - // collection and as such even whitespace matters - - if (goog.isArrayLike(col) || goog.isString(col)) { - return goog.array.isEmpty(/** @type {!Array<?>} */ (col)); - } - return goog.object.isEmpty(col); -}; - - -/** - * Removes all the elements from the collection. - * @param {Object} col The collection-like object. - */ -goog.structs.clear = function(col) { - // NOTE(arv): This should not contain strings because strings are immutable - if (typeof col.clear == 'function') { - col.clear(); - } else if (goog.isArrayLike(col)) { - goog.array.clear(/** @type {goog.array.ArrayLike} */ (col)); - } else { - goog.object.clear(col); - } -}; - - -/** - * Calls a function for each value in a collection. The function takes - * three arguments; the value, the key and the collection. - * - * NOTE: This will be deprecated soon! Please use a more specific method if - * possible, e.g. goog.array.forEach, goog.object.forEach, etc. - * - * @param {S} col The collection-like object. - * @param {function(this:T,?,?,S):?} f The function to call for every value. - * This function takes - * 3 arguments (the value, the key or undefined if the collection has no - * notion of keys, and the collection) and the return value is irrelevant. - * @param {T=} opt_obj The object to be used as the value of 'this' - * within {@code f}. - * @template T,S - */ -goog.structs.forEach = function(col, f, opt_obj) { - if (typeof col.forEach == 'function') { - col.forEach(f, opt_obj); - } else if (goog.isArrayLike(col) || goog.isString(col)) { - goog.array.forEach(/** @type {!Array<?>} */ (col), f, opt_obj); - } else { - var keys = goog.structs.getKeys(col); - var values = goog.structs.getValues(col); - var l = values.length; - for (var i = 0; i < l; i++) { - f.call(opt_obj, values[i], keys && keys[i], col); - } - } -}; - - -/** - * Calls a function for every value in the collection. When a call returns true, - * adds the value to a new collection (Array is returned by default). - * - * @param {S} col The collection-like object. - * @param {function(this:T,?,?,S):boolean} f The function to call for every - * value. This function takes - * 3 arguments (the value, the key or undefined if the collection has no - * notion of keys, and the collection) and should return a Boolean. If the - * return value is true the value is added to the result collection. If it - * is false the value is not included. - * @param {T=} opt_obj The object to be used as the value of 'this' - * within {@code f}. - * @return {!Object|!Array<?>} A new collection where the passed values are - * present. If col is a key-less collection an array is returned. If col - * has keys and values a plain old JS object is returned. - * @template T,S - */ -goog.structs.filter = function(col, f, opt_obj) { - if (typeof col.filter == 'function') { - return col.filter(f, opt_obj); - } - if (goog.isArrayLike(col) || goog.isString(col)) { - return goog.array.filter(/** @type {!Array<?>} */ (col), f, opt_obj); - } - - var rv; - var keys = goog.structs.getKeys(col); - var values = goog.structs.getValues(col); - var l = values.length; - if (keys) { - rv = {}; - for (var i = 0; i < l; i++) { - if (f.call(opt_obj, values[i], keys[i], col)) { - rv[keys[i]] = values[i]; - } - } - } else { - // We should not use goog.array.filter here since we want to make sure that - // the index is undefined as well as make sure that col is passed to the - // function. - rv = []; - for (var i = 0; i < l; i++) { - if (f.call(opt_obj, values[i], undefined, col)) { - rv.push(values[i]); - } - } - } - return rv; -}; - - -/** - * Calls a function for every value in the collection and adds the result into a - * new collection (defaults to creating a new Array). - * - * @param {S} col The collection-like object. - * @param {function(this:T,?,?,S):V} f The function to call for every value. - * This function takes 3 arguments (the value, the key or undefined if the - * collection has no notion of keys, and the collection) and should return - * something. The result will be used as the value in the new collection. - * @param {T=} opt_obj The object to be used as the value of 'this' - * within {@code f}. - * @return {!Object<V>|!Array<V>} A new collection with the new values. If - * col is a key-less collection an array is returned. If col has keys and - * values a plain old JS object is returned. - * @template T,S,V - */ -goog.structs.map = function(col, f, opt_obj) { - if (typeof col.map == 'function') { - return col.map(f, opt_obj); - } - if (goog.isArrayLike(col) || goog.isString(col)) { - return goog.array.map(/** @type {!Array<?>} */ (col), f, opt_obj); - } - - var rv; - var keys = goog.structs.getKeys(col); - var values = goog.structs.getValues(col); - var l = values.length; - if (keys) { - rv = {}; - for (var i = 0; i < l; i++) { - rv[keys[i]] = f.call(opt_obj, values[i], keys[i], col); - } - } else { - // We should not use goog.array.map here since we want to make sure that - // the index is undefined as well as make sure that col is passed to the - // function. - rv = []; - for (var i = 0; i < l; i++) { - rv[i] = f.call(opt_obj, values[i], undefined, col); - } - } - return rv; -}; - - -/** - * Calls f for each value in a collection. If any call returns true this returns - * true (without checking the rest). If all returns false this returns false. - * - * @param {S} col The collection-like object. - * @param {function(this:T,?,?,S):boolean} f The function to call for every - * value. This function takes 3 arguments (the value, the key or undefined - * if the collection has no notion of keys, and the collection) and should - * return a boolean. - * @param {T=} opt_obj The object to be used as the value of 'this' - * within {@code f}. - * @return {boolean} True if any value passes the test. - * @template T,S - */ -goog.structs.some = function(col, f, opt_obj) { - if (typeof col.some == 'function') { - return col.some(f, opt_obj); - } - if (goog.isArrayLike(col) || goog.isString(col)) { - return goog.array.some(/** @type {!Array<?>} */ (col), f, opt_obj); - } - var keys = goog.structs.getKeys(col); - var values = goog.structs.getValues(col); - var l = values.length; - for (var i = 0; i < l; i++) { - if (f.call(opt_obj, values[i], keys && keys[i], col)) { - return true; - } - } - return false; -}; - - -/** - * Calls f for each value in a collection. If all calls return true this return - * true this returns true. If any returns false this returns false at this point - * and does not continue to check the remaining values. - * - * @param {S} col The collection-like object. - * @param {function(this:T,?,?,S):boolean} f The function to call for every - * value. This function takes 3 arguments (the value, the key or - * undefined if the collection has no notion of keys, and the collection) - * and should return a boolean. - * @param {T=} opt_obj The object to be used as the value of 'this' - * within {@code f}. - * @return {boolean} True if all key-value pairs pass the test. - * @template T,S - */ -goog.structs.every = function(col, f, opt_obj) { - if (typeof col.every == 'function') { - return col.every(f, opt_obj); - } - if (goog.isArrayLike(col) || goog.isString(col)) { - return goog.array.every(/** @type {!Array<?>} */ (col), f, opt_obj); - } - var keys = goog.structs.getKeys(col); - var values = goog.structs.getValues(col); - var l = values.length; - for (var i = 0; i < l; i++) { - if (!f.call(opt_obj, values[i], keys && keys[i], col)) { - return false; - } - } - return true; -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/style/style.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/style/style.js deleted file mode 100644 index 9ed0efa..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/style/style.js +++ /dev/null @@ -1,2034 +0,0 @@ -// 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 for element styles. - * - * @author arv@google.com (Erik Arvidsson) - * @author eae@google.com (Emil A Eklund) - * @see ../demos/inline_block_quirks.html - * @see ../demos/inline_block_standards.html - * @see ../demos/style_viewport.html - */ - -goog.provide('goog.style'); - - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.dom'); -goog.require('goog.dom.NodeType'); -goog.require('goog.dom.vendor'); -goog.require('goog.math.Box'); -goog.require('goog.math.Coordinate'); -goog.require('goog.math.Rect'); -goog.require('goog.math.Size'); -goog.require('goog.object'); -goog.require('goog.string'); -goog.require('goog.userAgent'); - -goog.require('goog.events.BrowserEvent'); -goog.require('goog.events.Event'); - - -/** - * Sets a style value on an element. - * - * This function is not indended to patch issues in the browser's style - * handling, but to allow easy programmatic access to setting dash-separated - * style properties. An example is setting a batch of properties from a data - * object without overwriting old styles. When possible, use native APIs: - * elem.style.propertyKey = 'value' or (if obliterating old styles is fine) - * elem.style.cssText = 'property1: value1; property2: value2'. - * - * @param {Element} element The element to change. - * @param {string|Object} style If a string, a style name. If an object, a hash - * of style names to style values. - * @param {string|number|boolean=} opt_value If style was a string, then this - * should be the value. - */ -goog.style.setStyle = function(element, style, opt_value) { - if (goog.isString(style)) { - goog.style.setStyle_(element, opt_value, style); - } else { - for (var key in style) { - goog.style.setStyle_(element, style[key], key); - } - } -}; - - -/** - * Sets a style value on an element, with parameters swapped to work with - * {@code goog.object.forEach()}. Prepends a vendor-specific prefix when - * necessary. - * @param {Element} element The element to change. - * @param {string|number|boolean|undefined} value Style value. - * @param {string} style Style name. - * @private - */ -goog.style.setStyle_ = function(element, value, style) { - var propertyName = goog.style.getVendorJsStyleName_(element, style); - - if (propertyName) { - element.style[propertyName] = value; - } -}; - - -/** - * Style name cache that stores previous property name lookups. - * - * This is used by setStyle to speed up property lookups, entries look like: - * { StyleName: ActualPropertyName } - * - * @private {!Object<string, string>} - */ -goog.style.styleNameCache_ = {}; - - -/** - * Returns the style property name in camel-case. If it does not exist and a - * vendor-specific version of the property does exist, then return the vendor- - * specific property name instead. - * @param {Element} element The element to change. - * @param {string} style Style name. - * @return {string} Vendor-specific style. - * @private - */ -goog.style.getVendorJsStyleName_ = function(element, style) { - var propertyName = goog.style.styleNameCache_[style]; - if (!propertyName) { - var camelStyle = goog.string.toCamelCase(style); - propertyName = camelStyle; - - if (element.style[camelStyle] === undefined) { - var prefixedStyle = goog.dom.vendor.getVendorJsPrefix() + - goog.string.toTitleCase(camelStyle); - - if (element.style[prefixedStyle] !== undefined) { - propertyName = prefixedStyle; - } - } - goog.style.styleNameCache_[style] = propertyName; - } - - return propertyName; -}; - - -/** - * Returns the style property name in CSS notation. If it does not exist and a - * vendor-specific version of the property does exist, then return the vendor- - * specific property name instead. - * @param {Element} element The element to change. - * @param {string} style Style name. - * @return {string} Vendor-specific style. - * @private - */ -goog.style.getVendorStyleName_ = function(element, style) { - var camelStyle = goog.string.toCamelCase(style); - - if (element.style[camelStyle] === undefined) { - var prefixedStyle = goog.dom.vendor.getVendorJsPrefix() + - goog.string.toTitleCase(camelStyle); - - if (element.style[prefixedStyle] !== undefined) { - return goog.dom.vendor.getVendorPrefix() + '-' + style; - } - } - - return style; -}; - - -/** - * Retrieves an explicitly-set style value of a node. This returns '' if there - * isn't a style attribute on the element or if this style property has not been - * explicitly set in script. - * - * @param {Element} element Element to get style of. - * @param {string} property Property to get, css-style (if you have a camel-case - * property, use element.style[style]). - * @return {string} Style value. - */ -goog.style.getStyle = function(element, property) { - // element.style is '' for well-known properties which are unset. - // For for browser specific styles as 'filter' is undefined - // so we need to return '' explicitly to make it consistent across - // browsers. - var styleValue = element.style[goog.string.toCamelCase(property)]; - - // Using typeof here because of a bug in Safari 5.1, where this value - // was undefined, but === undefined returned false. - if (typeof(styleValue) !== 'undefined') { - return styleValue; - } - - return element.style[goog.style.getVendorJsStyleName_(element, property)] || - ''; -}; - - -/** - * Retrieves a computed style value of a node. It returns empty string if the - * value cannot be computed (which will be the case in Internet Explorer) or - * "none" if the property requested is an SVG one and it has not been - * explicitly set (firefox and webkit). - * - * @param {Element} element Element to get style of. - * @param {string} property Property to get (camel-case). - * @return {string} Style value. - */ -goog.style.getComputedStyle = function(element, property) { - var doc = goog.dom.getOwnerDocument(element); - if (doc.defaultView && doc.defaultView.getComputedStyle) { - var styles = doc.defaultView.getComputedStyle(element, null); - if (styles) { - // element.style[..] is undefined for browser specific styles - // as 'filter'. - return styles[property] || styles.getPropertyValue(property) || ''; - } - } - - return ''; -}; - - -/** - * Gets the cascaded style value of a node, or null if the value cannot be - * computed (only Internet Explorer can do this). - * - * @param {Element} element Element to get style of. - * @param {string} style Property to get (camel-case). - * @return {string} Style value. - */ -goog.style.getCascadedStyle = function(element, style) { - // TODO(nicksantos): This should be documented to return null. #fixTypes - return element.currentStyle ? element.currentStyle[style] : null; -}; - - -/** - * Cross-browser pseudo get computed style. It returns the computed style where - * available. If not available it tries the cascaded style value (IE - * currentStyle) and in worst case the inline style value. It shouldn't be - * called directly, see http://wiki/Main/ComputedStyleVsCascadedStyle for - * discussion. - * - * @param {Element} element Element to get style of. - * @param {string} style Property to get (must be camelCase, not css-style.). - * @return {string} Style value. - * @private - */ -goog.style.getStyle_ = function(element, style) { - return goog.style.getComputedStyle(element, style) || - goog.style.getCascadedStyle(element, style) || - (element.style && element.style[style]); -}; - - -/** - * Retrieves the computed value of the box-sizing CSS attribute. - * Browser support: http://caniuse.com/css3-boxsizing. - * @param {!Element} element The element whose box-sizing to get. - * @return {?string} 'content-box', 'border-box' or 'padding-box'. null if - * box-sizing is not supported (IE7 and below). - */ -goog.style.getComputedBoxSizing = function(element) { - return goog.style.getStyle_(element, 'boxSizing') || - goog.style.getStyle_(element, 'MozBoxSizing') || - goog.style.getStyle_(element, 'WebkitBoxSizing') || null; -}; - - -/** - * Retrieves the computed value of the position CSS attribute. - * @param {Element} element The element to get the position of. - * @return {string} Position value. - */ -goog.style.getComputedPosition = function(element) { - return goog.style.getStyle_(element, 'position'); -}; - - -/** - * Retrieves the computed background color string for a given element. The - * string returned is suitable for assigning to another element's - * background-color, but is not guaranteed to be in any particular string - * format. Accessing the color in a numeric form may not be possible in all - * browsers or with all input. - * - * If the background color for the element is defined as a hexadecimal value, - * the resulting string can be parsed by goog.color.parse in all supported - * browsers. - * - * Whether named colors like "red" or "lightblue" get translated into a - * format which can be parsed is browser dependent. Calling this function on - * transparent elements will return "transparent" in most browsers or - * "rgba(0, 0, 0, 0)" in WebKit. - * @param {Element} element The element to get the background color of. - * @return {string} The computed string value of the background color. - */ -goog.style.getBackgroundColor = function(element) { - return goog.style.getStyle_(element, 'backgroundColor'); -}; - - -/** - * Retrieves the computed value of the overflow-x CSS attribute. - * @param {Element} element The element to get the overflow-x of. - * @return {string} The computed string value of the overflow-x attribute. - */ -goog.style.getComputedOverflowX = function(element) { - return goog.style.getStyle_(element, 'overflowX'); -}; - - -/** - * Retrieves the computed value of the overflow-y CSS attribute. - * @param {Element} element The element to get the overflow-y of. - * @return {string} The computed string value of the overflow-y attribute. - */ -goog.style.getComputedOverflowY = function(element) { - return goog.style.getStyle_(element, 'overflowY'); -}; - - -/** - * Retrieves the computed value of the z-index CSS attribute. - * @param {Element} element The element to get the z-index of. - * @return {string|number} The computed value of the z-index attribute. - */ -goog.style.getComputedZIndex = function(element) { - return goog.style.getStyle_(element, 'zIndex'); -}; - - -/** - * Retrieves the computed value of the text-align CSS attribute. - * @param {Element} element The element to get the text-align of. - * @return {string} The computed string value of the text-align attribute. - */ -goog.style.getComputedTextAlign = function(element) { - return goog.style.getStyle_(element, 'textAlign'); -}; - - -/** - * Retrieves the computed value of the cursor CSS attribute. - * @param {Element} element The element to get the cursor of. - * @return {string} The computed string value of the cursor attribute. - */ -goog.style.getComputedCursor = function(element) { - return goog.style.getStyle_(element, 'cursor'); -}; - - -/** - * Retrieves the computed value of the CSS transform attribute. - * @param {Element} element The element to get the transform of. - * @return {string} The computed string representation of the transform matrix. - */ -goog.style.getComputedTransform = function(element) { - var property = goog.style.getVendorStyleName_(element, 'transform'); - return goog.style.getStyle_(element, property) || - goog.style.getStyle_(element, 'transform'); -}; - - -/** - * Sets the top/left values of an element. If no unit is specified in the - * argument then it will add px. The second argument is required if the first - * argument is a string or number and is ignored if the first argument - * is a coordinate. - * @param {Element} el Element to move. - * @param {string|number|goog.math.Coordinate} arg1 Left position or coordinate. - * @param {string|number=} opt_arg2 Top position. - */ -goog.style.setPosition = function(el, arg1, opt_arg2) { - var x, y; - - if (arg1 instanceof goog.math.Coordinate) { - x = arg1.x; - y = arg1.y; - } else { - x = arg1; - y = opt_arg2; - } - - el.style.left = goog.style.getPixelStyleValue_( - /** @type {number|string} */ (x), false); - el.style.top = goog.style.getPixelStyleValue_( - /** @type {number|string} */ (y), false); -}; - - -/** - * Gets the offsetLeft and offsetTop properties of an element and returns them - * in a Coordinate object - * @param {Element} element Element. - * @return {!goog.math.Coordinate} The position. - */ -goog.style.getPosition = function(element) { - return new goog.math.Coordinate(element.offsetLeft, element.offsetTop); -}; - - -/** - * Returns the viewport element for a particular document - * @param {Node=} opt_node DOM node (Document is OK) to get the viewport element - * of. - * @return {Element} document.documentElement or document.body. - */ -goog.style.getClientViewportElement = function(opt_node) { - var doc; - if (opt_node) { - doc = goog.dom.getOwnerDocument(opt_node); - } else { - doc = goog.dom.getDocument(); - } - - // In old IE versions the document.body represented the viewport - if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9) && - !goog.dom.getDomHelper(doc).isCss1CompatMode()) { - return doc.body; - } - return doc.documentElement; -}; - - -/** - * Calculates the viewport coordinates relative to the page/document - * containing the node. The viewport may be the browser viewport for - * non-iframe document, or the iframe container for iframe'd document. - * @param {!Document} doc The document to use as the reference point. - * @return {!goog.math.Coordinate} The page offset of the viewport. - */ -goog.style.getViewportPageOffset = function(doc) { - var body = doc.body; - var documentElement = doc.documentElement; - var scrollLeft = body.scrollLeft || documentElement.scrollLeft; - var scrollTop = body.scrollTop || documentElement.scrollTop; - return new goog.math.Coordinate(scrollLeft, scrollTop); -}; - - -/** - * Gets the client rectangle of the DOM element. - * - * getBoundingClientRect is part of a new CSS object model draft (with a - * long-time presence in IE), replacing the error-prone parent offset - * computation and the now-deprecated Gecko getBoxObjectFor. - * - * This utility patches common browser bugs in getBoundingClientRect. It - * will fail if getBoundingClientRect is unsupported. - * - * If the element is not in the DOM, the result is undefined, and an error may - * be thrown depending on user agent. - * - * @param {!Element|null} el The element whose bounding rectangle is being queried. - * @return {Object} A native bounding rectangle with numerical left, top, - * right, and bottom. Reported by Firefox to be of object type ClientRect. - * @private - */ -goog.style.getBoundingClientRect_ = function(el) { - var rect; - try { - rect = el.getBoundingClientRect(); - } catch (e) { - // In IE < 9, calling getBoundingClientRect on an orphan element raises an - // "Unspecified Error". All other browsers return zeros. - return {'left': 0, 'top': 0, 'right': 0, 'bottom': 0}; - } - - // Patch the result in IE only, so that this function can be inlined if - // compiled for non-IE. - if (goog.userAgent.IE && el.ownerDocument.body) { - - // In IE, most of the time, 2 extra pixels are added to the top and left - // due to the implicit 2-pixel inset border. In IE6/7 quirks mode and - // IE6 standards mode, this border can be overridden by setting the - // document element's border to zero -- thus, we cannot rely on the - // offset always being 2 pixels. - - // In quirks mode, the offset can be determined by querying the body's - // clientLeft/clientTop, but in standards mode, it is found by querying - // the document element's clientLeft/clientTop. Since we already called - // getBoundingClientRect we have already forced a reflow, so it is not - // too expensive just to query them all. - - // See: http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx - var doc = el.ownerDocument; - rect.left -= doc.documentElement.clientLeft + doc.body.clientLeft; - rect.top -= doc.documentElement.clientTop + doc.body.clientTop; - } - return /** @type {Object} */ (rect); -}; - - -/** - * Returns the first parent that could affect the position of a given element. - * @param {Element} element The element to get the offset parent for. - * @return {Element} The first offset parent or null if one cannot be found. - */ -goog.style.getOffsetParent = function(element) { - // element.offsetParent does the right thing in IE7 and below. In other - // browsers it only includes elements with position absolute, relative or - // fixed, not elements with overflow set to auto or scroll. - if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(8)) { - return element.offsetParent; - } - - var doc = goog.dom.getOwnerDocument(element); - var positionStyle = goog.style.getStyle_(element, 'position'); - var skipStatic = positionStyle == 'fixed' || positionStyle == 'absolute'; - for (var parent = element.parentNode; parent && parent != doc; - parent = parent.parentNode) { - // Skip shadowDOM roots. - if (parent.nodeType == goog.dom.NodeType.DOCUMENT_FRAGMENT && - parent.host) { - parent = parent.host; - } - positionStyle = - goog.style.getStyle_(/** @type {!Element} */ (parent), 'position'); - skipStatic = skipStatic && positionStyle == 'static' && - parent != doc.documentElement && parent != doc.body; - if (!skipStatic && (parent.scrollWidth > parent.clientWidth || - parent.scrollHeight > parent.clientHeight || - positionStyle == 'fixed' || - positionStyle == 'absolute' || - positionStyle == 'relative')) { - return /** @type {!Element} */ (parent); - } - } - return null; -}; - - -/** - * Calculates and returns the visible rectangle for a given element. Returns a - * box describing the visible portion of the nearest scrollable offset ancestor. - * Coordinates are given relative to the document. - * - * @param {Element} element Element to get the visible rect for. - * @return {goog.math.Box} Bounding elementBox describing the visible rect or - * null if scrollable ancestor isn't inside the visible viewport. - */ -goog.style.getVisibleRectForElement = function(element) { - var visibleRect = new goog.math.Box(0, Infinity, Infinity, 0); - var dom = goog.dom.getDomHelper(element); - var body = dom.getDocument().body; - var documentElement = dom.getDocument().documentElement; - var scrollEl = dom.getDocumentScrollElement(); - - // Determine the size of the visible rect by climbing the dom accounting for - // all scrollable containers. - for (var el = element; el = goog.style.getOffsetParent(el); ) { - // clientWidth is zero for inline block elements in IE. - // on WEBKIT, body element can have clientHeight = 0 and scrollHeight > 0 - if ((!goog.userAgent.IE || el.clientWidth != 0) && - (!goog.userAgent.WEBKIT || el.clientHeight != 0 || el != body) && - // body may have overflow set on it, yet we still get the entire - // viewport. In some browsers, el.offsetParent may be - // document.documentElement, so check for that too. - (el != body && el != documentElement && - goog.style.getStyle_(el, 'overflow') != 'visible')) { - var pos = goog.style.getPageOffset(el); - var client = goog.style.getClientLeftTop(el); - pos.x += client.x; - pos.y += client.y; - - visibleRect.top = Math.max(visibleRect.top, pos.y); - visibleRect.right = Math.min(visibleRect.right, - pos.x + el.clientWidth); - visibleRect.bottom = Math.min(visibleRect.bottom, - pos.y + el.clientHeight); - visibleRect.left = Math.max(visibleRect.left, pos.x); - } - } - - // Clip by window's viewport. - var scrollX = scrollEl.scrollLeft, scrollY = scrollEl.scrollTop; - visibleRect.left = Math.max(visibleRect.left, scrollX); - visibleRect.top = Math.max(visibleRect.top, scrollY); - var winSize = dom.getViewportSize(); - visibleRect.right = Math.min(visibleRect.right, scrollX + winSize.width); - visibleRect.bottom = Math.min(visibleRect.bottom, scrollY + winSize.height); - return visibleRect.top >= 0 && visibleRect.left >= 0 && - visibleRect.bottom > visibleRect.top && - visibleRect.right > visibleRect.left ? - visibleRect : null; -}; - - -/** - * Calculate the scroll position of {@code container} with the minimum amount so - * that the content and the borders of the given {@code element} become visible. - * If the element is bigger than the container, its top left corner will be - * aligned as close to the container's top left corner as possible. - * - * @param {Element} element The element to make visible. - * @param {Element} container The container to scroll. - * @param {boolean=} opt_center Whether to center the element in the container. - * Defaults to false. - * @return {!goog.math.Coordinate} The new scroll position of the container, - * in form of goog.math.Coordinate(scrollLeft, scrollTop). - */ -goog.style.getContainerOffsetToScrollInto = - function(element, container, opt_center) { - // Absolute position of the element's border's top left corner. - var elementPos = goog.style.getPageOffset(element); - // Absolute position of the container's border's top left corner. - var containerPos = goog.style.getPageOffset(container); - var containerBorder = goog.style.getBorderBox(container); - // Relative pos. of the element's border box to the container's content box. - var relX = elementPos.x - containerPos.x - containerBorder.left; - var relY = elementPos.y - containerPos.y - containerBorder.top; - // How much the element can move in the container, i.e. the difference between - // the element's bottom-right-most and top-left-most position where it's - // fully visible. - var spaceX = container.clientWidth - element.offsetWidth; - var spaceY = container.clientHeight - element.offsetHeight; - - var scrollLeft = container.scrollLeft; - var scrollTop = container.scrollTop; - if (container == goog.dom.getDocument().body || - container == goog.dom.getDocument().documentElement) { - // If the container is the document scroll element (usually <body>), - // getPageOffset(element) is already relative to it and there is no need to - // consider the current scroll. - scrollLeft = containerPos.x + containerBorder.left; - scrollTop = containerPos.y + containerBorder.top; - - if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) { - // In older versions of IE getPageOffset(element) does not include the - // continaer border so it has to be added to accomodate. - scrollLeft += containerBorder.left; - scrollTop += containerBorder.top; - } - } - if (opt_center) { - // All browsers round non-integer scroll positions down. - scrollLeft += relX - spaceX / 2; - scrollTop += relY - spaceY / 2; - } else { - // This formula was designed to give the correct scroll values in the - // following cases: - // - element is higher than container (spaceY < 0) => scroll down by relY - // - element is not higher that container (spaceY >= 0): - // - it is above container (relY < 0) => scroll up by abs(relY) - // - it is below container (relY > spaceY) => scroll down by relY - spaceY - // - it is in the container => don't scroll - scrollLeft += Math.min(relX, Math.max(relX - spaceX, 0)); - scrollTop += Math.min(relY, Math.max(relY - spaceY, 0)); - } - return new goog.math.Coordinate(scrollLeft, scrollTop); -}; - - -/** - * Changes the scroll position of {@code container} with the minimum amount so - * that the content and the borders of the given {@code element} become visible. - * If the element is bigger than the container, its top left corner will be - * aligned as close to the container's top left corner as possible. - * - * @param {Element} element The element to make visible. - * @param {Element} container The container to scroll. - * @param {boolean=} opt_center Whether to center the element in the container. - * Defaults to false. - */ -goog.style.scrollIntoContainerView = function(element, container, opt_center) { - var offset = - goog.style.getContainerOffsetToScrollInto(element, container, opt_center); - container.scrollLeft = offset.x; - container.scrollTop = offset.y; -}; - - -/** - * Returns clientLeft (width of the left border and, if the directionality is - * right to left, the vertical scrollbar) and clientTop as a coordinate object. - * - * @param {Element} el Element to get clientLeft for. - * @return {!goog.math.Coordinate} Client left and top. - */ -goog.style.getClientLeftTop = function(el) { - return new goog.math.Coordinate(el.clientLeft, el.clientTop); -}; - - -/** - * Returns a Coordinate object relative to the top-left of the HTML document. - * Implemented as a single function to save having to do two recursive loops in - * opera and safari just to get both coordinates. If you just want one value do - * use goog.style.getPageOffsetLeft() and goog.style.getPageOffsetTop(), but - * note if you call both those methods the tree will be analysed twice. - * - * @param {Element} el Element to get the page offset for. - * @return {!goog.math.Coordinate} The page offset. - */ -goog.style.getPageOffset = function(el) { - var doc = goog.dom.getOwnerDocument(el); - // TODO(gboyer): Update the jsdoc in a way that doesn't break the universe. - goog.asserts.assertObject(el, 'Parameter is required'); - - // NOTE(arv): If element is hidden (display none or disconnected or any the - // ancestors are hidden) we get (0,0) by default but we still do the - // accumulation of scroll position. - - // TODO(arv): Should we check if the node is disconnected and in that case - // return (0,0)? - - var pos = new goog.math.Coordinate(0, 0); - var viewportElement = goog.style.getClientViewportElement(doc); - if (el == viewportElement) { - // viewport is always at 0,0 as that defined the coordinate system for this - // function - this avoids special case checks in the code below - return pos; - } - - var box = goog.style.getBoundingClientRect_(el); - // Must add the scroll coordinates in to get the absolute page offset - // of element since getBoundingClientRect returns relative coordinates to - // the viewport. - var scrollCoord = goog.dom.getDomHelper(doc).getDocumentScroll(); - pos.x = box.left + scrollCoord.x; - pos.y = box.top + scrollCoord.y; - - return pos; -}; - - -/** - * Returns the left coordinate of an element relative to the HTML document - * @param {Element} el Elements. - * @return {number} The left coordinate. - */ -goog.style.getPageOffsetLeft = function(el) { - return goog.style.getPageOffset(el).x; -}; - - -/** - * Returns the top coordinate of an element relative to the HTML document - * @param {Element} el Elements. - * @return {number} The top coordinate. - */ -goog.style.getPageOffsetTop = function(el) { - return goog.style.getPageOffset(el).y; -}; - - -/** - * Returns a Coordinate object relative to the top-left of an HTML document - * in an ancestor frame of this element. Used for measuring the position of - * an element inside a frame relative to a containing frame. - * - * @param {Element} el Element to get the page offset for. - * @param {Window} relativeWin The window to measure relative to. If relativeWin - * is not in the ancestor frame chain of the element, we measure relative to - * the top-most window. - * @return {!goog.math.Coordinate} The page offset. - */ -goog.style.getFramedPageOffset = function(el, relativeWin) { - var position = new goog.math.Coordinate(0, 0); - - // Iterate up the ancestor frame chain, keeping track of the current window - // and the current element in that window. - var currentWin = goog.dom.getWindow(goog.dom.getOwnerDocument(el)); - var currentEl = el; - do { - // if we're at the top window, we want to get the page offset. - // if we're at an inner frame, we only want to get the window position - // so that we can determine the actual page offset in the context of - // the outer window. - var offset = currentWin == relativeWin ? - goog.style.getPageOffset(currentEl) : - goog.style.getClientPositionForElement_( - goog.asserts.assert(currentEl)); - - position.x += offset.x; - position.y += offset.y; - } while (currentWin && currentWin != relativeWin && - currentWin != currentWin.parent && - (currentEl = currentWin.frameElement) && - (currentWin = currentWin.parent)); - - return position; -}; - - -/** - * Translates the specified rect relative to origBase page, for newBase page. - * If origBase and newBase are the same, this function does nothing. - * - * @param {goog.math.Rect} rect The source rectangle relative to origBase page, - * and it will have the translated result. - * @param {goog.dom.DomHelper} origBase The DomHelper for the input rectangle. - * @param {goog.dom.DomHelper} newBase The DomHelper for the resultant - * coordinate. This must be a DOM for an ancestor frame of origBase - * or the same as origBase. - */ -goog.style.translateRectForAnotherFrame = function(rect, origBase, newBase) { - if (origBase.getDocument() != newBase.getDocument()) { - var body = origBase.getDocument().body; - var pos = goog.style.getFramedPageOffset(body, newBase.getWindow()); - - // Adjust Body's margin. - pos = goog.math.Coordinate.difference(pos, goog.style.getPageOffset(body)); - - if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9) && - !origBase.isCss1CompatMode()) { - pos = goog.math.Coordinate.difference(pos, origBase.getDocumentScroll()); - } - - rect.left += pos.x; - rect.top += pos.y; - } -}; - - -/** - * Returns the position of an element relative to another element in the - * document. A relative to B - * @param {Element|Event|goog.events.Event} a Element or mouse event whose - * position we're calculating. - * @param {Element|Event|goog.events.Event} b Element or mouse event position - * is relative to. - * @return {!goog.math.Coordinate} The relative position. - */ -goog.style.getRelativePosition = function(a, b) { - var ap = goog.style.getClientPosition(a); - var bp = goog.style.getClientPosition(b); - return new goog.math.Coordinate(ap.x - bp.x, ap.y - bp.y); -}; - - -/** - * Returns the position of the event or the element's border box relative to - * the client viewport. - * @param {!Element|null} el Element whose position to get. - * @return {!goog.math.Coordinate} The position. - * @private - */ -goog.style.getClientPositionForElement_ = function(el) { - var box = goog.style.getBoundingClientRect_(el); - return new goog.math.Coordinate(box.left, box.top); -}; - - -/** - * Returns the position of the event or the element's border box relative to - * the client viewport. - * @param {Element|Event|goog.events.Event} el Element or a mouse / touch event. - * @return {!goog.math.Coordinate} The position. - */ -goog.style.getClientPosition = function(el) { - goog.asserts.assert(el); - if (el.nodeType == goog.dom.NodeType.ELEMENT) { - return goog.style.getClientPositionForElement_( - /** @type {!Element} */ (el)); - } else { - var isAbstractedEvent = goog.isFunction(el.getBrowserEvent); - var be = /** @type {!goog.events.BrowserEvent} */ (el); - var targetEvent = el; - - if (el.targetTouches && el.targetTouches.length) { - targetEvent = el.targetTouches[0]; - } else if (isAbstractedEvent && be.getBrowserEvent().targetTouches && - be.getBrowserEvent().targetTouches.length) { - targetEvent = be.getBrowserEvent().targetTouches[0]; - } - - return new goog.math.Coordinate( - targetEvent.clientX, - targetEvent.clientY); - } -}; - - -/** - * Moves an element to the given coordinates relative to the client viewport. - * @param {Element} el Absolutely positioned element to set page offset for. - * It must be in the document. - * @param {number|goog.math.Coordinate} x Left position of the element's margin - * box or a coordinate object. - * @param {number=} opt_y Top position of the element's margin box. - */ -goog.style.setPageOffset = function(el, x, opt_y) { - // Get current pageoffset - var cur = goog.style.getPageOffset(el); - - if (x instanceof goog.math.Coordinate) { - opt_y = x.y; - x = x.x; - } - - // NOTE(arv): We cannot allow strings for x and y. We could but that would - // require us to manually transform between different units - - // Work out deltas - var dx = x - cur.x; - var dy = opt_y - cur.y; - - // Set position to current left/top + delta - goog.style.setPosition(el, el.offsetLeft + dx, el.offsetTop + dy); -}; - - -/** - * Sets the width/height values of an element. If an argument is numeric, - * or a goog.math.Size is passed, it is assumed to be pixels and will add - * 'px' after converting it to an integer in string form. (This just sets the - * CSS width and height properties so it might set content-box or border-box - * size depending on the box model the browser is using.) - * - * @param {Element} element Element to set the size of. - * @param {string|number|goog.math.Size} w Width of the element, or a - * size object. - * @param {string|number=} opt_h Height of the element. Required if w is not a - * size object. - */ -goog.style.setSize = function(element, w, opt_h) { - var h; - if (w instanceof goog.math.Size) { - h = w.height; - w = w.width; - } else { - if (opt_h == undefined) { - throw Error('missing height argument'); - } - h = opt_h; - } - - goog.style.setWidth(element, /** @type {string|number} */ (w)); - goog.style.setHeight(element, /** @type {string|number} */ (h)); -}; - - -/** - * Helper function to create a string to be set into a pixel-value style - * property of an element. Can round to the nearest integer value. - * - * @param {string|number} value The style value to be used. If a number, - * 'px' will be appended, otherwise the value will be applied directly. - * @param {boolean} round Whether to round the nearest integer (if property - * is a number). - * @return {string} The string value for the property. - * @private - */ -goog.style.getPixelStyleValue_ = function(value, round) { - if (typeof value == 'number') { - value = (round ? Math.round(value) : value) + 'px'; - } - - return value; -}; - - -/** - * Set the height of an element. Sets the element's style property. - * @param {Element} element Element to set the height of. - * @param {string|number} height The height value to set. If a number, 'px' - * will be appended, otherwise the value will be applied directly. - */ -goog.style.setHeight = function(element, height) { - element.style.height = goog.style.getPixelStyleValue_(height, true); -}; - - -/** - * Set the width of an element. Sets the element's style property. - * @param {Element} element Element to set the width of. - * @param {string|number} width The width value to set. If a number, 'px' - * will be appended, otherwise the value will be applied directly. - */ -goog.style.setWidth = function(element, width) { - element.style.width = goog.style.getPixelStyleValue_(width, true); -}; - - -/** - * Gets the height and width of an element, even if its display is none. - * - * Specifically, this returns the height and width of the border box, - * irrespective of the box model in effect. - * - * Note that this function does not take CSS transforms into account. Please see - * {@code goog.style.getTransformedSize}. - * @param {Element} element Element to get size of. - * @return {!goog.math.Size} Object with width/height properties. - */ -goog.style.getSize = function(element) { - return goog.style.evaluateWithTemporaryDisplay_( - goog.style.getSizeWithDisplay_, /** @type {!Element} */ (element)); -}; - - -/** - * Call {@code fn} on {@code element} such that {@code element}'s dimensions are - * accurate when it's passed to {@code fn}. - * @param {function(!Element): T} fn Function to call with {@code element} as - * an argument after temporarily changing {@code element}'s display such - * that its dimensions are accurate. - * @param {!Element} element Element (which may have display none) to use as - * argument to {@code fn}. - * @return {T} Value returned by calling {@code fn} with {@code element}. - * @template T - * @private - */ -goog.style.evaluateWithTemporaryDisplay_ = function(fn, element) { - if (goog.style.getStyle_(element, 'display') != 'none') { - return fn(element); - } - - var style = element.style; - var originalDisplay = style.display; - var originalVisibility = style.visibility; - var originalPosition = style.position; - - style.visibility = 'hidden'; - style.position = 'absolute'; - style.display = 'inline'; - - var retVal = fn(element); - - style.display = originalDisplay; - style.position = originalPosition; - style.visibility = originalVisibility; - - return retVal; -}; - - -/** - * Gets the height and width of an element when the display is not none. - * @param {Element} element Element to get size of. - * @return {!goog.math.Size} Object with width/height properties. - * @private - */ -goog.style.getSizeWithDisplay_ = function(element) { - var offsetWidth = element.offsetWidth; - var offsetHeight = element.offsetHeight; - var webkitOffsetsZero = - goog.userAgent.WEBKIT && !offsetWidth && !offsetHeight; - if ((!goog.isDef(offsetWidth) || webkitOffsetsZero) && - element.getBoundingClientRect) { - // Fall back to calling getBoundingClientRect when offsetWidth or - // offsetHeight are not defined, or when they are zero in WebKit browsers. - // This makes sure that we return for the correct size for SVG elements, but - // will still return 0 on Webkit prior to 534.8, see - // http://trac.webkit.org/changeset/67252. - var clientRect = goog.style.getBoundingClientRect_(element); - return new goog.math.Size(clientRect.right - clientRect.left, - clientRect.bottom - clientRect.top); - } - return new goog.math.Size(offsetWidth, offsetHeight); -}; - - -/** - * Gets the height and width of an element, post transform, even if its display - * is none. - * - * This is like {@code goog.style.getSize}, except: - * <ol> - * <li>Takes webkitTransforms such as rotate and scale into account. - * <li>Will return null if {@code element} doesn't respond to - * {@code getBoundingClientRect}. - * <li>Currently doesn't make sense on non-WebKit browsers which don't support - * webkitTransforms. - * </ol> - * @param {!Element} element Element to get size of. - * @return {goog.math.Size} Object with width/height properties. - */ -goog.style.getTransformedSize = function(element) { - if (!element.getBoundingClientRect) { - return null; - } - - var clientRect = goog.style.evaluateWithTemporaryDisplay_( - goog.style.getBoundingClientRect_, element); - return new goog.math.Size(clientRect.right - clientRect.left, - clientRect.bottom - clientRect.top); -}; - - -/** - * Returns a bounding rectangle for a given element in page space. - * @param {Element} element Element to get bounds of. Must not be display none. - * @return {!goog.math.Rect} Bounding rectangle for the element. - */ -goog.style.getBounds = function(element) { - var o = goog.style.getPageOffset(element); - var s = goog.style.getSize(element); - return new goog.math.Rect(o.x, o.y, s.width, s.height); -}; - - -/** - * Converts a CSS selector in the form style-property to styleProperty. - * @param {*} selector CSS Selector. - * @return {string} Camel case selector. - * @deprecated Use goog.string.toCamelCase instead. - */ -goog.style.toCamelCase = function(selector) { - return goog.string.toCamelCase(String(selector)); -}; - - -/** - * Converts a CSS selector in the form styleProperty to style-property. - * @param {string} selector Camel case selector. - * @return {string} Selector cased. - * @deprecated Use goog.string.toSelectorCase instead. - */ -goog.style.toSelectorCase = function(selector) { - return goog.string.toSelectorCase(selector); -}; - - -/** - * Gets the opacity of a node (x-browser). This gets the inline style opacity - * of the node, and does not take into account the cascaded or the computed - * style for this node. - * @param {Element} el Element whose opacity has to be found. - * @return {number|string} Opacity between 0 and 1 or an empty string {@code ''} - * if the opacity is not set. - */ -goog.style.getOpacity = function(el) { - var style = el.style; - var result = ''; - if ('opacity' in style) { - result = style.opacity; - } else if ('MozOpacity' in style) { - result = style.MozOpacity; - } else if ('filter' in style) { - var match = style.filter.match(/alpha\(opacity=([\d.]+)\)/); - if (match) { - result = String(match[1] / 100); - } - } - return result == '' ? result : Number(result); -}; - - -/** - * Sets the opacity of a node (x-browser). - * @param {Element} el Elements whose opacity has to be set. - * @param {number|string} alpha Opacity between 0 and 1 or an empty string - * {@code ''} to clear the opacity. - */ -goog.style.setOpacity = function(el, alpha) { - var style = el.style; - if ('opacity' in style) { - style.opacity = alpha; - } else if ('MozOpacity' in style) { - style.MozOpacity = alpha; - } else if ('filter' in style) { - // TODO(arv): Overwriting the filter might have undesired side effects. - if (alpha === '') { - style.filter = ''; - } else { - style.filter = 'alpha(opacity=' + alpha * 100 + ')'; - } - } -}; - - -/** - * Sets the background of an element to a transparent image in a browser- - * independent manner. - * - * This function does not support repeating backgrounds or alternate background - * positions to match the behavior of Internet Explorer. It also does not - * support sizingMethods other than crop since they cannot be replicated in - * browsers other than Internet Explorer. - * - * @param {Element} el The element to set background on. - * @param {string} src The image source URL. - */ -goog.style.setTransparentBackgroundImage = function(el, src) { - var style = el.style; - // It is safe to use the style.filter in IE only. In Safari 'filter' is in - // style object but access to style.filter causes it to throw an exception. - // Note: IE8 supports images with an alpha channel. - if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('8')) { - // See TODO in setOpacity. - style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(' + - 'src="' + src + '", sizingMethod="crop")'; - } else { - // Set style properties individually instead of using background shorthand - // to prevent overwriting a pre-existing background color. - style.backgroundImage = 'url(' + src + ')'; - style.backgroundPosition = 'top left'; - style.backgroundRepeat = 'no-repeat'; - } -}; - - -/** - * Clears the background image of an element in a browser independent manner. - * @param {Element} el The element to clear background image for. - */ -goog.style.clearTransparentBackgroundImage = function(el) { - var style = el.style; - if ('filter' in style) { - // See TODO in setOpacity. - style.filter = ''; - } else { - // Set style properties individually instead of using background shorthand - // to prevent overwriting a pre-existing background color. - style.backgroundImage = 'none'; - } -}; - - -/** - * Shows or hides an element from the page. Hiding the element is done by - * setting the display property to "none", removing the element from the - * rendering hierarchy so it takes up no space. To show the element, the default - * inherited display property is restored (defined either in stylesheets or by - * the browser's default style rules.) - * - * Caveat 1: if the inherited display property for the element is set to "none" - * by the stylesheets, that is the property that will be restored by a call to - * showElement(), effectively toggling the display between "none" and "none". - * - * Caveat 2: if the element display style is set inline (by setting either - * element.style.display or a style attribute in the HTML), a call to - * showElement will clear that setting and defer to the inherited style in the - * stylesheet. - * @param {Element} el Element to show or hide. - * @param {*} display True to render the element in its default style, - * false to disable rendering the element. - * @deprecated Use goog.style.setElementShown instead. - */ -goog.style.showElement = function(el, display) { - goog.style.setElementShown(el, display); -}; - - -/** - * Shows or hides an element from the page. Hiding the element is done by - * setting the display property to "none", removing the element from the - * rendering hierarchy so it takes up no space. To show the element, the default - * inherited display property is restored (defined either in stylesheets or by - * the browser's default style rules). - * - * Caveat 1: if the inherited display property for the element is set to "none" - * by the stylesheets, that is the property that will be restored by a call to - * setElementShown(), effectively toggling the display between "none" and - * "none". - * - * Caveat 2: if the element display style is set inline (by setting either - * element.style.display or a style attribute in the HTML), a call to - * setElementShown will clear that setting and defer to the inherited style in - * the stylesheet. - * @param {Element} el Element to show or hide. - * @param {*} isShown True to render the element in its default style, - * false to disable rendering the element. - */ -goog.style.setElementShown = function(el, isShown) { - el.style.display = isShown ? '' : 'none'; -}; - - -/** - * Test whether the given element has been shown or hidden via a call to - * {@link #setElementShown}. - * - * Note this is strictly a companion method for a call - * to {@link #setElementShown} and the same caveats apply; in particular, this - * method does not guarantee that the return value will be consistent with - * whether or not the element is actually visible. - * - * @param {Element} el The element to test. - * @return {boolean} Whether the element has been shown. - * @see #setElementShown - */ -goog.style.isElementShown = function(el) { - return el.style.display != 'none'; -}; - - -/** - * Installs the styles string into the window that contains opt_element. If - * opt_element is null, the main window is used. - * @param {string} stylesString The style string to install. - * @param {Node=} opt_node Node whose parent document should have the - * styles installed. - * @return {Element|StyleSheet} The style element created. - */ -goog.style.installStyles = function(stylesString, opt_node) { - var dh = goog.dom.getDomHelper(opt_node); - var styleSheet = null; - - // IE < 11 requires createStyleSheet. Note that doc.createStyleSheet will be - // undefined as of IE 11. - var doc = dh.getDocument(); - if (goog.userAgent.IE && doc.createStyleSheet) { - styleSheet = doc.createStyleSheet(); - goog.style.setStyles(styleSheet, stylesString); - } else { - var head = dh.getElementsByTagNameAndClass('head')[0]; - - // In opera documents are not guaranteed to have a head element, thus we - // have to make sure one exists before using it. - if (!head) { - var body = dh.getElementsByTagNameAndClass('body')[0]; - head = dh.createDom('head'); - body.parentNode.insertBefore(head, body); - } - styleSheet = dh.createDom('style'); - // NOTE(user): Setting styles after the style element has been appended - // to the head results in a nasty Webkit bug in certain scenarios. Please - // refer to https://bugs.webkit.org/show_bug.cgi?id=26307 for additional - // details. - goog.style.setStyles(styleSheet, stylesString); - dh.appendChild(head, styleSheet); - } - return styleSheet; -}; - - -/** - * Removes the styles added by {@link #installStyles}. - * @param {Element|StyleSheet} styleSheet The value returned by - * {@link #installStyles}. - */ -goog.style.uninstallStyles = function(styleSheet) { - var node = styleSheet.ownerNode || styleSheet.owningElement || - /** @type {Element} */ (styleSheet); - goog.dom.removeNode(node); -}; - - -/** - * Sets the content of a style element. The style element can be any valid - * style element. This element will have its content completely replaced by - * the new stylesString. - * @param {Element|StyleSheet} element A stylesheet element as returned by - * installStyles. - * @param {string} stylesString The new content of the stylesheet. - */ -goog.style.setStyles = function(element, stylesString) { - if (goog.userAgent.IE && goog.isDef(element.cssText)) { - // Adding the selectors individually caused the browser to hang if the - // selector was invalid or there were CSS comments. Setting the cssText of - // the style node works fine and ignores CSS that IE doesn't understand. - // However IE >= 11 doesn't support cssText any more, so we make sure that - // cssText is a defined property and otherwise fall back to innerHTML. - element.cssText = stylesString; - } else { - element.innerHTML = stylesString; - } -}; - - -/** - * Sets 'white-space: pre-wrap' for a node (x-browser). - * - * There are as many ways of specifying pre-wrap as there are browsers. - * - * CSS3/IE8: white-space: pre-wrap; - * Mozilla: white-space: -moz-pre-wrap; - * Opera: white-space: -o-pre-wrap; - * IE6/7: white-space: pre; word-wrap: break-word; - * - * @param {Element} el Element to enable pre-wrap for. - */ -goog.style.setPreWrap = function(el) { - var style = el.style; - if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('8')) { - style.whiteSpace = 'pre'; - style.wordWrap = 'break-word'; - } else if (goog.userAgent.GECKO) { - style.whiteSpace = '-moz-pre-wrap'; - } else { - style.whiteSpace = 'pre-wrap'; - } -}; - - -/** - * Sets 'display: inline-block' for an element (cross-browser). - * @param {Element} el Element to which the inline-block display style is to be - * applied. - * @see ../demos/inline_block_quirks.html - * @see ../demos/inline_block_standards.html - */ -goog.style.setInlineBlock = function(el) { - var style = el.style; - // Without position:relative, weirdness ensues. Just accept it and move on. - style.position = 'relative'; - - if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('8')) { - // IE8 supports inline-block so fall through to the else - // Zoom:1 forces hasLayout, display:inline gives inline behavior. - style.zoom = '1'; - style.display = 'inline'; - } else { - // Opera, Webkit, and Safari seem to do OK with the standard inline-block - // style. - style.display = 'inline-block'; - } -}; - - -/** - * Returns true if the element is using right to left (rtl) direction. - * @param {Element} el The element to test. - * @return {boolean} True for right to left, false for left to right. - */ -goog.style.isRightToLeft = function(el) { - return 'rtl' == goog.style.getStyle_(el, 'direction'); -}; - - -/** - * The CSS style property corresponding to an element being - * unselectable on the current browser platform (null if none). - * Opera and IE instead use a DOM attribute 'unselectable'. - * @type {?string} - * @private - */ -goog.style.unselectableStyle_ = - goog.userAgent.GECKO ? 'MozUserSelect' : - goog.userAgent.WEBKIT ? 'WebkitUserSelect' : - null; - - -/** - * Returns true if the element is set to be unselectable, false otherwise. - * Note that on some platforms (e.g. Mozilla), even if an element isn't set - * to be unselectable, it will behave as such if any of its ancestors is - * unselectable. - * @param {Element} el Element to check. - * @return {boolean} Whether the element is set to be unselectable. - */ -goog.style.isUnselectable = function(el) { - if (goog.style.unselectableStyle_) { - return el.style[goog.style.unselectableStyle_].toLowerCase() == 'none'; - } else if (goog.userAgent.IE || goog.userAgent.OPERA) { - return el.getAttribute('unselectable') == 'on'; - } - return false; -}; - - -/** - * Makes the element and its descendants selectable or unselectable. Note - * that on some platforms (e.g. Mozilla), even if an element isn't set to - * be unselectable, it will behave as such if any of its ancestors is - * unselectable. - * @param {Element} el The element to alter. - * @param {boolean} unselectable Whether the element and its descendants - * should be made unselectable. - * @param {boolean=} opt_noRecurse Whether to only alter the element's own - * selectable state, and leave its descendants alone; defaults to false. - */ -goog.style.setUnselectable = function(el, unselectable, opt_noRecurse) { - // TODO(attila): Do we need all of TR_DomUtil.makeUnselectable() in Closure? - var descendants = !opt_noRecurse ? el.getElementsByTagName('*') : null; - var name = goog.style.unselectableStyle_; - if (name) { - // Add/remove the appropriate CSS style to/from the element and its - // descendants. - var value = unselectable ? 'none' : ''; - el.style[name] = value; - if (descendants) { - for (var i = 0, descendant; descendant = descendants[i]; i++) { - descendant.style[name] = value; - } - } - } else if (goog.userAgent.IE || goog.userAgent.OPERA) { - // Toggle the 'unselectable' attribute on the element and its descendants. - var value = unselectable ? 'on' : ''; - el.setAttribute('unselectable', value); - if (descendants) { - for (var i = 0, descendant; descendant = descendants[i]; i++) { - descendant.setAttribute('unselectable', value); - } - } - } -}; - - -/** - * Gets the border box size for an element. - * @param {Element} element The element to get the size for. - * @return {!goog.math.Size} The border box size. - */ -goog.style.getBorderBoxSize = function(element) { - return new goog.math.Size(element.offsetWidth, element.offsetHeight); -}; - - -/** - * Sets the border box size of an element. This is potentially expensive in IE - * if the document is CSS1Compat mode - * @param {Element} element The element to set the size on. - * @param {goog.math.Size} size The new size. - */ -goog.style.setBorderBoxSize = function(element, size) { - var doc = goog.dom.getOwnerDocument(element); - var isCss1CompatMode = goog.dom.getDomHelper(doc).isCss1CompatMode(); - - if (goog.userAgent.IE && - !goog.userAgent.isVersionOrHigher('10') && - (!isCss1CompatMode || !goog.userAgent.isVersionOrHigher('8'))) { - var style = element.style; - if (isCss1CompatMode) { - var paddingBox = goog.style.getPaddingBox(element); - var borderBox = goog.style.getBorderBox(element); - style.pixelWidth = size.width - borderBox.left - paddingBox.left - - paddingBox.right - borderBox.right; - style.pixelHeight = size.height - borderBox.top - paddingBox.top - - paddingBox.bottom - borderBox.bottom; - } else { - style.pixelWidth = size.width; - style.pixelHeight = size.height; - } - } else { - goog.style.setBoxSizingSize_(element, size, 'border-box'); - } -}; - - -/** - * Gets the content box size for an element. This is potentially expensive in - * all browsers. - * @param {Element} element The element to get the size for. - * @return {!goog.math.Size} The content box size. - */ -goog.style.getContentBoxSize = function(element) { - var doc = goog.dom.getOwnerDocument(element); - var ieCurrentStyle = goog.userAgent.IE && element.currentStyle; - if (ieCurrentStyle && - goog.dom.getDomHelper(doc).isCss1CompatMode() && - ieCurrentStyle.width != 'auto' && ieCurrentStyle.height != 'auto' && - !ieCurrentStyle.boxSizing) { - // If IE in CSS1Compat mode than just use the width and height. - // If we have a boxSizing then fall back on measuring the borders etc. - var width = goog.style.getIePixelValue_(element, ieCurrentStyle.width, - 'width', 'pixelWidth'); - var height = goog.style.getIePixelValue_(element, ieCurrentStyle.height, - 'height', 'pixelHeight'); - return new goog.math.Size(width, height); - } else { - var borderBoxSize = goog.style.getBorderBoxSize(element); - var paddingBox = goog.style.getPaddingBox(element); - var borderBox = goog.style.getBorderBox(element); - return new goog.math.Size(borderBoxSize.width - - borderBox.left - paddingBox.left - - paddingBox.right - borderBox.right, - borderBoxSize.height - - borderBox.top - paddingBox.top - - paddingBox.bottom - borderBox.bottom); - } -}; - - -/** - * Sets the content box size of an element. This is potentially expensive in IE - * if the document is BackCompat mode. - * @param {Element} element The element to set the size on. - * @param {goog.math.Size} size The new size. - */ -goog.style.setContentBoxSize = function(element, size) { - var doc = goog.dom.getOwnerDocument(element); - var isCss1CompatMode = goog.dom.getDomHelper(doc).isCss1CompatMode(); - if (goog.userAgent.IE && - !goog.userAgent.isVersionOrHigher('10') && - (!isCss1CompatMode || !goog.userAgent.isVersionOrHigher('8'))) { - var style = element.style; - if (isCss1CompatMode) { - style.pixelWidth = size.width; - style.pixelHeight = size.height; - } else { - var paddingBox = goog.style.getPaddingBox(element); - var borderBox = goog.style.getBorderBox(element); - style.pixelWidth = size.width + borderBox.left + paddingBox.left + - paddingBox.right + borderBox.right; - style.pixelHeight = size.height + borderBox.top + paddingBox.top + - paddingBox.bottom + borderBox.bottom; - } - } else { - goog.style.setBoxSizingSize_(element, size, 'content-box'); - } -}; - - -/** - * Helper function that sets the box sizing as well as the width and height - * @param {Element} element The element to set the size on. - * @param {goog.math.Size} size The new size to set. - * @param {string} boxSizing The box-sizing value. - * @private - */ -goog.style.setBoxSizingSize_ = function(element, size, boxSizing) { - var style = element.style; - if (goog.userAgent.GECKO) { - style.MozBoxSizing = boxSizing; - } else if (goog.userAgent.WEBKIT) { - style.WebkitBoxSizing = boxSizing; - } else { - // Includes IE8 and Opera 9.50+ - style.boxSizing = boxSizing; - } - - // Setting this to a negative value will throw an exception on IE - // (and doesn't do anything different than setting it to 0). - style.width = Math.max(size.width, 0) + 'px'; - style.height = Math.max(size.height, 0) + 'px'; -}; - - -/** - * IE specific function that converts a non pixel unit to pixels. - * @param {Element} element The element to convert the value for. - * @param {string} value The current value as a string. The value must not be - * ''. - * @param {string} name The CSS property name to use for the converstion. This - * should be 'left', 'top', 'width' or 'height'. - * @param {string} pixelName The CSS pixel property name to use to get the - * value in pixels. - * @return {number} The value in pixels. - * @private - */ -goog.style.getIePixelValue_ = function(element, value, name, pixelName) { - // Try if we already have a pixel value. IE does not do half pixels so we - // only check if it matches a number followed by 'px'. - if (/^\d+px?$/.test(value)) { - return parseInt(value, 10); - } else { - var oldStyleValue = element.style[name]; - var oldRuntimeValue = element.runtimeStyle[name]; - // set runtime style to prevent changes - element.runtimeStyle[name] = element.currentStyle[name]; - element.style[name] = value; - var pixelValue = element.style[pixelName]; - // restore - element.style[name] = oldStyleValue; - element.runtimeStyle[name] = oldRuntimeValue; - return pixelValue; - } -}; - - -/** - * Helper function for getting the pixel padding or margin for IE. - * @param {Element} element The element to get the padding for. - * @param {string} propName The property name. - * @return {number} The pixel padding. - * @private - */ -goog.style.getIePixelDistance_ = function(element, propName) { - var value = goog.style.getCascadedStyle(element, propName); - return value ? - goog.style.getIePixelValue_(element, value, 'left', 'pixelLeft') : 0; -}; - - -/** - * Gets the computed paddings or margins (on all sides) in pixels. - * @param {Element} element The element to get the padding for. - * @param {string} stylePrefix Pass 'padding' to retrieve the padding box, - * or 'margin' to retrieve the margin box. - * @return {!goog.math.Box} The computed paddings or margins. - * @private - */ -goog.style.getBox_ = function(element, stylePrefix) { - if (goog.userAgent.IE) { - var left = goog.style.getIePixelDistance_(element, stylePrefix + 'Left'); - var right = goog.style.getIePixelDistance_(element, stylePrefix + 'Right'); - var top = goog.style.getIePixelDistance_(element, stylePrefix + 'Top'); - var bottom = goog.style.getIePixelDistance_( - element, stylePrefix + 'Bottom'); - return new goog.math.Box(top, right, bottom, left); - } else { - // On non-IE browsers, getComputedStyle is always non-null. - var left = /** @type {string} */ ( - goog.style.getComputedStyle(element, stylePrefix + 'Left')); - var right = /** @type {string} */ ( - goog.style.getComputedStyle(element, stylePrefix + 'Right')); - var top = /** @type {string} */ ( - goog.style.getComputedStyle(element, stylePrefix + 'Top')); - var bottom = /** @type {string} */ ( - goog.style.getComputedStyle(element, stylePrefix + 'Bottom')); - - // NOTE(arv): Gecko can return floating point numbers for the computed - // style values. - return new goog.math.Box(parseFloat(top), - parseFloat(right), - parseFloat(bottom), - parseFloat(left)); - } -}; - - -/** - * Gets the computed paddings (on all sides) in pixels. - * @param {Element} element The element to get the padding for. - * @return {!goog.math.Box} The computed paddings. - */ -goog.style.getPaddingBox = function(element) { - return goog.style.getBox_(element, 'padding'); -}; - - -/** - * Gets the computed margins (on all sides) in pixels. - * @param {Element} element The element to get the margins for. - * @return {!goog.math.Box} The computed margins. - */ -goog.style.getMarginBox = function(element) { - return goog.style.getBox_(element, 'margin'); -}; - - -/** - * A map used to map the border width keywords to a pixel width. - * @type {Object} - * @private - */ -goog.style.ieBorderWidthKeywords_ = { - 'thin': 2, - 'medium': 4, - 'thick': 6 -}; - - -/** - * Helper function for IE to get the pixel border. - * @param {Element} element The element to get the pixel border for. - * @param {string} prop The part of the property name. - * @return {number} The value in pixels. - * @private - */ -goog.style.getIePixelBorder_ = function(element, prop) { - if (goog.style.getCascadedStyle(element, prop + 'Style') == 'none') { - return 0; - } - var width = goog.style.getCascadedStyle(element, prop + 'Width'); - if (width in goog.style.ieBorderWidthKeywords_) { - return goog.style.ieBorderWidthKeywords_[width]; - } - return goog.style.getIePixelValue_(element, width, 'left', 'pixelLeft'); -}; - - -/** - * Gets the computed border widths (on all sides) in pixels - * @param {Element} element The element to get the border widths for. - * @return {!goog.math.Box} The computed border widths. - */ -goog.style.getBorderBox = function(element) { - if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) { - var left = goog.style.getIePixelBorder_(element, 'borderLeft'); - var right = goog.style.getIePixelBorder_(element, 'borderRight'); - var top = goog.style.getIePixelBorder_(element, 'borderTop'); - var bottom = goog.style.getIePixelBorder_(element, 'borderBottom'); - return new goog.math.Box(top, right, bottom, left); - } else { - // On non-IE browsers, getComputedStyle is always non-null. - var left = /** @type {string} */ ( - goog.style.getComputedStyle(element, 'borderLeftWidth')); - var right = /** @type {string} */ ( - goog.style.getComputedStyle(element, 'borderRightWidth')); - var top = /** @type {string} */ ( - goog.style.getComputedStyle(element, 'borderTopWidth')); - var bottom = /** @type {string} */ ( - goog.style.getComputedStyle(element, 'borderBottomWidth')); - - return new goog.math.Box(parseFloat(top), - parseFloat(right), - parseFloat(bottom), - parseFloat(left)); - } -}; - - -/** - * Returns the font face applied to a given node. Opera and IE should return - * the font actually displayed. Firefox returns the author's most-preferred - * font (whether the browser is capable of displaying it or not.) - * @param {Element} el The element whose font family is returned. - * @return {string} The font family applied to el. - */ -goog.style.getFontFamily = function(el) { - var doc = goog.dom.getOwnerDocument(el); - var font = ''; - // The moveToElementText method from the TextRange only works if the element - // is attached to the owner document. - if (doc.body.createTextRange && goog.dom.contains(doc, el)) { - var range = doc.body.createTextRange(); - range.moveToElementText(el); - /** @preserveTry */ - try { - font = range.queryCommandValue('FontName'); - } catch (e) { - // This is a workaround for a awkward exception. - // On some IE, there is an exception coming from it. - // The error description from this exception is: - // This window has already been registered as a drop target - // This is bogus description, likely due to a bug in ie. - font = ''; - } - } - if (!font) { - // Note if for some reason IE can't derive FontName with a TextRange, we - // fallback to using currentStyle - font = goog.style.getStyle_(el, 'fontFamily'); - } - - // Firefox returns the applied font-family string (author's list of - // preferred fonts.) We want to return the most-preferred font, in lieu of - // the *actually* applied font. - var fontsArray = font.split(','); - if (fontsArray.length > 1) font = fontsArray[0]; - - // Sanitize for x-browser consistency: - // Strip quotes because browsers aren't consistent with how they're - // applied; Opera always encloses, Firefox sometimes, and IE never. - return goog.string.stripQuotes(font, '"\''); -}; - - -/** - * Regular expression used for getLengthUnits. - * @type {RegExp} - * @private - */ -goog.style.lengthUnitRegex_ = /[^\d]+$/; - - -/** - * Returns the units used for a CSS length measurement. - * @param {string} value A CSS length quantity. - * @return {?string} The units of measurement. - */ -goog.style.getLengthUnits = function(value) { - var units = value.match(goog.style.lengthUnitRegex_); - return units && units[0] || null; -}; - - -/** - * Map of absolute CSS length units - * @type {Object} - * @private - */ -goog.style.ABSOLUTE_CSS_LENGTH_UNITS_ = { - 'cm' : 1, - 'in' : 1, - 'mm' : 1, - 'pc' : 1, - 'pt' : 1 -}; - - -/** - * Map of relative CSS length units that can be accurately converted to px - * font-size values using getIePixelValue_. Only units that are defined in - * relation to a font size are convertible (%, small, etc. are not). - * @type {Object} - * @private - */ -goog.style.CONVERTIBLE_RELATIVE_CSS_UNITS_ = { - 'em' : 1, - 'ex' : 1 -}; - - -/** - * Returns the font size, in pixels, of text in an element. - * @param {Element} el The element whose font size is returned. - * @return {number} The font size (in pixels). - */ -goog.style.getFontSize = function(el) { - var fontSize = goog.style.getStyle_(el, 'fontSize'); - var sizeUnits = goog.style.getLengthUnits(fontSize); - if (fontSize && 'px' == sizeUnits) { - // NOTE(user): This could be parseFloat instead, but IE doesn't return - // decimal fractions in getStyle_ and Firefox reports the fractions, but - // ignores them when rendering. Interestingly enough, when we force the - // issue and size something to e.g., 50% of 25px, the browsers round in - // opposite directions with Firefox reporting 12px and IE 13px. I punt. - return parseInt(fontSize, 10); - } - - // In IE, we can convert absolute length units to a px value using - // goog.style.getIePixelValue_. Units defined in relation to a font size - // (em, ex) are applied relative to the element's parentNode and can also - // be converted. - if (goog.userAgent.IE) { - if (sizeUnits in goog.style.ABSOLUTE_CSS_LENGTH_UNITS_) { - return goog.style.getIePixelValue_(el, - fontSize, - 'left', - 'pixelLeft'); - } else if (el.parentNode && - el.parentNode.nodeType == goog.dom.NodeType.ELEMENT && - sizeUnits in goog.style.CONVERTIBLE_RELATIVE_CSS_UNITS_) { - // Check the parent size - if it is the same it means the relative size - // value is inherited and we therefore don't want to count it twice. If - // it is different, this element either has explicit style or has a CSS - // rule applying to it. - var parentElement = /** @type {!Element} */ (el.parentNode); - var parentSize = goog.style.getStyle_(parentElement, 'fontSize'); - return goog.style.getIePixelValue_(parentElement, - fontSize == parentSize ? - '1em' : fontSize, - 'left', - 'pixelLeft'); - } - } - - // Sometimes we can't cleanly find the font size (some units relative to a - // node's parent's font size are difficult: %, smaller et al), so we create - // an invisible, absolutely-positioned span sized to be the height of an 'M' - // rendered in its parent's (i.e., our target element's) font size. This is - // the definition of CSS's font size attribute. - var sizeElement = goog.dom.createDom( - 'span', - {'style': 'visibility:hidden;position:absolute;' + - 'line-height:0;padding:0;margin:0;border:0;height:1em;'}); - goog.dom.appendChild(el, sizeElement); - fontSize = sizeElement.offsetHeight; - goog.dom.removeNode(sizeElement); - - return fontSize; -}; - - -/** - * Parses a style attribute value. Converts CSS property names to camel case. - * @param {string} value The style attribute value. - * @return {!Object} Map of CSS properties to string values. - */ -goog.style.parseStyleAttribute = function(value) { - var result = {}; - goog.array.forEach(value.split(/\s*;\s*/), function(pair) { - var keyValue = pair.split(/\s*:\s*/); - if (keyValue.length == 2) { - result[goog.string.toCamelCase(keyValue[0].toLowerCase())] = keyValue[1]; - } - }); - return result; -}; - - -/** - * Reverse of parseStyleAttribute; that is, takes a style object and returns the - * corresponding attribute value. Converts camel case property names to proper - * CSS selector names. - * @param {Object} obj Map of CSS properties to values. - * @return {string} The style attribute value. - */ -goog.style.toStyleAttribute = function(obj) { - var buffer = []; - goog.object.forEach(obj, function(value, key) { - buffer.push(goog.string.toSelectorCase(key), ':', value, ';'); - }); - return buffer.join(''); -}; - - -/** - * Sets CSS float property on an element. - * @param {Element} el The element to set float property on. - * @param {string} value The value of float CSS property to set on this element. - */ -goog.style.setFloat = function(el, value) { - el.style[goog.userAgent.IE ? 'styleFloat' : 'cssFloat'] = value; -}; - - -/** - * Gets value of explicitly-set float CSS property on an element. - * @param {Element} el The element to get float property of. - * @return {string} The value of explicitly-set float CSS property on this - * element. - */ -goog.style.getFloat = function(el) { - return el.style[goog.userAgent.IE ? 'styleFloat' : 'cssFloat'] || ''; -}; - - -/** - * Returns the scroll bar width (represents the width of both horizontal - * and vertical scroll). - * - * @param {string=} opt_className An optional class name (or names) to apply - * to the invisible div created to measure the scrollbar. This is necessary - * if some scrollbars are styled differently than others. - * @return {number} The scroll bar width in px. - */ -goog.style.getScrollbarWidth = function(opt_className) { - // Add two hidden divs. The child div is larger than the parent and - // forces scrollbars to appear on it. - // Using overflow:scroll does not work consistently with scrollbars that - // are styled with ::-webkit-scrollbar. - var outerDiv = goog.dom.createElement('div'); - if (opt_className) { - outerDiv.className = opt_className; - } - outerDiv.style.cssText = 'overflow:auto;' + - 'position:absolute;top:0;width:100px;height:100px'; - var innerDiv = goog.dom.createElement('div'); - goog.style.setSize(innerDiv, '200px', '200px'); - outerDiv.appendChild(innerDiv); - goog.dom.appendChild(goog.dom.getDocument().body, outerDiv); - var width = outerDiv.offsetWidth - outerDiv.clientWidth; - goog.dom.removeNode(outerDiv); - return width; -}; - - -/** - * Regular expression to extract x and y translation components from a CSS - * transform Matrix representation. - * - * @type {!RegExp} - * @const - * @private - */ -goog.style.MATRIX_TRANSLATION_REGEX_ = - new RegExp('matrix\\([0-9\\.\\-]+, [0-9\\.\\-]+, ' + - '[0-9\\.\\-]+, [0-9\\.\\-]+, ' + - '([0-9\\.\\-]+)p?x?, ([0-9\\.\\-]+)p?x?\\)'); - - -/** - * Returns the x,y translation component of any CSS transforms applied to the - * element, in pixels. - * - * @param {!Element} element The element to get the translation of. - * @return {!goog.math.Coordinate} The CSS translation of the element in px. - */ -goog.style.getCssTranslation = function(element) { - var transform = goog.style.getComputedTransform(element); - if (!transform) { - return new goog.math.Coordinate(0, 0); - } - var matches = transform.match(goog.style.MATRIX_TRANSLATION_REGEX_); - if (!matches) { - return new goog.math.Coordinate(0, 0); - } - return new goog.math.Coordinate(parseFloat(matches[1]), - parseFloat(matches[2])); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/testing/watchers.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/testing/watchers.js deleted file mode 100644 index a242a57..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/testing/watchers.js +++ /dev/null @@ -1,46 +0,0 @@ -// 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 Simple notifiers for the Closure testing framework. - * - * @author johnlenz@google.com (John Lenz) - */ - -goog.provide('goog.testing.watchers'); - - -/** @private {!Array<function()>} */ -goog.testing.watchers.resetWatchers_ = []; - - -/** - * Fires clock reset watching functions. - */ -goog.testing.watchers.signalClockReset = function() { - var watchers = goog.testing.watchers.resetWatchers_; - for (var i = 0; i < watchers.length; i++) { - goog.testing.watchers.resetWatchers_[i](); - } -}; - - -/** - * Enqueues a function to be called when the clock used for setTimeout is reset. - * @param {function()} fn - */ -goog.testing.watchers.watchClockReset = function(fn) { - goog.testing.watchers.resetWatchers_.push(fn); -}; - diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/timer/timer.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/timer/timer.js deleted file mode 100644 index 19a26b6..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/timer/timer.js +++ /dev/null @@ -1,329 +0,0 @@ -// 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.Promise'); -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 setTimeout, 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; - - -/** - * A timer ID that cannot be returned by any known implmentation of - * Window.setTimeout. Passing this value to window.clearTimeout should - * therefore be a no-op. - * - * @const {number} - * @private - */ -goog.Timer.INVALID_TIMEOUT_ID_ = -1; - - -/** - * 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; - } - - // Prevents setInterval from registering a duplicate timeout when called - // in the timer event handler. - if (this.timer_) { - this.timerObject_.clearTimeout(this.timer_); - this.timer_ = null; - } - - 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(this:SCOPE)|{handleEvent:function()}|null} listener Function - * or object that has a handleEvent method. - * @param {number=} opt_delay Milliseconds to wait; default is 0. - * @param {SCOPE=} opt_handler Object in whose scope to call the listener. - * @return {number} A handle to the timer ID. - * @template SCOPE - */ -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 goog.Timer.INVALID_TIMEOUT_ID_; - } 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); -}; - - -/** - * @param {number} delay Milliseconds to wait. - * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value - * with which the promise will be resolved. - * @return {!goog.Promise<RESULT>} A promise that will be resolved after - * the specified delay, unless it is canceled first. - * @template RESULT - */ -goog.Timer.promise = function(delay, opt_result) { - var timerKey = null; - return new goog.Promise(function(resolve, reject) { - timerKey = goog.Timer.callOnce(function() { - resolve(opt_result); - }, delay); - if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) { - reject(new Error('Failed to schedule timer.')); - } - }).thenCatch(function(error) { - // Clear the timer. The most likely reason is "cancel" signal. - goog.Timer.clear(timerKey); - throw error; - }); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/uri/uri.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/uri/uri.js deleted file mode 100644 index 86b9d47..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/uri/uri.js +++ /dev/null @@ -1,1526 +0,0 @@ -// 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 Class for parsing and formatting URIs. - * - * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to - * create a new instance of the goog.Uri object from Uri parts. - * - * e.g: <code>var myUri = new goog.Uri(window.location);</code> - * - * Implements RFC 3986 for parsing/formatting URIs. - * http://www.ietf.org/rfc/rfc3986.txt - * - * Some changes have been made to the interface (more like .NETs), though the - * internal representation is now of un-encoded parts, this will change the - * behavior slightly. - * - */ - -goog.provide('goog.Uri'); -goog.provide('goog.Uri.QueryData'); - -goog.require('goog.array'); -goog.require('goog.string'); -goog.require('goog.structs'); -goog.require('goog.structs.Map'); -goog.require('goog.uri.utils'); -goog.require('goog.uri.utils.ComponentIndex'); -goog.require('goog.uri.utils.StandardQueryParam'); - - - -/** - * This class contains setters and getters for the parts of the URI. - * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part - * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the - * decoded path, <code>/foo bar</code>. - * - * Reserved characters (see RFC 3986 section 2.2) can be present in - * their percent-encoded form in scheme, domain, and path URI components and - * will not be auto-decoded. For example: - * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will - * return <code>relative/path%2fto/resource</code>. - * - * The constructor accepts an optional unparsed, raw URI string. The parser - * is relaxed, so special characters that aren't escaped but don't cause - * ambiguities will not cause parse failures. - * - * All setters return <code>this</code> and so may be chained, a la - * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>. - * - * @param {*=} opt_uri Optional string URI to parse - * (use goog.Uri.create() to create a URI from parts), or if - * a goog.Uri is passed, a clone is created. - * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore - * the case of the parameter name. - * - * @constructor - * @struct - */ -goog.Uri = function(opt_uri, opt_ignoreCase) { - // Parse in the uri string - var m; - if (opt_uri instanceof goog.Uri) { - this.ignoreCase_ = goog.isDef(opt_ignoreCase) ? - opt_ignoreCase : opt_uri.getIgnoreCase(); - this.setScheme(opt_uri.getScheme()); - this.setUserInfo(opt_uri.getUserInfo()); - this.setDomain(opt_uri.getDomain()); - this.setPort(opt_uri.getPort()); - this.setPath(opt_uri.getPath()); - this.setQueryData(opt_uri.getQueryData().clone()); - this.setFragment(opt_uri.getFragment()); - } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) { - this.ignoreCase_ = !!opt_ignoreCase; - - // Set the parts -- decoding as we do so. - // COMPATABILITY NOTE - In IE, unmatched fields may be empty strings, - // whereas in other browsers they will be undefined. - this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true); - this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true); - this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true); - this.setPort(m[goog.uri.utils.ComponentIndex.PORT]); - this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true); - this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true); - this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true); - - } else { - this.ignoreCase_ = !!opt_ignoreCase; - this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_); - } -}; - - -/** - * If true, we preserve the type of query parameters set programmatically. - * - * This means that if you set a parameter to a boolean, and then call - * getParameterValue, you will get a boolean back. - * - * If false, we will coerce parameters to strings, just as they would - * appear in real URIs. - * - * TODO(nicksantos): Remove this once people have time to fix all tests. - * - * @type {boolean} - */ -goog.Uri.preserveParameterTypesCompatibilityFlag = false; - - -/** - * Parameter name added to stop caching. - * @type {string} - */ -goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM; - - -/** - * Scheme such as "http". - * @type {string} - * @private - */ -goog.Uri.prototype.scheme_ = ''; - - -/** - * User credentials in the form "username:password". - * @type {string} - * @private - */ -goog.Uri.prototype.userInfo_ = ''; - - -/** - * Domain part, e.g. "www.google.com". - * @type {string} - * @private - */ -goog.Uri.prototype.domain_ = ''; - - -/** - * Port, e.g. 8080. - * @type {?number} - * @private - */ -goog.Uri.prototype.port_ = null; - - -/** - * Path, e.g. "/tests/img.png". - * @type {string} - * @private - */ -goog.Uri.prototype.path_ = ''; - - -/** - * Object representing query data. - * @type {!goog.Uri.QueryData} - * @private - */ -goog.Uri.prototype.queryData_; - - -/** - * The fragment without the #. - * @type {string} - * @private - */ -goog.Uri.prototype.fragment_ = ''; - - -/** - * Whether or not this Uri should be treated as Read Only. - * @type {boolean} - * @private - */ -goog.Uri.prototype.isReadOnly_ = false; - - -/** - * Whether or not to ignore case when comparing query params. - * @type {boolean} - * @private - */ -goog.Uri.prototype.ignoreCase_ = false; - - -/** - * @return {string} The string form of the url. - * @override - */ -goog.Uri.prototype.toString = function() { - var out = []; - - var scheme = this.getScheme(); - if (scheme) { - out.push(goog.Uri.encodeSpecialChars_( - scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), ':'); - } - - var domain = this.getDomain(); - if (domain) { - out.push('//'); - - var userInfo = this.getUserInfo(); - if (userInfo) { - out.push(goog.Uri.encodeSpecialChars_( - userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), '@'); - } - - out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain))); - - var port = this.getPort(); - if (port != null) { - out.push(':', String(port)); - } - } - - var path = this.getPath(); - if (path) { - if (this.hasDomain() && path.charAt(0) != '/') { - out.push('/'); - } - out.push(goog.Uri.encodeSpecialChars_( - path, - path.charAt(0) == '/' ? - goog.Uri.reDisallowedInAbsolutePath_ : - goog.Uri.reDisallowedInRelativePath_, - true)); - } - - var query = this.getEncodedQuery(); - if (query) { - out.push('?', query); - } - - var fragment = this.getFragment(); - if (fragment) { - out.push('#', goog.Uri.encodeSpecialChars_( - fragment, goog.Uri.reDisallowedInFragment_)); - } - return out.join(''); -}; - - -/** - * Resolves the given relative URI (a goog.Uri object), using the URI - * represented by this instance as the base URI. - * - * There are several kinds of relative URIs:<br> - * 1. foo - replaces the last part of the path, the whole query and fragment<br> - * 2. /foo - replaces the the path, the query and fragment<br> - * 3. //foo - replaces everything from the domain on. foo is a domain name<br> - * 4. ?foo - replace the query and fragment<br> - * 5. #foo - replace the fragment only - * - * Additionally, if relative URI has a non-empty path, all ".." and "." - * segments will be resolved, as described in RFC 3986. - * - * @param {!goog.Uri} relativeUri The relative URI to resolve. - * @return {!goog.Uri} The resolved URI. - */ -goog.Uri.prototype.resolve = function(relativeUri) { - - var absoluteUri = this.clone(); - - // we satisfy these conditions by looking for the first part of relativeUri - // that is not blank and applying defaults to the rest - - var overridden = relativeUri.hasScheme(); - - if (overridden) { - absoluteUri.setScheme(relativeUri.getScheme()); - } else { - overridden = relativeUri.hasUserInfo(); - } - - if (overridden) { - absoluteUri.setUserInfo(relativeUri.getUserInfo()); - } else { - overridden = relativeUri.hasDomain(); - } - - if (overridden) { - absoluteUri.setDomain(relativeUri.getDomain()); - } else { - overridden = relativeUri.hasPort(); - } - - var path = relativeUri.getPath(); - if (overridden) { - absoluteUri.setPort(relativeUri.getPort()); - } else { - overridden = relativeUri.hasPath(); - if (overridden) { - // resolve path properly - if (path.charAt(0) != '/') { - // path is relative - if (this.hasDomain() && !this.hasPath()) { - // RFC 3986, section 5.2.3, case 1 - path = '/' + path; - } else { - // RFC 3986, section 5.2.3, case 2 - var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/'); - if (lastSlashIndex != -1) { - path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path; - } - } - } - path = goog.Uri.removeDotSegments(path); - } - } - - if (overridden) { - absoluteUri.setPath(path); - } else { - overridden = relativeUri.hasQuery(); - } - - if (overridden) { - absoluteUri.setQueryData(relativeUri.getDecodedQuery()); - } else { - overridden = relativeUri.hasFragment(); - } - - if (overridden) { - absoluteUri.setFragment(relativeUri.getFragment()); - } - - return absoluteUri; -}; - - -/** - * Clones the URI instance. - * @return {!goog.Uri} New instance of the URI object. - */ -goog.Uri.prototype.clone = function() { - return new goog.Uri(this); -}; - - -/** - * @return {string} The encoded scheme/protocol for the URI. - */ -goog.Uri.prototype.getScheme = function() { - return this.scheme_; -}; - - -/** - * Sets the scheme/protocol. - * @param {string} newScheme New scheme value. - * @param {boolean=} opt_decode Optional param for whether to decode new value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setScheme = function(newScheme, opt_decode) { - this.enforceReadOnly(); - this.scheme_ = opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : - newScheme; - - // remove an : at the end of the scheme so somebody can pass in - // window.location.protocol - if (this.scheme_) { - this.scheme_ = this.scheme_.replace(/:$/, ''); - } - return this; -}; - - -/** - * @return {boolean} Whether the scheme has been set. - */ -goog.Uri.prototype.hasScheme = function() { - return !!this.scheme_; -}; - - -/** - * @return {string} The decoded user info. - */ -goog.Uri.prototype.getUserInfo = function() { - return this.userInfo_; -}; - - -/** - * Sets the userInfo. - * @param {string} newUserInfo New userInfo value. - * @param {boolean=} opt_decode Optional param for whether to decode new value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) { - this.enforceReadOnly(); - this.userInfo_ = opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : - newUserInfo; - return this; -}; - - -/** - * @return {boolean} Whether the user info has been set. - */ -goog.Uri.prototype.hasUserInfo = function() { - return !!this.userInfo_; -}; - - -/** - * @return {string} The decoded domain. - */ -goog.Uri.prototype.getDomain = function() { - return this.domain_; -}; - - -/** - * Sets the domain. - * @param {string} newDomain New domain value. - * @param {boolean=} opt_decode Optional param for whether to decode new value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setDomain = function(newDomain, opt_decode) { - this.enforceReadOnly(); - this.domain_ = opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : - newDomain; - return this; -}; - - -/** - * @return {boolean} Whether the domain has been set. - */ -goog.Uri.prototype.hasDomain = function() { - return !!this.domain_; -}; - - -/** - * @return {?number} The port number. - */ -goog.Uri.prototype.getPort = function() { - return this.port_; -}; - - -/** - * Sets the port number. - * @param {*} newPort Port number. Will be explicitly casted to a number. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setPort = function(newPort) { - this.enforceReadOnly(); - - if (newPort) { - newPort = Number(newPort); - if (isNaN(newPort) || newPort < 0) { - throw Error('Bad port number ' + newPort); - } - this.port_ = newPort; - } else { - this.port_ = null; - } - - return this; -}; - - -/** - * @return {boolean} Whether the port has been set. - */ -goog.Uri.prototype.hasPort = function() { - return this.port_ != null; -}; - - -/** - * @return {string} The decoded path. - */ -goog.Uri.prototype.getPath = function() { - return this.path_; -}; - - -/** - * Sets the path. - * @param {string} newPath New path value. - * @param {boolean=} opt_decode Optional param for whether to decode new value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setPath = function(newPath, opt_decode) { - this.enforceReadOnly(); - this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath; - return this; -}; - - -/** - * @return {boolean} Whether the path has been set. - */ -goog.Uri.prototype.hasPath = function() { - return !!this.path_; -}; - - -/** - * @return {boolean} Whether the query string has been set. - */ -goog.Uri.prototype.hasQuery = function() { - return this.queryData_.toString() !== ''; -}; - - -/** - * Sets the query data. - * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object. - * @param {boolean=} opt_decode Optional param for whether to decode new value. - * Applies only if queryData is a string. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setQueryData = function(queryData, opt_decode) { - this.enforceReadOnly(); - - if (queryData instanceof goog.Uri.QueryData) { - this.queryData_ = queryData; - this.queryData_.setIgnoreCase(this.ignoreCase_); - } else { - if (!opt_decode) { - // QueryData accepts encoded query string, so encode it if - // opt_decode flag is not true. - queryData = goog.Uri.encodeSpecialChars_(queryData, - goog.Uri.reDisallowedInQuery_); - } - this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_); - } - - return this; -}; - - -/** - * Sets the URI query. - * @param {string} newQuery New query value. - * @param {boolean=} opt_decode Optional param for whether to decode new value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setQuery = function(newQuery, opt_decode) { - return this.setQueryData(newQuery, opt_decode); -}; - - -/** - * @return {string} The encoded URI query, not including the ?. - */ -goog.Uri.prototype.getEncodedQuery = function() { - return this.queryData_.toString(); -}; - - -/** - * @return {string} The decoded URI query, not including the ?. - */ -goog.Uri.prototype.getDecodedQuery = function() { - return this.queryData_.toDecodedString(); -}; - - -/** - * Returns the query data. - * @return {!goog.Uri.QueryData} QueryData object. - */ -goog.Uri.prototype.getQueryData = function() { - return this.queryData_; -}; - - -/** - * @return {string} The encoded URI query, not including the ?. - * - * Warning: This method, unlike other getter methods, returns encoded - * value, instead of decoded one. - */ -goog.Uri.prototype.getQuery = function() { - return this.getEncodedQuery(); -}; - - -/** - * Sets the value of the named query parameters, clearing previous values for - * that key. - * - * @param {string} key The parameter to set. - * @param {*} value The new value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setParameterValue = function(key, value) { - this.enforceReadOnly(); - this.queryData_.set(key, value); - return this; -}; - - -/** - * Sets the values of the named query parameters, clearing previous values for - * that key. Not new values will currently be moved to the end of the query - * string. - * - * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new']) - * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p> - * - * @param {string} key The parameter to set. - * @param {*} values The new values. If values is a single - * string then it will be treated as the sole value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setParameterValues = function(key, values) { - this.enforceReadOnly(); - - if (!goog.isArray(values)) { - values = [String(values)]; - } - - this.queryData_.setValues(key, values); - - return this; -}; - - -/** - * Returns the value<b>s</b> for a given cgi parameter as a list of decoded - * query parameter values. - * @param {string} name The parameter to get values for. - * @return {!Array<?>} The values for a given cgi parameter as a list of - * decoded query parameter values. - */ -goog.Uri.prototype.getParameterValues = function(name) { - return this.queryData_.getValues(name); -}; - - -/** - * Returns the first value for a given cgi parameter or undefined if the given - * parameter name does not appear in the query string. - * @param {string} paramName Unescaped parameter name. - * @return {string|undefined} The first value for a given cgi parameter or - * undefined if the given parameter name does not appear in the query - * string. - */ -goog.Uri.prototype.getParameterValue = function(paramName) { - // NOTE(nicksantos): This type-cast is a lie when - // preserveParameterTypesCompatibilityFlag is set to true. - // But this should only be set to true in tests. - return /** @type {string|undefined} */ (this.queryData_.get(paramName)); -}; - - -/** - * @return {string} The URI fragment, not including the #. - */ -goog.Uri.prototype.getFragment = function() { - return this.fragment_; -}; - - -/** - * Sets the URI fragment. - * @param {string} newFragment New fragment value. - * @param {boolean=} opt_decode Optional param for whether to decode new value. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.setFragment = function(newFragment, opt_decode) { - this.enforceReadOnly(); - this.fragment_ = opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : - newFragment; - return this; -}; - - -/** - * @return {boolean} Whether the URI has a fragment set. - */ -goog.Uri.prototype.hasFragment = function() { - return !!this.fragment_; -}; - - -/** - * Returns true if this has the same domain as that of uri2. - * @param {!goog.Uri} uri2 The URI object to compare to. - * @return {boolean} true if same domain; false otherwise. - */ -goog.Uri.prototype.hasSameDomainAs = function(uri2) { - return ((!this.hasDomain() && !uri2.hasDomain()) || - this.getDomain() == uri2.getDomain()) && - ((!this.hasPort() && !uri2.hasPort()) || - this.getPort() == uri2.getPort()); -}; - - -/** - * Adds a random parameter to the Uri. - * @return {!goog.Uri} Reference to this Uri object. - */ -goog.Uri.prototype.makeUnique = function() { - this.enforceReadOnly(); - this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString()); - - return this; -}; - - -/** - * Removes the named query parameter. - * - * @param {string} key The parameter to remove. - * @return {!goog.Uri} Reference to this URI object. - */ -goog.Uri.prototype.removeParameter = function(key) { - this.enforceReadOnly(); - this.queryData_.remove(key); - return this; -}; - - -/** - * Sets whether Uri is read only. If this goog.Uri is read-only, - * enforceReadOnly_ will be called at the start of any function that may modify - * this Uri. - * @param {boolean} isReadOnly whether this goog.Uri should be read only. - * @return {!goog.Uri} Reference to this Uri object. - */ -goog.Uri.prototype.setReadOnly = function(isReadOnly) { - this.isReadOnly_ = isReadOnly; - return this; -}; - - -/** - * @return {boolean} Whether the URI is read only. - */ -goog.Uri.prototype.isReadOnly = function() { - return this.isReadOnly_; -}; - - -/** - * Checks if this Uri has been marked as read only, and if so, throws an error. - * This should be called whenever any modifying function is called. - */ -goog.Uri.prototype.enforceReadOnly = function() { - if (this.isReadOnly_) { - throw Error('Tried to modify a read-only Uri'); - } -}; - - -/** - * Sets whether to ignore case. - * NOTE: If there are already key/value pairs in the QueryData, and - * ignoreCase_ is set to false, the keys will all be lower-cased. - * @param {boolean} ignoreCase whether this goog.Uri should ignore case. - * @return {!goog.Uri} Reference to this Uri object. - */ -goog.Uri.prototype.setIgnoreCase = function(ignoreCase) { - this.ignoreCase_ = ignoreCase; - if (this.queryData_) { - this.queryData_.setIgnoreCase(ignoreCase); - } - return this; -}; - - -/** - * @return {boolean} Whether to ignore case. - */ -goog.Uri.prototype.getIgnoreCase = function() { - return this.ignoreCase_; -}; - - -//============================================================================== -// Static members -//============================================================================== - - -/** - * Creates a uri from the string form. Basically an alias of new goog.Uri(). - * If a Uri object is passed to parse then it will return a clone of the object. - * - * @param {*} uri Raw URI string or instance of Uri - * object. - * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter - * names in #getParameterValue. - * @return {!goog.Uri} The new URI object. - */ -goog.Uri.parse = function(uri, opt_ignoreCase) { - return uri instanceof goog.Uri ? - uri.clone() : new goog.Uri(uri, opt_ignoreCase); -}; - - -/** - * Creates a new goog.Uri object from unencoded parts. - * - * @param {?string=} opt_scheme Scheme/protocol or full URI to parse. - * @param {?string=} opt_userInfo username:password. - * @param {?string=} opt_domain www.google.com. - * @param {?number=} opt_port 9830. - * @param {?string=} opt_path /some/path/to/a/file.html. - * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2. - * @param {?string=} opt_fragment The fragment without the #. - * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in - * #getParameterValue. - * - * @return {!goog.Uri} The new URI object. - */ -goog.Uri.create = function(opt_scheme, opt_userInfo, opt_domain, opt_port, - opt_path, opt_query, opt_fragment, opt_ignoreCase) { - - var uri = new goog.Uri(null, opt_ignoreCase); - - // Only set the parts if they are defined and not empty strings. - opt_scheme && uri.setScheme(opt_scheme); - opt_userInfo && uri.setUserInfo(opt_userInfo); - opt_domain && uri.setDomain(opt_domain); - opt_port && uri.setPort(opt_port); - opt_path && uri.setPath(opt_path); - opt_query && uri.setQueryData(opt_query); - opt_fragment && uri.setFragment(opt_fragment); - - return uri; -}; - - -/** - * Resolves a relative Uri against a base Uri, accepting both strings and - * Uri objects. - * - * @param {*} base Base Uri. - * @param {*} rel Relative Uri. - * @return {!goog.Uri} Resolved uri. - */ -goog.Uri.resolve = function(base, rel) { - if (!(base instanceof goog.Uri)) { - base = goog.Uri.parse(base); - } - - if (!(rel instanceof goog.Uri)) { - rel = goog.Uri.parse(rel); - } - - return base.resolve(rel); -}; - - -/** - * Removes dot segments in given path component, as described in - * RFC 3986, section 5.2.4. - * - * @param {string} path A non-empty path component. - * @return {string} Path component with removed dot segments. - */ -goog.Uri.removeDotSegments = function(path) { - if (path == '..' || path == '.') { - return ''; - - } else if (!goog.string.contains(path, './') && - !goog.string.contains(path, '/.')) { - // This optimization detects uris which do not contain dot-segments, - // and as a consequence do not require any processing. - return path; - - } else { - var leadingSlash = goog.string.startsWith(path, '/'); - var segments = path.split('/'); - var out = []; - - for (var pos = 0; pos < segments.length; ) { - var segment = segments[pos++]; - - if (segment == '.') { - if (leadingSlash && pos == segments.length) { - out.push(''); - } - } else if (segment == '..') { - if (out.length > 1 || out.length == 1 && out[0] != '') { - out.pop(); - } - if (leadingSlash && pos == segments.length) { - out.push(''); - } - } else { - out.push(segment); - leadingSlash = true; - } - } - - return out.join('/'); - } -}; - - -/** - * Decodes a value or returns the empty string if it isn't defined or empty. - * @param {string|undefined} val Value to decode. - * @param {boolean=} opt_preserveReserved If true, restricted characters will - * not be decoded. - * @return {string} Decoded value. - * @private - */ -goog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) { - // Don't use UrlDecode() here because val is not a query parameter. - if (!val) { - return ''; - } - - return opt_preserveReserved ? decodeURI(val) : decodeURIComponent(val); -}; - - -/** - * If unescapedPart is non null, then escapes any characters in it that aren't - * valid characters in a url and also escapes any special characters that - * appear in extra. - * - * @param {*} unescapedPart The string to encode. - * @param {RegExp} extra A character set of characters in [\01-\177]. - * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent - * encoding. - * @return {?string} null iff unescapedPart == null. - * @private - */ -goog.Uri.encodeSpecialChars_ = function(unescapedPart, extra, - opt_removeDoubleEncoding) { - if (goog.isString(unescapedPart)) { - var encoded = encodeURI(unescapedPart). - replace(extra, goog.Uri.encodeChar_); - if (opt_removeDoubleEncoding) { - // encodeURI double-escapes %XX sequences used to represent restricted - // characters in some URI components, remove the double escaping here. - encoded = goog.Uri.removeDoubleEncoding_(encoded); - } - return encoded; - } - return null; -}; - - -/** - * Converts a character in [\01-\177] to its unicode character equivalent. - * @param {string} ch One character string. - * @return {string} Encoded string. - * @private - */ -goog.Uri.encodeChar_ = function(ch) { - var n = ch.charCodeAt(0); - return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16); -}; - - -/** - * Removes double percent-encoding from a string. - * @param {string} doubleEncodedString String - * @return {string} String with double encoding removed. - * @private - */ -goog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) { - return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1'); -}; - - -/** - * Regular expression for characters that are disallowed in the scheme or - * userInfo part of the URI. - * @type {RegExp} - * @private - */ -goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g; - - -/** - * Regular expression for characters that are disallowed in a relative path. - * Colon is included due to RFC 3986 3.3. - * @type {RegExp} - * @private - */ -goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g; - - -/** - * Regular expression for characters that are disallowed in an absolute path. - * @type {RegExp} - * @private - */ -goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g; - - -/** - * Regular expression for characters that are disallowed in the query. - * @type {RegExp} - * @private - */ -goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g; - - -/** - * Regular expression for characters that are disallowed in the fragment. - * @type {RegExp} - * @private - */ -goog.Uri.reDisallowedInFragment_ = /#/g; - - -/** - * Checks whether two URIs have the same domain. - * @param {string} uri1String First URI string. - * @param {string} uri2String Second URI string. - * @return {boolean} true if the two URIs have the same domain; false otherwise. - */ -goog.Uri.haveSameDomain = function(uri1String, uri2String) { - // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme. - // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain. - var pieces1 = goog.uri.utils.split(uri1String); - var pieces2 = goog.uri.utils.split(uri2String); - return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == - pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && - pieces1[goog.uri.utils.ComponentIndex.PORT] == - pieces2[goog.uri.utils.ComponentIndex.PORT]; -}; - - - -/** - * Class used to represent URI query parameters. It is essentially a hash of - * name-value pairs, though a name can be present more than once. - * - * Has the same interface as the collections in goog.structs. - * - * @param {?string=} opt_query Optional encoded query string to parse into - * the object. - * @param {goog.Uri=} opt_uri Optional uri object that should have its - * cache invalidated when this object updates. Deprecated -- this - * is no longer required. - * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter - * name in #get. - * @constructor - * @struct - * @final - */ -goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) { - /** - * Encoded query string, or null if it requires computing from the key map. - * @type {?string} - * @private - */ - this.encodedQuery_ = opt_query || null; - - /** - * If true, ignore the case of the parameter name in #get. - * @type {boolean} - * @private - */ - this.ignoreCase_ = !!opt_ignoreCase; -}; - - -/** - * If the underlying key map is not yet initialized, it parses the - * query string and fills the map with parsed data. - * @private - */ -goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() { - if (!this.keyMap_) { - this.keyMap_ = new goog.structs.Map(); - this.count_ = 0; - if (this.encodedQuery_) { - var self = this; - goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) { - self.add(goog.string.urlDecode(name), value); - }); - } - } -}; - - -/** - * Creates a new query data instance from a map of names and values. - * - * @param {!goog.structs.Map<string, ?>|!Object} map Map of string parameter - * names to parameter value. If parameter value is an array, it is - * treated as if the key maps to each individual value in the - * array. - * @param {goog.Uri=} opt_uri URI object that should have its cache - * invalidated when this object updates. - * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter - * name in #get. - * @return {!goog.Uri.QueryData} The populated query data instance. - */ -goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) { - var keys = goog.structs.getKeys(map); - if (typeof keys == 'undefined') { - throw Error('Keys are undefined'); - } - - var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); - var values = goog.structs.getValues(map); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = values[i]; - if (!goog.isArray(value)) { - queryData.add(key, value); - } else { - queryData.setValues(key, value); - } - } - return queryData; -}; - - -/** - * Creates a new query data instance from parallel arrays of parameter names - * and values. Allows for duplicate parameter names. Throws an error if the - * lengths of the arrays differ. - * - * @param {!Array<string>} keys Parameter names. - * @param {!Array<?>} values Parameter values. - * @param {goog.Uri=} opt_uri URI object that should have its cache - * invalidated when this object updates. - * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter - * name in #get. - * @return {!goog.Uri.QueryData} The populated query data instance. - */ -goog.Uri.QueryData.createFromKeysValues = function( - keys, values, opt_uri, opt_ignoreCase) { - if (keys.length != values.length) { - throw Error('Mismatched lengths for keys/values'); - } - var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); - for (var i = 0; i < keys.length; i++) { - queryData.add(keys[i], values[i]); - } - return queryData; -}; - - -/** - * The map containing name/value or name/array-of-values pairs. - * May be null if it requires parsing from the query string. - * - * We need to use a Map because we cannot guarantee that the key names will - * not be problematic for IE. - * - * @private {goog.structs.Map<string, !Array<*>>} - */ -goog.Uri.QueryData.prototype.keyMap_ = null; - - -/** - * The number of params, or null if it requires computing. - * @type {?number} - * @private - */ -goog.Uri.QueryData.prototype.count_ = null; - - -/** - * @return {?number} The number of parameters. - */ -goog.Uri.QueryData.prototype.getCount = function() { - this.ensureKeyMapInitialized_(); - return this.count_; -}; - - -/** - * Adds a key value pair. - * @param {string} key Name. - * @param {*} value Value. - * @return {!goog.Uri.QueryData} Instance of this object. - */ -goog.Uri.QueryData.prototype.add = function(key, value) { - this.ensureKeyMapInitialized_(); - this.invalidateCache_(); - - key = this.getKeyName_(key); - var values = this.keyMap_.get(key); - if (!values) { - this.keyMap_.set(key, (values = [])); - } - values.push(value); - this.count_++; - return this; -}; - - -/** - * Removes all the params with the given key. - * @param {string} key Name. - * @return {boolean} Whether any parameter was removed. - */ -goog.Uri.QueryData.prototype.remove = function(key) { - this.ensureKeyMapInitialized_(); - - key = this.getKeyName_(key); - if (this.keyMap_.containsKey(key)) { - this.invalidateCache_(); - - // Decrement parameter count. - this.count_ -= this.keyMap_.get(key).length; - return this.keyMap_.remove(key); - } - return false; -}; - - -/** - * Clears the parameters. - */ -goog.Uri.QueryData.prototype.clear = function() { - this.invalidateCache_(); - this.keyMap_ = null; - this.count_ = 0; -}; - - -/** - * @return {boolean} Whether we have any parameters. - */ -goog.Uri.QueryData.prototype.isEmpty = function() { - this.ensureKeyMapInitialized_(); - return this.count_ == 0; -}; - - -/** - * Whether there is a parameter with the given name - * @param {string} key The parameter name to check for. - * @return {boolean} Whether there is a parameter with the given name. - */ -goog.Uri.QueryData.prototype.containsKey = function(key) { - this.ensureKeyMapInitialized_(); - key = this.getKeyName_(key); - return this.keyMap_.containsKey(key); -}; - - -/** - * Whether there is a parameter with the given value. - * @param {*} value The value to check for. - * @return {boolean} Whether there is a parameter with the given value. - */ -goog.Uri.QueryData.prototype.containsValue = function(value) { - // NOTE(arv): This solution goes through all the params even if it was the - // first param. We can get around this by not reusing code or by switching to - // iterators. - var vals = this.getValues(); - return goog.array.contains(vals, value); -}; - - -/** - * Returns all the keys of the parameters. If a key is used multiple times - * it will be included multiple times in the returned array - * @return {!Array<string>} All the keys of the parameters. - */ -goog.Uri.QueryData.prototype.getKeys = function() { - this.ensureKeyMapInitialized_(); - // We need to get the values to know how many keys to add. - var vals = /** @type {!Array<*>} */ (this.keyMap_.getValues()); - var keys = this.keyMap_.getKeys(); - var rv = []; - for (var i = 0; i < keys.length; i++) { - var val = vals[i]; - for (var j = 0; j < val.length; j++) { - rv.push(keys[i]); - } - } - return rv; -}; - - -/** - * Returns all the values of the parameters with the given name. If the query - * data has no such key this will return an empty array. If no key is given - * all values wil be returned. - * @param {string=} opt_key The name of the parameter to get the values for. - * @return {!Array<?>} All the values of the parameters with the given name. - */ -goog.Uri.QueryData.prototype.getValues = function(opt_key) { - this.ensureKeyMapInitialized_(); - var rv = []; - if (goog.isString(opt_key)) { - if (this.containsKey(opt_key)) { - rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key))); - } - } else { - // Return all values. - var values = this.keyMap_.getValues(); - for (var i = 0; i < values.length; i++) { - rv = goog.array.concat(rv, values[i]); - } - } - return rv; -}; - - -/** - * Sets a key value pair and removes all other keys with the same value. - * - * @param {string} key Name. - * @param {*} value Value. - * @return {!goog.Uri.QueryData} Instance of this object. - */ -goog.Uri.QueryData.prototype.set = function(key, value) { - this.ensureKeyMapInitialized_(); - this.invalidateCache_(); - - // TODO(chrishenry): This could be better written as - // this.remove(key), this.add(key, value), but that would reorder - // the key (since the key is first removed and then added at the - // end) and we would have to fix unit tests that depend on key - // ordering. - key = this.getKeyName_(key); - if (this.containsKey(key)) { - this.count_ -= this.keyMap_.get(key).length; - } - this.keyMap_.set(key, [value]); - this.count_++; - return this; -}; - - -/** - * Returns the first value associated with the key. If the query data has no - * such key this will return undefined or the optional default. - * @param {string} key The name of the parameter to get the value for. - * @param {*=} opt_default The default value to return if the query data - * has no such key. - * @return {*} The first string value associated with the key, or opt_default - * if there's no value. - */ -goog.Uri.QueryData.prototype.get = function(key, opt_default) { - var values = key ? this.getValues(key) : []; - if (goog.Uri.preserveParameterTypesCompatibilityFlag) { - return values.length > 0 ? values[0] : opt_default; - } else { - return values.length > 0 ? String(values[0]) : opt_default; - } -}; - - -/** - * Sets the values for a key. If the key already exists, this will - * override all of the existing values that correspond to the key. - * @param {string} key The key to set values for. - * @param {!Array<?>} values The values to set. - */ -goog.Uri.QueryData.prototype.setValues = function(key, values) { - this.remove(key); - - if (values.length > 0) { - this.invalidateCache_(); - this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values)); - this.count_ += values.length; - } -}; - - -/** - * @return {string} Encoded query string. - * @override - */ -goog.Uri.QueryData.prototype.toString = function() { - if (this.encodedQuery_) { - return this.encodedQuery_; - } - - if (!this.keyMap_) { - return ''; - } - - var sb = []; - - // In the past, we use this.getKeys() and this.getVals(), but that - // generates a lot of allocations as compared to simply iterating - // over the keys. - var keys = this.keyMap_.getKeys(); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var encodedKey = goog.string.urlEncode(key); - var val = this.getValues(key); - for (var j = 0; j < val.length; j++) { - var param = encodedKey; - // Ensure that null and undefined are encoded into the url as - // literal strings. - if (val[j] !== '') { - param += '=' + goog.string.urlEncode(val[j]); - } - sb.push(param); - } - } - - return this.encodedQuery_ = sb.join('&'); -}; - - -/** - * @return {string} Decoded query string. - */ -goog.Uri.QueryData.prototype.toDecodedString = function() { - return goog.Uri.decodeOrEmpty_(this.toString()); -}; - - -/** - * Invalidate the cache. - * @private - */ -goog.Uri.QueryData.prototype.invalidateCache_ = function() { - this.encodedQuery_ = null; -}; - - -/** - * Removes all keys that are not in the provided list. (Modifies this object.) - * @param {Array<string>} keys The desired keys. - * @return {!goog.Uri.QueryData} a reference to this object. - */ -goog.Uri.QueryData.prototype.filterKeys = function(keys) { - this.ensureKeyMapInitialized_(); - this.keyMap_.forEach( - function(value, key) { - if (!goog.array.contains(keys, key)) { - this.remove(key); - } - }, this); - return this; -}; - - -/** - * Clone the query data instance. - * @return {!goog.Uri.QueryData} New instance of the QueryData object. - */ -goog.Uri.QueryData.prototype.clone = function() { - var rv = new goog.Uri.QueryData(); - rv.encodedQuery_ = this.encodedQuery_; - if (this.keyMap_) { - rv.keyMap_ = this.keyMap_.clone(); - rv.count_ = this.count_; - } - return rv; -}; - - -/** - * Helper function to get the key name from a JavaScript object. Converts - * the object to a string, and to lower case if necessary. - * @private - * @param {*} arg The object to get a key name from. - * @return {string} valid key name which can be looked up in #keyMap_. - */ -goog.Uri.QueryData.prototype.getKeyName_ = function(arg) { - var keyName = String(arg); - if (this.ignoreCase_) { - keyName = keyName.toLowerCase(); - } - return keyName; -}; - - -/** - * Ignore case in parameter names. - * NOTE: If there are already key/value pairs in the QueryData, and - * ignoreCase_ is set to false, the keys will all be lower-cased. - * @param {boolean} ignoreCase whether this goog.Uri should ignore case. - */ -goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) { - var resetKeys = ignoreCase && !this.ignoreCase_; - if (resetKeys) { - this.ensureKeyMapInitialized_(); - this.invalidateCache_(); - this.keyMap_.forEach( - function(value, key) { - var lowerCase = key.toLowerCase(); - if (key != lowerCase) { - this.remove(key); - this.setValues(lowerCase, value); - } - }, this); - } - this.ignoreCase_ = ignoreCase; -}; - - -/** - * Extends a query data object with another query data or map like object. This - * operates 'in-place', it does not create a new QueryData object. - * - * @param {...(goog.Uri.QueryData|goog.structs.Map<?, ?>|Object)} var_args - * The object from which key value pairs will be copied. - */ -goog.Uri.QueryData.prototype.extend = function(var_args) { - for (var i = 0; i < arguments.length; i++) { - var data = arguments[i]; - goog.structs.forEach(data, - /** @this {goog.Uri.QueryData} */ - function(value, key) { - this.add(key, value); - }, this); - } -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/uri/utils.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/uri/utils.js deleted file mode 100644 index 28a6ee3..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/uri/utils.js +++ /dev/null @@ -1,1116 +0,0 @@ -// 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 Simple utilities for dealing with URI strings. - * - * This is intended to be a lightweight alternative to constructing goog.Uri - * objects. Whereas goog.Uri adds several kilobytes to the binary regardless - * of how much of its functionality you use, this is designed to be a set of - * mostly-independent utilities so that the compiler includes only what is - * necessary for the task. Estimated savings of porting is 5k pre-gzip and - * 1.5k post-gzip. To ensure the savings remain, future developers should - * avoid adding new functionality to existing functions, but instead create - * new ones and factor out shared code. - * - * Many of these utilities have limited functionality, tailored to common - * cases. The query parameter utilities assume that the parameter keys are - * already encoded, since most keys are compile-time alphanumeric strings. The - * query parameter mutation utilities also do not tolerate fragment identifiers. - * - * By design, these functions can be slower than goog.Uri equivalents. - * Repeated calls to some of functions may be quadratic in behavior for IE, - * although the effect is somewhat limited given the 2kb limit. - * - * One advantage of the limited functionality here is that this approach is - * less sensitive to differences in URI encodings than goog.Uri, since these - * functions operate on strings directly, rather than decoding them and - * then re-encoding. - * - * Uses features of RFC 3986 for parsing/formatting URIs: - * http://www.ietf.org/rfc/rfc3986.txt - * - * @author gboyer@google.com (Garrett Boyer) - The "lightened" design. - */ - -goog.provide('goog.uri.utils'); -goog.provide('goog.uri.utils.ComponentIndex'); -goog.provide('goog.uri.utils.QueryArray'); -goog.provide('goog.uri.utils.QueryValue'); -goog.provide('goog.uri.utils.StandardQueryParam'); - -goog.require('goog.asserts'); -goog.require('goog.string'); -goog.require('goog.userAgent'); - - -/** - * Character codes inlined to avoid object allocations due to charCode. - * @enum {number} - * @private - */ -goog.uri.utils.CharCode_ = { - AMPERSAND: 38, - EQUAL: 61, - HASH: 35, - QUESTION: 63 -}; - - -/** - * Builds a URI string from already-encoded parts. - * - * No encoding is performed. Any component may be omitted as either null or - * undefined. - * - * @param {?string=} opt_scheme The scheme such as 'http'. - * @param {?string=} opt_userInfo The user name before the '@'. - * @param {?string=} opt_domain The domain such as 'www.google.com', already - * URI-encoded. - * @param {(string|number|null)=} opt_port The port number. - * @param {?string=} opt_path The path, already URI-encoded. If it is not - * empty, it must begin with a slash. - * @param {?string=} opt_queryData The URI-encoded query data. - * @param {?string=} opt_fragment The URI-encoded fragment identifier. - * @return {string} The fully combined URI. - */ -goog.uri.utils.buildFromEncodedParts = function(opt_scheme, opt_userInfo, - opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { - var out = ''; - - if (opt_scheme) { - out += opt_scheme + ':'; - } - - if (opt_domain) { - out += '//'; - - if (opt_userInfo) { - out += opt_userInfo + '@'; - } - - out += opt_domain; - - if (opt_port) { - out += ':' + opt_port; - } - } - - if (opt_path) { - out += opt_path; - } - - if (opt_queryData) { - out += '?' + opt_queryData; - } - - if (opt_fragment) { - out += '#' + opt_fragment; - } - - return out; -}; - - -/** - * A regular expression for breaking a URI into its component parts. - * - * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B - * As the "first-match-wins" algorithm is identical to the "greedy" - * disambiguation method used by POSIX regular expressions, it is natural and - * commonplace to use a regular expression for parsing the potential five - * components of a URI reference. - * - * The following line is the regular expression for breaking-down a - * well-formed URI reference into its components. - * - * <pre> - * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - * 12 3 4 5 6 7 8 9 - * </pre> - * - * The numbers in the second line above are only to assist readability; they - * indicate the reference points for each subexpression (i.e., each paired - * parenthesis). We refer to the value matched for subexpression <n> as $<n>. - * For example, matching the above expression to - * <pre> - * http://www.ics.uci.edu/pub/ietf/uri/#Related - * </pre> - * results in the following subexpression matches: - * <pre> - * $1 = http: - * $2 = http - * $3 = //www.ics.uci.edu - * $4 = www.ics.uci.edu - * $5 = /pub/ietf/uri/ - * $6 = <undefined> - * $7 = <undefined> - * $8 = #Related - * $9 = Related - * </pre> - * where <undefined> indicates that the component is not present, as is the - * case for the query component in the above example. Therefore, we can - * determine the value of the five components as - * <pre> - * scheme = $2 - * authority = $4 - * path = $5 - * query = $7 - * fragment = $9 - * </pre> - * - * The regular expression has been modified slightly to expose the - * userInfo, domain, and port separately from the authority. - * The modified version yields - * <pre> - * $1 = http scheme - * $2 = <undefined> userInfo -\ - * $3 = www.ics.uci.edu domain | authority - * $4 = <undefined> port -/ - * $5 = /pub/ietf/uri/ path - * $6 = <undefined> query without ? - * $7 = Related fragment without # - * </pre> - * @type {!RegExp} - * @private - */ -goog.uri.utils.splitRe_ = new RegExp( - '^' + - '(?:' + - '([^:/?#.]+)' + // scheme - ignore special characters - // used by other URL parts such as :, - // ?, /, #, and . - ':)?' + - '(?://' + - '(?:([^/?#]*)@)?' + // userInfo - '([^/#?]*?)' + // domain - '(?::([0-9]+))?' + // port - '(?=[/#?]|$)' + // authority-terminating character - ')?' + - '([^?#]+)?' + // path - '(?:\\?([^#]*))?' + // query - '(?:#(.*))?' + // fragment - '$'); - - -/** - * The index of each URI component in the return value of goog.uri.utils.split. - * @enum {number} - */ -goog.uri.utils.ComponentIndex = { - SCHEME: 1, - USER_INFO: 2, - DOMAIN: 3, - PORT: 4, - PATH: 5, - QUERY_DATA: 6, - FRAGMENT: 7 -}; - - -/** - * Splits a URI into its component parts. - * - * Each component can be accessed via the component indices; for example: - * <pre> - * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA]; - * </pre> - * - * @param {string} uri The URI string to examine. - * @return {!Array<string|undefined>} Each component still URI-encoded. - * Each component that is present will contain the encoded value, whereas - * components that are not present will be undefined or empty, depending - * on the browser's regular expression implementation. Never null, since - * arbitrary strings may still look like path names. - */ -goog.uri.utils.split = function(uri) { - goog.uri.utils.phishingProtection_(); - - // See @return comment -- never null. - return /** @type {!Array<string|undefined>} */ ( - uri.match(goog.uri.utils.splitRe_)); -}; - - -/** - * Safari has a nasty bug where if you have an http URL with a username, e.g., - * http://evil.com%2F@google.com/ - * Safari will report that window.location.href is - * http://evil.com/google.com/ - * so that anyone who tries to parse the domain of that URL will get - * the wrong domain. We've seen exploits where people use this to trick - * Safari into loading resources from evil domains. - * - * To work around this, we run a little "Safari phishing check", and throw - * an exception if we see this happening. - * - * There is no convenient place to put this check. We apply it to - * anyone doing URI parsing on Webkit. We're not happy about this, but - * it fixes the problem. - * - * This should be removed once Safari fixes their bug. - * - * Exploit reported by Masato Kinugawa. - * - * @type {boolean} - * @private - */ -goog.uri.utils.needsPhishingProtection_ = goog.userAgent.WEBKIT; - - -/** - * Check to see if the user is being phished. - * @private - */ -goog.uri.utils.phishingProtection_ = function() { - if (goog.uri.utils.needsPhishingProtection_) { - // Turn protection off, so that we don't recurse. - goog.uri.utils.needsPhishingProtection_ = false; - - // Use quoted access, just in case the user isn't using location externs. - var location = goog.global['location']; - if (location) { - var href = location['href']; - if (href) { - var domain = goog.uri.utils.getDomain(href); - if (domain && domain != location['hostname']) { - // Phishing attack - goog.uri.utils.needsPhishingProtection_ = true; - throw Error(); - } - } - } - } -}; - - -/** - * @param {?string} uri A possibly null string. - * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986 - * reserved characters will not be removed. - * @return {?string} The string URI-decoded, or null if uri is null. - * @private - */ -goog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) { - if (!uri) { - return uri; - } - - return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri); -}; - - -/** - * Gets a URI component by index. - * - * It is preferred to use the getPathEncoded() variety of functions ahead, - * since they are more readable. - * - * @param {goog.uri.utils.ComponentIndex} componentIndex The component index. - * @param {string} uri The URI to examine. - * @return {?string} The still-encoded component, or null if the component - * is not present. - * @private - */ -goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) { - // Convert undefined, null, and empty string into null. - return goog.uri.utils.split(uri)[componentIndex] || null; -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The protocol or scheme, or null if none. Does not - * include trailing colons or slashes. - */ -goog.uri.utils.getScheme = function(uri) { - return goog.uri.utils.getComponentByIndex_( - goog.uri.utils.ComponentIndex.SCHEME, uri); -}; - - -/** - * Gets the effective scheme for the URL. If the URL is relative then the - * scheme is derived from the page's location. - * @param {string} uri The URI to examine. - * @return {string} The protocol or scheme, always lower case. - */ -goog.uri.utils.getEffectiveScheme = function(uri) { - var scheme = goog.uri.utils.getScheme(uri); - if (!scheme && self.location) { - var protocol = self.location.protocol; - scheme = protocol.substr(0, protocol.length - 1); - } - // NOTE: When called from a web worker in Firefox 3.5, location maybe null. - // All other browsers with web workers support self.location from the worker. - return scheme ? scheme.toLowerCase() : ''; -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The user name still encoded, or null if none. - */ -goog.uri.utils.getUserInfoEncoded = function(uri) { - return goog.uri.utils.getComponentByIndex_( - goog.uri.utils.ComponentIndex.USER_INFO, uri); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The decoded user info, or null if none. - */ -goog.uri.utils.getUserInfo = function(uri) { - return goog.uri.utils.decodeIfPossible_( - goog.uri.utils.getUserInfoEncoded(uri)); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The domain name still encoded, or null if none. - */ -goog.uri.utils.getDomainEncoded = function(uri) { - return goog.uri.utils.getComponentByIndex_( - goog.uri.utils.ComponentIndex.DOMAIN, uri); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The decoded domain, or null if none. - */ -goog.uri.utils.getDomain = function(uri) { - return goog.uri.utils.decodeIfPossible_( - goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?number} The port number, or null if none. - */ -goog.uri.utils.getPort = function(uri) { - // Coerce to a number. If the result of getComponentByIndex_ is null or - // non-numeric, the number coersion yields NaN. This will then return - // null for all non-numeric cases (though also zero, which isn't a relevant - // port number). - return Number(goog.uri.utils.getComponentByIndex_( - goog.uri.utils.ComponentIndex.PORT, uri)) || null; -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The path still encoded, or null if none. Includes the - * leading slash, if any. - */ -goog.uri.utils.getPathEncoded = function(uri) { - return goog.uri.utils.getComponentByIndex_( - goog.uri.utils.ComponentIndex.PATH, uri); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The decoded path, or null if none. Includes the leading - * slash, if any. - */ -goog.uri.utils.getPath = function(uri) { - return goog.uri.utils.decodeIfPossible_( - goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The query data still encoded, or null if none. Does not - * include the question mark itself. - */ -goog.uri.utils.getQueryData = function(uri) { - return goog.uri.utils.getComponentByIndex_( - goog.uri.utils.ComponentIndex.QUERY_DATA, uri); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The fragment identifier, or null if none. Does not - * include the hash mark itself. - */ -goog.uri.utils.getFragmentEncoded = function(uri) { - // The hash mark may not appear in any other part of the URL. - var hashIndex = uri.indexOf('#'); - return hashIndex < 0 ? null : uri.substr(hashIndex + 1); -}; - - -/** - * @param {string} uri The URI to examine. - * @param {?string} fragment The encoded fragment identifier, or null if none. - * Does not include the hash mark itself. - * @return {string} The URI with the fragment set. - */ -goog.uri.utils.setFragmentEncoded = function(uri, fragment) { - return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : ''); -}; - - -/** - * @param {string} uri The URI to examine. - * @return {?string} The decoded fragment identifier, or null if none. Does - * not include the hash mark. - */ -goog.uri.utils.getFragment = function(uri) { - return goog.uri.utils.decodeIfPossible_( - goog.uri.utils.getFragmentEncoded(uri)); -}; - - -/** - * Extracts everything up to the port of the URI. - * @param {string} uri The URI string. - * @return {string} Everything up to and including the port. - */ -goog.uri.utils.getHost = function(uri) { - var pieces = goog.uri.utils.split(uri); - return goog.uri.utils.buildFromEncodedParts( - pieces[goog.uri.utils.ComponentIndex.SCHEME], - pieces[goog.uri.utils.ComponentIndex.USER_INFO], - pieces[goog.uri.utils.ComponentIndex.DOMAIN], - pieces[goog.uri.utils.ComponentIndex.PORT]); -}; - - -/** - * Extracts the path of the URL and everything after. - * @param {string} uri The URI string. - * @return {string} The URI, starting at the path and including the query - * parameters and fragment identifier. - */ -goog.uri.utils.getPathAndAfter = function(uri) { - var pieces = goog.uri.utils.split(uri); - return goog.uri.utils.buildFromEncodedParts(null, null, null, null, - pieces[goog.uri.utils.ComponentIndex.PATH], - pieces[goog.uri.utils.ComponentIndex.QUERY_DATA], - pieces[goog.uri.utils.ComponentIndex.FRAGMENT]); -}; - - -/** - * Gets the URI with the fragment identifier removed. - * @param {string} uri The URI to examine. - * @return {string} Everything preceding the hash mark. - */ -goog.uri.utils.removeFragment = function(uri) { - // The hash mark may not appear in any other part of the URL. - var hashIndex = uri.indexOf('#'); - return hashIndex < 0 ? uri : uri.substr(0, hashIndex); -}; - - -/** - * Ensures that two URI's have the exact same domain, scheme, and port. - * - * Unlike the version in goog.Uri, this checks protocol, and therefore is - * suitable for checking against the browser's same-origin policy. - * - * @param {string} uri1 The first URI. - * @param {string} uri2 The second URI. - * @return {boolean} Whether they have the same scheme, domain and port. - */ -goog.uri.utils.haveSameDomain = function(uri1, uri2) { - var pieces1 = goog.uri.utils.split(uri1); - var pieces2 = goog.uri.utils.split(uri2); - return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == - pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && - pieces1[goog.uri.utils.ComponentIndex.SCHEME] == - pieces2[goog.uri.utils.ComponentIndex.SCHEME] && - pieces1[goog.uri.utils.ComponentIndex.PORT] == - pieces2[goog.uri.utils.ComponentIndex.PORT]; -}; - - -/** - * Asserts that there are no fragment or query identifiers, only in uncompiled - * mode. - * @param {string} uri The URI to examine. - * @private - */ -goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) { - // NOTE: would use goog.asserts here, but jscompiler doesn't know that - // indexOf has no side effects. - if (goog.DEBUG && (uri.indexOf('#') >= 0 || uri.indexOf('?') >= 0)) { - throw Error('goog.uri.utils: Fragment or query identifiers are not ' + - 'supported: [' + uri + ']'); - } -}; - - -/** - * Supported query parameter values by the parameter serializing utilities. - * - * If a value is null or undefined, the key-value pair is skipped, as an easy - * way to omit parameters conditionally. Non-array parameters are converted - * to a string and URI encoded. Array values are expanded into multiple - * &key=value pairs, with each element stringized and URI-encoded. - * - * @typedef {*} - */ -goog.uri.utils.QueryValue; - - -/** - * An array representing a set of query parameters with alternating keys - * and values. - * - * Keys are assumed to be URI encoded already and live at even indices. See - * goog.uri.utils.QueryValue for details on how parameter values are encoded. - * - * Example: - * <pre> - * var data = [ - * // Simple param: ?name=BobBarker - * 'name', 'BobBarker', - * // Conditional param -- may be omitted entirely. - * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null, - * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null - * 'house', ['LosAngeles', 'NewYork', null] - * ]; - * </pre> - * - * @typedef {!Array<string|goog.uri.utils.QueryValue>} - */ -goog.uri.utils.QueryArray; - - -/** - * Parses encoded query parameters and calls callback function for every - * parameter found in the string. - * - * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an - * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means - * that “…&=&…” and “…&&…” will result in an empty key and value. - * - * @param {string} encodedQuery Encoded query string excluding question mark at - * the beginning. - * @param {function(string, string)} callback Function called for every - * parameter found in query string. The first argument (name) will not be - * urldecoded (so the function is consistent with buildQueryData), but the - * second will. If the parameter has no value (i.e. “=” was not present) - * the second argument (value) will be an empty string. - */ -goog.uri.utils.parseQueryData = function(encodedQuery, callback) { - var pairs = encodedQuery.split('&'); - for (var i = 0; i < pairs.length; i++) { - var indexOfEquals = pairs[i].indexOf('='); - var name = null; - var value = null; - if (indexOfEquals >= 0) { - name = pairs[i].substring(0, indexOfEquals); - value = pairs[i].substring(indexOfEquals + 1); - } else { - name = pairs[i]; - } - callback(name, value ? goog.string.urlDecode(value) : ''); - } -}; - - -/** - * Appends a URI and query data in a string buffer with special preconditions. - * - * Internal implementation utility, performing very few object allocations. - * - * @param {!Array<string|undefined>} buffer A string buffer. The first element - * must be the base URI, and may have a fragment identifier. If the array - * contains more than one element, the second element must be an ampersand, - * and may be overwritten, depending on the base URI. Undefined elements - * are treated as empty-string. - * @return {string} The concatenated URI and query data. - * @private - */ -goog.uri.utils.appendQueryData_ = function(buffer) { - if (buffer[1]) { - // At least one query parameter was added. We need to check the - // punctuation mark, which is currently an ampersand, and also make sure - // there aren't any interfering fragment identifiers. - var baseUri = /** @type {string} */ (buffer[0]); - var hashIndex = baseUri.indexOf('#'); - if (hashIndex >= 0) { - // Move the fragment off the base part of the URI into the end. - buffer.push(baseUri.substr(hashIndex)); - buffer[0] = baseUri = baseUri.substr(0, hashIndex); - } - var questionIndex = baseUri.indexOf('?'); - if (questionIndex < 0) { - // No question mark, so we need a question mark instead of an ampersand. - buffer[1] = '?'; - } else if (questionIndex == baseUri.length - 1) { - // Question mark is the very last character of the existing URI, so don't - // append an additional delimiter. - buffer[1] = undefined; - } - } - - return buffer.join(''); -}; - - -/** - * Appends key=value pairs to an array, supporting multi-valued objects. - * @param {string} key The key prefix. - * @param {goog.uri.utils.QueryValue} value The value to serialize. - * @param {!Array<string>} pairs The array to which the 'key=value' strings - * should be appended. - * @private - */ -goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) { - if (goog.isArray(value)) { - // Convince the compiler it's an array. - goog.asserts.assertArray(value); - for (var j = 0; j < value.length; j++) { - // Convert to string explicitly, to short circuit the null and array - // logic in this function -- this ensures that null and undefined get - // written as literal 'null' and 'undefined', and arrays don't get - // expanded out but instead encoded in the default way. - goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs); - } - } else if (value != null) { - // Skip a top-level null or undefined entirely. - pairs.push('&', key, - // Check for empty string. Zero gets encoded into the url as literal - // strings. For empty string, skip the equal sign, to be consistent - // with UriBuilder.java. - value === '' ? '' : '=', - goog.string.urlEncode(value)); - } -}; - - -/** - * Builds a buffer of query data from a sequence of alternating keys and values. - * - * @param {!Array<string|undefined>} buffer A string buffer to append to. The - * first element appended will be an '&', and may be replaced by the caller. - * @param {!goog.uri.utils.QueryArray|!Arguments} keysAndValues An array with - * alternating keys and values -- see the typedef. - * @param {number=} opt_startIndex A start offset into the arary, defaults to 0. - * @return {!Array<string|undefined>} The buffer argument. - * @private - */ -goog.uri.utils.buildQueryDataBuffer_ = function( - buffer, keysAndValues, opt_startIndex) { - goog.asserts.assert(Math.max(keysAndValues.length - (opt_startIndex || 0), - 0) % 2 == 0, 'goog.uri.utils: Key/value lists must be even in length.'); - - for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) { - goog.uri.utils.appendKeyValuePairs_( - keysAndValues[i], keysAndValues[i + 1], buffer); - } - - return buffer; -}; - - -/** - * Builds a query data string from a sequence of alternating keys and values. - * Currently generates "&key&" for empty args. - * - * @param {goog.uri.utils.QueryArray} keysAndValues Alternating keys and - * values. See the typedef. - * @param {number=} opt_startIndex A start offset into the arary, defaults to 0. - * @return {string} The encoded query string, in the form 'a=1&b=2'. - */ -goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) { - var buffer = goog.uri.utils.buildQueryDataBuffer_( - [], keysAndValues, opt_startIndex); - buffer[0] = ''; // Remove the leading ampersand. - return buffer.join(''); -}; - - -/** - * Builds a buffer of query data from a map. - * - * @param {!Array<string|undefined>} buffer A string buffer to append to. The - * first element appended will be an '&', and may be replaced by the caller. - * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys - * are URI-encoded parameter keys, and the values conform to the contract - * specified in the goog.uri.utils.QueryValue typedef. - * @return {!Array<string|undefined>} The buffer argument. - * @private - */ -goog.uri.utils.buildQueryDataBufferFromMap_ = function(buffer, map) { - for (var key in map) { - goog.uri.utils.appendKeyValuePairs_(key, map[key], buffer); - } - - return buffer; -}; - - -/** - * Builds a query data string from a map. - * Currently generates "&key&" for empty args. - * - * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys - * are URI-encoded parameter keys, and the values are arbitrary types - * or arrays. Keys with a null value are dropped. - * @return {string} The encoded query string, in the form 'a=1&b=2'. - */ -goog.uri.utils.buildQueryDataFromMap = function(map) { - var buffer = goog.uri.utils.buildQueryDataBufferFromMap_([], map); - buffer[0] = ''; - return buffer.join(''); -}; - - -/** - * Appends URI parameters to an existing URI. - * - * The variable arguments may contain alternating keys and values. Keys are - * assumed to be already URI encoded. The values should not be URI-encoded, - * and will instead be encoded by this function. - * <pre> - * appendParams('http://www.foo.com?existing=true', - * 'key1', 'value1', - * 'key2', 'value?willBeEncoded', - * 'key3', ['valueA', 'valueB', 'valueC'], - * 'key4', null); - * result: 'http://www.foo.com?existing=true&' + - * 'key1=value1&' + - * 'key2=value%3FwillBeEncoded&' + - * 'key3=valueA&key3=valueB&key3=valueC' - * </pre> - * - * A single call to this function will not exhibit quadratic behavior in IE, - * whereas multiple repeated calls may, although the effect is limited by - * fact that URL's generally can't exceed 2kb. - * - * @param {string} uri The original URI, which may already have query data. - * @param {...(goog.uri.utils.QueryArray|string|goog.uri.utils.QueryValue)} var_args - * An array or argument list conforming to goog.uri.utils.QueryArray. - * @return {string} The URI with all query parameters added. - */ -goog.uri.utils.appendParams = function(uri, var_args) { - return goog.uri.utils.appendQueryData_( - arguments.length == 2 ? - goog.uri.utils.buildQueryDataBuffer_([uri], arguments[1], 0) : - goog.uri.utils.buildQueryDataBuffer_([uri], arguments, 1)); -}; - - -/** - * Appends query parameters from a map. - * - * @param {string} uri The original URI, which may already have query data. - * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are - * URI-encoded parameter keys, and the values are arbitrary types or arrays. - * Keys with a null value are dropped. - * @return {string} The new parameters. - */ -goog.uri.utils.appendParamsFromMap = function(uri, map) { - return goog.uri.utils.appendQueryData_( - goog.uri.utils.buildQueryDataBufferFromMap_([uri], map)); -}; - - -/** - * Appends a single URI parameter. - * - * Repeated calls to this can exhibit quadratic behavior in IE6 due to the - * way string append works, though it should be limited given the 2kb limit. - * - * @param {string} uri The original URI, which may already have query data. - * @param {string} key The key, which must already be URI encoded. - * @param {*=} opt_value The value, which will be stringized and encoded - * (assumed not already to be encoded). If omitted, undefined, or null, the - * key will be added as a valueless parameter. - * @return {string} The URI with the query parameter added. - */ -goog.uri.utils.appendParam = function(uri, key, opt_value) { - var paramArr = [uri, '&', key]; - if (goog.isDefAndNotNull(opt_value)) { - paramArr.push('=', goog.string.urlEncode(opt_value)); - } - return goog.uri.utils.appendQueryData_(paramArr); -}; - - -/** - * Finds the next instance of a query parameter with the specified name. - * - * Does not instantiate any objects. - * - * @param {string} uri The URI to search. May contain a fragment identifier - * if opt_hashIndex is specified. - * @param {number} startIndex The index to begin searching for the key at. A - * match may be found even if this is one character after the ampersand. - * @param {string} keyEncoded The URI-encoded key. - * @param {number} hashOrEndIndex Index to stop looking at. If a hash - * mark is present, it should be its index, otherwise it should be the - * length of the string. - * @return {number} The position of the first character in the key's name, - * immediately after either a question mark or a dot. - * @private - */ -goog.uri.utils.findParam_ = function( - uri, startIndex, keyEncoded, hashOrEndIndex) { - var index = startIndex; - var keyLength = keyEncoded.length; - - // Search for the key itself and post-filter for surronuding punctuation, - // rather than expensively building a regexp. - while ((index = uri.indexOf(keyEncoded, index)) >= 0 && - index < hashOrEndIndex) { - var precedingChar = uri.charCodeAt(index - 1); - // Ensure that the preceding character is '&' or '?'. - if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND || - precedingChar == goog.uri.utils.CharCode_.QUESTION) { - // Ensure the following character is '&', '=', '#', or NaN - // (end of string). - var followingChar = uri.charCodeAt(index + keyLength); - if (!followingChar || - followingChar == goog.uri.utils.CharCode_.EQUAL || - followingChar == goog.uri.utils.CharCode_.AMPERSAND || - followingChar == goog.uri.utils.CharCode_.HASH) { - return index; - } - } - index += keyLength + 1; - } - - return -1; -}; - - -/** - * Regular expression for finding a hash mark or end of string. - * @type {RegExp} - * @private - */ -goog.uri.utils.hashOrEndRe_ = /#|$/; - - -/** - * Determines if the URI contains a specific key. - * - * Performs no object instantiations. - * - * @param {string} uri The URI to process. May contain a fragment - * identifier. - * @param {string} keyEncoded The URI-encoded key. Case-sensitive. - * @return {boolean} Whether the key is present. - */ -goog.uri.utils.hasParam = function(uri, keyEncoded) { - return goog.uri.utils.findParam_(uri, 0, keyEncoded, - uri.search(goog.uri.utils.hashOrEndRe_)) >= 0; -}; - - -/** - * Gets the first value of a query parameter. - * @param {string} uri The URI to process. May contain a fragment. - * @param {string} keyEncoded The URI-encoded key. Case-sensitive. - * @return {?string} The first value of the parameter (URI-decoded), or null - * if the parameter is not found. - */ -goog.uri.utils.getParamValue = function(uri, keyEncoded) { - var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); - var foundIndex = goog.uri.utils.findParam_( - uri, 0, keyEncoded, hashOrEndIndex); - - if (foundIndex < 0) { - return null; - } else { - var endPosition = uri.indexOf('&', foundIndex); - if (endPosition < 0 || endPosition > hashOrEndIndex) { - endPosition = hashOrEndIndex; - } - // Progress forth to the end of the "key=" or "key&" substring. - foundIndex += keyEncoded.length + 1; - // Use substr, because it (unlike substring) will return empty string - // if foundIndex > endPosition. - return goog.string.urlDecode( - uri.substr(foundIndex, endPosition - foundIndex)); - } -}; - - -/** - * Gets all values of a query parameter. - * @param {string} uri The URI to process. May contain a framgnet. - * @param {string} keyEncoded The URI-encoded key. Case-snsitive. - * @return {!Array<string>} All URI-decoded values with the given key. - * If the key is not found, this will have length 0, but never be null. - */ -goog.uri.utils.getParamValues = function(uri, keyEncoded) { - var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); - var position = 0; - var foundIndex; - var result = []; - - while ((foundIndex = goog.uri.utils.findParam_( - uri, position, keyEncoded, hashOrEndIndex)) >= 0) { - // Find where this parameter ends, either the '&' or the end of the - // query parameters. - position = uri.indexOf('&', foundIndex); - if (position < 0 || position > hashOrEndIndex) { - position = hashOrEndIndex; - } - - // Progress forth to the end of the "key=" or "key&" substring. - foundIndex += keyEncoded.length + 1; - // Use substr, because it (unlike substring) will return empty string - // if foundIndex > position. - result.push(goog.string.urlDecode(uri.substr( - foundIndex, position - foundIndex))); - } - - return result; -}; - - -/** - * Regexp to find trailing question marks and ampersands. - * @type {RegExp} - * @private - */ -goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/; - - -/** - * Removes all instances of a query parameter. - * @param {string} uri The URI to process. Must not contain a fragment. - * @param {string} keyEncoded The URI-encoded key. - * @return {string} The URI with all instances of the parameter removed. - */ -goog.uri.utils.removeParam = function(uri, keyEncoded) { - var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); - var position = 0; - var foundIndex; - var buffer = []; - - // Look for a query parameter. - while ((foundIndex = goog.uri.utils.findParam_( - uri, position, keyEncoded, hashOrEndIndex)) >= 0) { - // Get the portion of the query string up to, but not including, the ? - // or & starting the parameter. - buffer.push(uri.substring(position, foundIndex)); - // Progress to immediately after the '&'. If not found, go to the end. - // Avoid including the hash mark. - position = Math.min((uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, - hashOrEndIndex); - } - - // Append everything that is remaining. - buffer.push(uri.substr(position)); - - // Join the buffer, and remove trailing punctuation that remains. - return buffer.join('').replace( - goog.uri.utils.trailingQueryPunctuationRe_, '$1'); -}; - - -/** - * Replaces all existing definitions of a parameter with a single definition. - * - * Repeated calls to this can exhibit quadratic behavior due to the need to - * find existing instances and reconstruct the string, though it should be - * limited given the 2kb limit. Consider using appendParams to append multiple - * parameters in bulk. - * - * @param {string} uri The original URI, which may already have query data. - * @param {string} keyEncoded The key, which must already be URI encoded. - * @param {*} value The value, which will be stringized and encoded (assumed - * not already to be encoded). - * @return {string} The URI with the query parameter added. - */ -goog.uri.utils.setParam = function(uri, keyEncoded, value) { - return goog.uri.utils.appendParam( - goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value); -}; - - -/** - * Generates a URI path using a given URI and a path with checks to - * prevent consecutive "//". The baseUri passed in must not contain - * query or fragment identifiers. The path to append may not contain query or - * fragment identifiers. - * - * @param {string} baseUri URI to use as the base. - * @param {string} path Path to append. - * @return {string} Updated URI. - */ -goog.uri.utils.appendPath = function(baseUri, path) { - goog.uri.utils.assertNoFragmentsOrQueries_(baseUri); - - // Remove any trailing '/' - if (goog.string.endsWith(baseUri, '/')) { - baseUri = baseUri.substr(0, baseUri.length - 1); - } - // Remove any leading '/' - if (goog.string.startsWith(path, '/')) { - path = path.substr(1); - } - return goog.string.buildString(baseUri, '/', path); -}; - - -/** - * Replaces the path. - * @param {string} uri URI to use as the base. - * @param {string} path New path. - * @return {string} Updated URI. - */ -goog.uri.utils.setPath = function(uri, path) { - // Add any missing '/'. - if (!goog.string.startsWith(path, '/')) { - path = '/' + path; - } - var parts = goog.uri.utils.split(uri); - return goog.uri.utils.buildFromEncodedParts( - parts[goog.uri.utils.ComponentIndex.SCHEME], - parts[goog.uri.utils.ComponentIndex.USER_INFO], - parts[goog.uri.utils.ComponentIndex.DOMAIN], - parts[goog.uri.utils.ComponentIndex.PORT], - path, - parts[goog.uri.utils.ComponentIndex.QUERY_DATA], - parts[goog.uri.utils.ComponentIndex.FRAGMENT]); -}; - - -/** - * Standard supported query parameters. - * @enum {string} - */ -goog.uri.utils.StandardQueryParam = { - - /** Unused parameter for unique-ifying. */ - RANDOM: 'zx' -}; - - -/** - * Sets the zx parameter of a URI to a random value. - * @param {string} uri Any URI. - * @return {string} That URI with the "zx" parameter added or replaced to - * contain a random string. - */ -goog.uri.utils.makeUnique = function(uri) { - return goog.uri.utils.setParam(uri, - goog.uri.utils.StandardQueryParam.RANDOM, goog.string.getRandomString()); -}; diff --git a/third_party/document_image_extractor/third_party/closure-library/closure/goog/useragent/useragent.js b/third_party/document_image_extractor/third_party/closure-library/closure/goog/useragent/useragent.js deleted file mode 100644 index c2ce867..0000000 --- a/third_party/document_image_extractor/third_party/closure-library/closure/goog/useragent/useragent.js +++ /dev/null @@ -1,538 +0,0 @@ -// 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 Rendering engine detection. - * @see <a href="http://www.useragentstring.com/">User agent strings</a> - * For information on the browser brand (such as Safari versus Chrome), see - * goog.userAgent.product. - * @author arv@google.com (Erik Arvidsson) - * @see ../demos/useragent.html - */ - -goog.provide('goog.userAgent'); - -goog.require('goog.labs.userAgent.browser'); -goog.require('goog.labs.userAgent.engine'); -goog.require('goog.labs.userAgent.platform'); -goog.require('goog.labs.userAgent.util'); -goog.require('goog.string'); - - -/** - * @define {boolean} Whether we know at compile-time that the browser is IE. - */ -goog.define('goog.userAgent.ASSUME_IE', false); - - -/** - * @define {boolean} Whether we know at compile-time that the browser is GECKO. - */ -goog.define('goog.userAgent.ASSUME_GECKO', false); - - -/** - * @define {boolean} Whether we know at compile-time that the browser is WEBKIT. - */ -goog.define('goog.userAgent.ASSUME_WEBKIT', false); - - -/** - * @define {boolean} Whether we know at compile-time that the browser is a - * mobile device running WebKit e.g. iPhone or Android. - */ -goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false); - - -/** - * @define {boolean} Whether we know at compile-time that the browser is OPERA. - */ -goog.define('goog.userAgent.ASSUME_OPERA', false); - - -/** - * @define {boolean} Whether the - * {@code goog.userAgent.isVersionOrHigher} - * function will return true for any version. - */ -goog.define('goog.userAgent.ASSUME_ANY_VERSION', false); - - -/** - * Whether we know the browser engine at compile-time. - * @type {boolean} - * @private - */ -goog.userAgent.BROWSER_KNOWN_ = - goog.userAgent.ASSUME_IE || - goog.userAgent.ASSUME_GECKO || - goog.userAgent.ASSUME_MOBILE_WEBKIT || - goog.userAgent.ASSUME_WEBKIT || - goog.userAgent.ASSUME_OPERA; - - -/** - * Returns the userAgent string for the current browser. - * - * @return {string} The userAgent string. - */ -goog.userAgent.getUserAgentString = function() { - return goog.labs.userAgent.util.getUserAgent(); -}; - - -/** - * TODO(nnaze): Change type to "Navigator" and update compilation targets. - * @return {Object} The native navigator object. - */ -goog.userAgent.getNavigator = function() { - // Need a local navigator reference instead of using the global one, - // to avoid the rare case where they reference different objects. - // (in a WorkerPool, for example). - return goog.global['navigator'] || null; -}; - - -/** - * Whether the user agent is Opera. - * @type {boolean} - */ -goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ? - goog.userAgent.ASSUME_OPERA : - goog.labs.userAgent.browser.isOpera(); - - -/** - * Whether the user agent is Internet Explorer. - * @type {boolean} - */ -goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ? - goog.userAgent.ASSUME_IE : - goog.labs.userAgent.browser.isIE(); - - -/** - * Whether the user agent is Gecko. Gecko is the rendering engine used by - * Mozilla, Firefox, and others. - * @type {boolean} - */ -goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ? - goog.userAgent.ASSUME_GECKO : - goog.labs.userAgent.engine.isGecko(); - - -/** - * Whether the user agent is WebKit. WebKit is the rendering engine that - * Safari, Android and others use. - * @type {boolean} - */ -goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ? - goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT : - goog.labs.userAgent.engine.isWebKit(); - - -/** - * Whether the user agent is running on a mobile device. - * - * This is a separate function so that the logic can be tested. - * - * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile(). - * - * @return {boolean} Whether the user agent is running on a mobile device. - * @private - */ -goog.userAgent.isMobile_ = function() { - return goog.userAgent.WEBKIT && - goog.labs.userAgent.util.matchUserAgent('Mobile'); -}; - - -/** - * Whether the user agent is running on a mobile device. - * - * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent - * is promoted as the gecko/webkit logic is likely inaccurate. - * - * @type {boolean} - */ -goog.userAgent.MOBILE = goog.userAgent.ASSUME_MOBILE_WEBKIT || - goog.userAgent.isMobile_(); - - -/** - * Used while transitioning code to use WEBKIT instead. - * @type {boolean} - * @deprecated Use {@link goog.userAgent.product.SAFARI} instead. - * TODO(nicksantos): Delete this from goog.userAgent. - */ -goog.userAgent.SAFARI = goog.userAgent.WEBKIT; - - -/** - * @return {string} the platform (operating system) the user agent is running - * on. Default to empty string because navigator.platform may not be defined - * (on Rhino, for example). - * @private - */ -goog.userAgent.determinePlatform_ = function() { - var navigator = goog.userAgent.getNavigator(); - return navigator && navigator.platform || ''; -}; - - -/** - * The platform (operating system) the user agent is running on. Default to - * empty string because navigator.platform may not be defined (on Rhino, for - * example). - * @type {string} - */ -goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_(); - - -/** - * @define {boolean} Whether the user agent is running on a Macintosh operating - * system. - */ -goog.define('goog.userAgent.ASSUME_MAC', false); - - -/** - * @define {boolean} Whether the user agent is running on a Windows operating - * system. - */ -goog.define('goog.userAgent.ASSUME_WINDOWS', false); - - -/** - * @define {boolean} Whether the user agent is running on a Linux operating - * system. - */ -goog.define('goog.userAgent.ASSUME_LINUX', false); - - -/** - * @define {boolean} Whether the user agent is running on a X11 windowing - * system. - */ -goog.define('goog.userAgent.ASSUME_X11', false); - - -/** - * @define {boolean} Whether the user agent is running on Android. - */ -goog.define('goog.userAgent.ASSUME_ANDROID', false); - - -/** - * @define {boolean} Whether the user agent is running on an iPhone. - */ -goog.define('goog.userAgent.ASSUME_IPHONE', false); - - -/** - * @define {boolean} Whether the user agent is running on an iPad. - */ -goog.define('goog.userAgent.ASSUME_IPAD', false); - - -/** - * @type {boolean} - * @private - */ -goog.userAgent.PLATFORM_KNOWN_ = - goog.userAgent.ASSUME_MAC || - goog.userAgent.ASSUME_WINDOWS || - goog.userAgent.ASSUME_LINUX || - goog.userAgent.ASSUME_X11 || - goog.userAgent.ASSUME_ANDROID || - goog.userAgent.ASSUME_IPHONE || - goog.userAgent.ASSUME_IPAD; - - -/** - * Whether the user agent is running on a Macintosh operating system. - * @type {boolean} - */ -goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ? - goog.userAgent.ASSUME_MAC : goog.labs.userAgent.platform.isMacintosh(); - - -/** - * Whether the user agent is running on a Windows operating system. - * @type {boolean} - */ -goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ? - goog.userAgent.ASSUME_WINDOWS : - goog.labs.userAgent.platform.isWindows(); - - -/** - * Whether the user agent is Linux per the legacy behavior of - * goog.userAgent.LINUX, which considered ChromeOS to also be - * Linux. - * @return {boolean} - * @private - */ -goog.userAgent.isLegacyLinux_ = function() { - return goog.labs.userAgent.platform.isLinux() || - goog.labs.userAgent.platform.isChromeOS(); -}; - - -/** - * Whether the user agent is running on a Linux operating system. - * - * Note that goog.userAgent.LINUX considers ChromeOS to be Linux, - * while goog.labs.userAgent.platform considers ChromeOS and - * Linux to be different OSes. - * - * @type {boolean} - */ -goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ? - goog.userAgent.ASSUME_LINUX : - goog.userAgent.isLegacyLinux_(); - - -/** - * @return {boolean} Whether the user agent is an X11 windowing system. - * @private - */ -goog.userAgent.isX11_ = function() { - var navigator = goog.userAgent.getNavigator(); - return !!navigator && - goog.string.contains(navigator['appVersion'] || '', 'X11'); -}; - - -/** - * Whether the user agent is running on a X11 windowing system. - * @type {boolean} - */ -goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ? - goog.userAgent.ASSUME_X11 : - goog.userAgent.isX11_(); - - -/** - * Whether the user agent is running on Android. - * @type {boolean} - */ -goog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ? - goog.userAgent.ASSUME_ANDROID : - goog.labs.userAgent.platform.isAndroid(); - - -/** - * Whether the user agent is running on an iPhone. - * @type {boolean} - */ -goog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ? - goog.userAgent.ASSUME_IPHONE : - goog.labs.userAgent.platform.isIphone(); - - -/** - * Whether the user agent is running on an iPad. - * @type {boolean} - */ -goog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ? - goog.userAgent.ASSUME_IPAD : - goog.labs.userAgent.platform.isIpad(); - - -/** - * @return {string} The string that describes the version number of the user - * agent. - * @private - */ -goog.userAgent.determineVersion_ = function() { - // All browsers have different ways to detect the version and they all have - // different naming schemes. - - if (goog.userAgent.OPERA && goog.global['opera']) { - var operaVersion = goog.global['opera'].version; - return goog.isFunction(operaVersion) ? operaVersion() : operaVersion; - } - - // version is a string rather than a number because it may contain 'b', 'a', - // and so on. - var version = ''; - var arr = goog.userAgent.getVersionRegexResult_(); - if (arr) { - version = arr ? arr[1] : ''; - } - - if (goog.userAgent.IE && !goog.labs.userAgent.engine.isEdge()) { - // IE9 can be in document mode 9 but be reporting an inconsistent user agent - // version. If it is identifying as a version lower than 9 we take the - // documentMode as the version instead. IE8 has similar behavior. - // It is recommended to set the X-UA-Compatible header to ensure that IE9 - // uses documentMode 9. - var docMode = goog.userAgent.getDocumentMode_(); - if (docMode > parseFloat(version)) { - return String(docMode); - } - } - - return version; -}; - - -/** - * @return {Array|undefined} The version regex matches from parsing the user - * agent string. These regex statements must be executed inline so they can - * be compiled out by the closure compiler with the rest of the useragent - * detection logic when ASSUME_* is specified. - * @private - */ -goog.userAgent.getVersionRegexResult_ = function() { - var userAgent = goog.userAgent.getUserAgentString(); - if (goog.userAgent.GECKO) { - return /rv\:([^\);]+)(\)|;)/.exec(userAgent); - } - if (goog.userAgent.IE && goog.labs.userAgent.engine.isEdge()) { - return /Edge\/([\d\.]+)/.exec(userAgent); - } - if (goog.userAgent.IE) { - return /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(userAgent); - } - if (goog.userAgent.WEBKIT) { - // WebKit/125.4 - return /WebKit\/(\S+)/.exec(userAgent); - } -}; - - -/** - * @return {number|undefined} Returns the document mode (for testing). - * @private - */ -goog.userAgent.getDocumentMode_ = function() { - // NOTE(user): goog.userAgent may be used in context where there is no DOM. - var doc = goog.global['document']; - return doc ? doc['documentMode'] : undefined; -}; - - -/** - * The version of the user agent. This is a string because it might contain - * 'b' (as in beta) as well as multiple dots. - * @type {string} - */ -goog.userAgent.VERSION = goog.userAgent.determineVersion_(); - - -/** - * Compares two version numbers. - * - * @param {string} v1 Version of first item. - * @param {string} v2 Version of second item. - * - * @return {number} 1 if first argument is higher - * 0 if arguments are equal - * -1 if second argument is higher. - * @deprecated Use goog.string.compareVersions. - */ -goog.userAgent.compare = function(v1, v2) { - return goog.string.compareVersions(v1, v2); -}; - - -/** - * Cache for {@link goog.userAgent.isVersionOrHigher}. - * Calls to compareVersions are surprisingly expensive and, as a browser's - * version number is unlikely to change during a session, we cache the results. - * @const - * @private - */ -goog.userAgent.isVersionOrHigherCache_ = {}; - - -/** - * Whether the user agent version is higher or the same as the given version. - * NOTE: When checking the version numbers for Firefox and Safari, be sure to - * use the engine's version, not the browser's version number. For example, - * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11. - * Opera and Internet Explorer versions match the product release number.<br> - * @see <a href="http://en.wikipedia.org/wiki/Safari_version_history"> - * Webkit</a> - * @see <a href="http://en.wikipedia.org/wiki/Gecko_engine">Gecko</a> - * - * @param {string|number} version The version to check. - * @return {boolean} Whether the user agent version is higher or the same as - * the given version. - */ -goog.userAgent.isVersionOrHigher = function(version) { - return goog.userAgent.ASSUME_ANY_VERSION || - goog.userAgent.isVersionOrHigherCache_[version] || - (goog.userAgent.isVersionOrHigherCache_[version] = - goog.string.compareVersions(goog.userAgent.VERSION, version) >= 0); -}; - - -/** - * Deprecated alias to {@code goog.userAgent.isVersionOrHigher}. - * @param {string|number} version The version to check. - * @return {boolean} Whether the user agent version is higher or the same as - * the given version. - * @deprecated Use goog.userAgent.isVersionOrHigher(). - */ -goog.userAgent.isVersion = goog.userAgent.isVersionOrHigher; - - -/** - * Whether the IE effective document mode is higher or the same as the given - * document mode version. Because document modes were deprecated with the launch - * of IE's new Edge engine, Edge browsers will always return true for this - * function. - * NOTE: Only for IE, return false for another browser. - * - * @param {number} documentMode The document mode version to check. - * @return {boolean} Whether the IE effective document mode is higher or the - * same as the given version. - */ -goog.userAgent.isDocumentModeOrHigher = function(documentMode) { - return goog.userAgent.IE && (goog.labs.userAgent.engine.isEdge() || - goog.userAgent.DOCUMENT_MODE >= documentMode); -}; - - -/** - * Deprecated alias to {@code goog.userAgent.isDocumentModeOrHigher}. - * @param {number} version The version to check. - * @return {boolean} Whether the IE effective document mode is higher or the - * same as the given version. - * @deprecated Use goog.userAgent.isDocumentModeOrHigher(). - */ -goog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher; - - -/** - * For IE version < 7 and IE Edge browsers, documentMode is undefined. For - * non-Edge browsers attempt to use the CSS1Compat property to see if we are in - * standards mode. If we are in standards mode, treat the browser version as the - * document mode. Otherwise, IE is emulating version 5. - * @type {number|undefined} - * @const - */ -goog.userAgent.DOCUMENT_MODE = (function() { - var doc = goog.global['document']; - var mode = goog.userAgent.getDocumentMode_(); - if (!doc || !goog.userAgent.IE || - (!mode && goog.labs.userAgent.engine.isEdge())) { - return undefined; - } - return mode || (doc['compatMode'] == 'CSS1Compat' ? - parseInt(goog.userAgent.VERSION, 10) : 5); -})(); diff --git a/third_party/document_image_extractor/third_party/src/ad_element_filter.js b/third_party/document_image_extractor/third_party/src/ad_element_filter.js deleted file mode 100644 index 7bbf9f6..0000000 --- a/third_party/document_image_extractor/third_party/src/ad_element_filter.js +++ /dev/null @@ -1,42 +0,0 @@ -goog.provide('image.collections.extension.AdElementFilter'); - -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.dom.classlist'); -goog.require('image.collections.extension.ElementFilter'); - -goog.scope(function() { -var ElementFilter = image.collections.extension.ElementFilter; - - - -/** - * Filters out potential ad elements. - * @constructor - * @implements {ElementFilter} - */ -image.collections.extension.AdElementFilter = function() { - /** @private {!Array.<string>} */ - this.adWords_ = ['ad', 'advertisement', 'ads', 'sponsor', 'sponsored']; -}; -var AdElementFilter = image.collections.extension.AdElementFilter; - - -/** @override */ -AdElementFilter.prototype.filter = function(element) { - var ancestorElement = element; - while (ancestorElement) { - var classNames = goog.dom.classlist.get(ancestorElement); - for (var i = 0; i < classNames.length; ++i) { - var tokens = classNames[i].split(/\W+/); - for (var j = 0; j < tokens.length; ++j) { - if (goog.array.contains(this.adWords_, tokens[j].toLowerCase())) { - return false; - } - } - } - ancestorElement = goog.dom.getParentElement(ancestorElement); - } - return true; -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/constants.js b/third_party/document_image_extractor/third_party/src/constants.js deleted file mode 100644 index 7f86d27..0000000 --- a/third_party/document_image_extractor/third_party/src/constants.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * @fileoverview Collections constants. - * @author busaryev@google.com (Oleksiy Busaryev) - */ -goog.provide('gws.collections.common.Constants'); - -goog.scope(function() { - -var Constants = gws.collections.common.Constants; - -/** @type {number} The minimum width of extracted images. */ -Constants.EXTRACT_MIN_WIDTH = 100; - - -/** @type {number} The minimum height of extracted images. */ -Constants.EXTRACT_MIN_HEIGHT = 100; - -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/controller.js b/third_party/document_image_extractor/third_party/src/controller.js deleted file mode 100644 index 3aa1961..0000000 --- a/third_party/document_image_extractor/third_party/src/controller.js +++ /dev/null @@ -1,40 +0,0 @@ -goog.provide('image.collections.extension.Controller'); - -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventTarget'); - -goog.scope(function() { - - - -/** - * A base class for all controller classes. Controllers connect UI of the - * 'Google Stars' Chrome extension (see go/stars for details) to backends - * (such as GWS, Chrome Sync etc.) Should not be instantiated by itself. - * Each derived controller should handle certain types of UI events - * (e.g. search requests, clustering requests etc.) - * - * @extends {goog.events.EventTarget} - * @constructor - */ -image.collections.extension.Controller = function() { - Controller.base(this, 'constructor'); - - /** @protected {!goog.events.EventHandler} */ - this.eventHandler = new goog.events.EventHandler(this); - this.registerDisposable(this.eventHandler); -}; -goog.inherits(image.collections.extension.Controller, goog.events.EventTarget); -var Controller = image.collections.extension.Controller; - - -/** - * Initializes the controller. By default, sets the parent event target - * (controllers communicate with UI by handling and dispatching events - * on this event target). - * @param {!goog.events.EventTarget} parentEventTarget - */ -Controller.prototype.initialize = function(parentEventTarget) { - this.setParentEventTarget(parentEventTarget); -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/document_feature.js b/third_party/document_image_extractor/third_party/src/document_feature.js deleted file mode 100644 index 09239d4..0000000 --- a/third_party/document_image_extractor/third_party/src/document_feature.js +++ /dev/null @@ -1,40 +0,0 @@ -goog.provide('image.collections.extension.DocumentFeature'); - -goog.scope(function() { - - - -/** - * This is a base class for all document features (e.g. title, snippet, image). - * @param {number} relevance Relevance of this feature to the document. - * @constructor - */ -image.collections.extension.DocumentFeature = function(relevance) { - /** @private {number} */ - this.relevance_ = relevance; -}; -var DocumentFeature = image.collections.extension.DocumentFeature; - - -/** - * Returns the feature relevance. - * @return {number} - */ -DocumentFeature.prototype.getRelevance = function() { - return this.relevance_; -}; - - -/** - * Compares two document features by their relevance. - * @param {!DocumentFeature} feature1 - * @param {!DocumentFeature} feature2 - * @return {number} - */ -DocumentFeature.compare = function(feature1, feature2) { - if (feature1 == feature2) { - return 0; - } - return feature1.getRelevance() - feature2.getRelevance(); -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/document_feature_extractor.js b/third_party/document_image_extractor/third_party/src/document_feature_extractor.js deleted file mode 100644 index 200c937..0000000 --- a/third_party/document_image_extractor/third_party/src/document_feature_extractor.js +++ /dev/null @@ -1,117 +0,0 @@ -goog.provide('image.collections.extension.DocumentFeatureExtractor'); - -goog.require('goog.asserts'); -goog.require('image.collections.extension.DocumentFeature'); -goog.require('image.collections.extension.ElementFilter'); - -goog.scope(function() { -var DocumentFeature = image.collections.extension.DocumentFeature; -var ElementFilter = image.collections.extension.ElementFilter; - - - -/** - * A base class for document feature (title, snippet, image) extractors. - * @constructor - */ -image.collections.extension.DocumentFeatureExtractor = function() { - /** @protected {!Array.<!ElementFilter>} */ - this.filters_ = []; -}; -var DocumentFeatureExtractor = - image.collections.extension.DocumentFeatureExtractor; - - -/** - * Installs an element filter. - * @param {!ElementFilter} filter - * @protected - */ -DocumentFeatureExtractor.prototype.addFilter = function(filter) { - this.filters_.push(filter); -}; - - -/** - * Returns true iff an element passes all the filters. - * @param {!Element} element - * @return {boolean} - */ -DocumentFeatureExtractor.prototype.filter = function(element) { - for (var i = 0; i < this.filters_.length; ++i) { - if (!this.filters_[i].filter(element)) { - return false; - } - } - return true; -}; - - -/** - * Given an HTML document, returns a feature with a highest relevance value. - * TODO(busaryev): look at the mean, median relevance etc. - * @param {!Document} doc HTML document. - * @return {DocumentFeature} - */ -DocumentFeatureExtractor.prototype.extractBestFromDocument = function(doc) { - var features = this.extractAllFromDocument(doc); - if (features.length == 0) return null; - var best = features[0]; - for (var i = 1; i < features.length; ++i) { - var feature = features[i]; - if (feature.getRelevance() > best.getRelevance()) { - best = feature; - } - } - return best; -}; - - -/** - * Given an HTML document, returns an array of features sorted by relevance. - * By default, this function tries to extract a feature from every DOM element. - * Derived classes may override this function to look at a subset of DOM (e.g. - * only <meta> and <link> elements). - * @param {!Document} doc HTML document. - * @return {!Array.<!DocumentFeature>} - */ -DocumentFeatureExtractor.prototype.extractAllFromDocument = function(doc) { - return this.extractFromNodeList(doc.getElementsByTagName('*')); -}; - - -/** - * This function tries to extract a feature from every node in a nodelist - * and returns an array of features. - * @param {!NodeList} nodeList DOM node list. - * @param {!Object=} opt_context Optional context. - * @return {!Array.<!DocumentFeature>} - */ -DocumentFeatureExtractor.prototype.extractFromNodeList = function( - nodeList, opt_context) { - goog.asserts.assert(goog.isArrayLike(nodeList)); - var result = []; - var nodeListLength = nodeList.length; - for (var j = 0; j < nodeListLength; ++j) { - var feature = this.extractFromElement(nodeList[j], opt_context); - if (feature) { - result.push(feature); - } - } - return result; -}; - - -/** - * This function extracts a feature from an HTML element. It should be - * overridden in derived classes, unless the feature can be extracted without - * looking at DOM. - * @param {!Element} element HTML element. - * @param {!Object=} opt_context Optional context. - * @return {DocumentFeature} - */ -DocumentFeatureExtractor.prototype.extractFromElement = function( - element, opt_context) { - return null; -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/document_image.js b/third_party/document_image_extractor/third_party/src/document_image.js deleted file mode 100644 index 262c8d7..0000000 --- a/third_party/document_image_extractor/third_party/src/document_image.js +++ /dev/null @@ -1,80 +0,0 @@ -goog.provide('image.collections.extension.DocumentImage'); - -goog.require('goog.asserts'); -goog.require('image.collections.extension.DocumentFeature'); - -goog.scope(function() { -var DocumentFeature = image.collections.extension.DocumentFeature; - - - -/** - * A class representing a salient image in an HTML document. - * @param {number} relevance - * @param {string} url - * @param {!goog.math.Size=} opt_size Natural size of image or null if image - * size is not available in the DOM tree. - * @param {!goog.math.Size=} opt_displaySize Size at which the image is being - * shown. One of opt_size or opt_displaySize MUST be specified. - * @extends {DocumentFeature} - * @constructor - */ -image.collections.extension.DocumentImage = function( - relevance, url, opt_size, opt_displaySize) { - DocumentImage.base(this, 'constructor', relevance); - - /** @private {string} Absolute image url. */ - this.url_ = url; - - /** @private {!goog.math.Size|undefined} Image resolution in pixels. */ - this.size_ = opt_size; - - /** @private {!goog.math.Size|undefined} Displayed image resolution - * in pixels. - */ - this.displaySize_ = opt_displaySize; - - goog.asserts.assert(goog.isDef(opt_size) || goog.isDef(opt_displaySize)); -}; -goog.inherits(image.collections.extension.DocumentImage, DocumentFeature); -var DocumentImage = image.collections.extension.DocumentImage; - - -/** - * These attributes needs to be set for images defined in <meta> and <link> - * elements (e.g. OpenGraph images) so that they can be used as salient image - * candidates. They are computed by the DomController class. - * @enum {string} - */ -DocumentImage.CustomAttribute = { - WIDTH: 'data-google-stars-image-width', - HEIGHT: 'data-google-stars-image-height' -}; - - -/** - * Returns the absolute image url. - * @return {string} - */ -DocumentImage.prototype.getUrl = function() { - return this.url_; -}; - - -/** - * Returns the image resolution in pixels. - * @return {!goog.math.Size|undefined} - */ -DocumentImage.prototype.getSize = function() { - return this.size_; -}; - - -/** - * Returns the shown image resolution in pixels. - * @return {!goog.math.Size|undefined} - */ -DocumentImage.prototype.getDisplaySize = function() { - return this.displaySize_; -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/document_image_extractor.js b/third_party/document_image_extractor/third_party/src/document_image_extractor.js deleted file mode 100644 index d82702d..0000000 --- a/third_party/document_image_extractor/third_party/src/document_image_extractor.js +++ /dev/null @@ -1,400 +0,0 @@ -goog.provide('image.collections.extension.DocumentImageExtractor'); - -goog.require('goog.Uri'); -goog.require('goog.asserts'); -goog.require('goog.dom'); -goog.require('goog.log'); -goog.require('goog.math.Size'); -goog.require('goog.object'); -goog.require('goog.string'); -goog.require('goog.style'); -goog.require('goog.uri.utils'); -goog.require('gws.collections.common.Constants'); -goog.require('image.collections.extension.AdElementFilter'); -goog.require('image.collections.extension.DocumentFeature'); -goog.require('image.collections.extension.DocumentFeatureExtractor'); -goog.require('image.collections.extension.DocumentImage'); -goog.require('image.collections.extension.VisibleElementFilter'); - -goog.scope(function() { -var AdElementFilter = image.collections.extension.AdElementFilter; -var Constants = gws.collections.common.Constants; -var DocumentFeature = image.collections.extension.DocumentFeature; -var DocumentFeatureExtractor = - image.collections.extension.DocumentFeatureExtractor; -var DocumentImage = image.collections.extension.DocumentImage; -var CustomAttribute = DocumentImage.CustomAttribute; -var VisibleElementFilter = image.collections.extension.VisibleElementFilter; - - - -/** - * This class is used for extracting a salient image from an HTML document. - * @extends {DocumentFeatureExtractor} - * @constructor - */ -image.collections.extension.DocumentImageExtractor = function() { - DocumentImageExtractor.base(this, 'constructor'); - - this.addFilter(new AdElementFilter()); - this.addFilter(new VisibleElementFilter()); -}; -goog.inherits(image.collections.extension.DocumentImageExtractor, - DocumentFeatureExtractor); -var DocumentImageExtractor = image.collections.extension.DocumentImageExtractor; -goog.addSingletonGetter(DocumentImageExtractor); - - -/** @private {goog.log.Logger} Extractor logger. */ -DocumentImageExtractor.logger_ = goog.log.getLogger( - 'image.collections.extension.DocumentImageExtractor'); - - -/** @enum {number} */ -DocumentImageExtractor.Parameters = { - AREA_MULTIPLIER: -1e-5, - ASPECT_RATIO_DEMOTION_FACTOR: 0.8, - MAX_ASPECT_RATIO: 2, - MAX_ELEMENTS_WITH_BACKGROUND: 30, - MAX_OFFSET: 2000, - NON_TOPLEVEL_DEMOTION_FACTOR: 0.5, - OFFSET_MULTIPLIER: 1e-3, - WEIGHT_APPLE: 0.7, - WEIGHT_MICRODATA: 0.55, - WEIGHT_MICROSOFT: 0.9, - WEIGHT_OPEN_GRAPH: 1.0, - WEIGHT_SRC: 0.6, - WEIGHT_TWITTER: 0.8 -}; -var Parameters = DocumentImageExtractor.Parameters; - - -/** - * Map of image type to relevance multiplier. - * @private {!Object.<string, number>} - */ -DocumentImageExtractor.IMAGE_TYPE_RELEVANCE_MULTIPLIER_ = - goog.object.create('.gif', 0.5); - - - -/** @constructor */ -DocumentImageExtractor.Context = function() { - /** @type {number} */ - this.numElementsWithBackground = 0; - - /** @type {!Object.<string, number>} */ - this.urlToRelevance = {}; -}; -var Context = DocumentImageExtractor.Context; - - -/** - * Extracts salient images from an HTML document. - * @param {!Document} doc - * @return {!Array.<!DocumentImage>} - * @override - */ -DocumentImageExtractor.prototype.extractAllFromDocument = function(doc) { - var context = new Context(); - return this.extractFromNodeList(doc.getElementsByTagName('*'), context); -}; - - -/** - * Extracts a salient image from an HTML element, returns null if failed. - * @param {!Element} element HTML element. - * @param {Object=} opt_context Optional context. - * @return {DocumentImage} - * @override - */ -DocumentImageExtractor.prototype.extractFromElement = function( - element, opt_context) { - var image = null; - switch (element.tagName.toLowerCase()) { - case 'meta': - image = this.extractOpenGraphImage_(element) || - this.extractMicrosoftImage_(element) || - this.extractTwitterImage_(element) || - this.extractMicrodataImage_(element); - break; - case 'link': - image = this.extractAppleImage_(element) || - this.extractImageSrcImage_(element) || - this.extractMicrodataImage_(element); - break; - case 'img': - if (this.filter(element)) { - image = this.extractImage_(element); - } - break; - default: - if (this.filter(element) && opt_context.numElementsWithBackground < - Parameters.MAX_ELEMENTS_WITH_BACKGROUND) { - image = this.extractBackgroundImage_(element); - if (image) { - ++opt_context.numElementsWithBackground; - } - } - } - - if (!image) { - return null; - } - - var size = image.getDisplaySize() || image.getSize(); - goog.asserts.assert(!goog.isNull(size)); - if (image.getUrl() != document.location.href) { - // Ignore images that are too small. - if (size.width < Constants.EXTRACT_MIN_WIDTH || - size.height < Constants.EXTRACT_MIN_HEIGHT) { - return null; - } - } - // Demote smaller images (squash area using the sigmoid function). - var relevance = image.getRelevance(); - relevance /= (1 + Math.exp(Parameters.AREA_MULTIPLIER * size.area())); - // Demote images with bad aspect ratio. - var aspectRatio = size.aspectRatio(); - if (aspectRatio < 1) { - aspectRatio = 1 / aspectRatio; - } - if (aspectRatio > Parameters.MAX_ASPECT_RATIO) { - relevance *= Parameters.ASPECT_RATIO_DEMOTION_FACTOR; - } - - // TODO(busaryev): use the following features: - // - relative size of the image comparing to neighbors; - // - area of the visible portion of the image; - // - position (demote images on the border of the page). - - var url = image.getUrl(); - try { - // Make sure that image url is absolute. - var documentUrl = goog.dom.getOwnerDocument(element).documentURI; - url = goog.Uri.resolve(documentUrl, url).toString(); - } catch (e) { - goog.log.info(DocumentImageExtractor.logger_, - 'Cannot resolve url: ' + url); - return null; - } - - var imagePath = goog.string.makeSafe(goog.uri.utils.getPath(url)); - var lastDot = imagePath.lastIndexOf('.'); - if (lastDot > 0) { - var imageType = imagePath.slice(lastDot); - var multiplier = - DocumentImageExtractor.IMAGE_TYPE_RELEVANCE_MULTIPLIER_[imageType]; - if (multiplier) { - relevance *= multiplier; - } - } - - if (url in opt_context.urlToRelevance && - opt_context.urlToRelevance[url] > relevance) { - return null; - } - opt_context.urlToRelevance[url] = relevance; - return new DocumentImage(relevance, url, image.getSize(), - image.getDisplaySize()); -}; - - -/** - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractOpenGraphImage_ = function(element) { - return this.extractCanonicalImage_( - element, Parameters.WEIGHT_OPEN_GRAPH, 'property', 'og:image', 'content'); -}; - - -/** - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractMicrosoftImage_ = function(element) { - return this.extractCanonicalImage_(element, Parameters.WEIGHT_MICROSOFT, - 'name', 'msapplication-tileimage', 'content'); -}; - - -/** - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractTwitterImage_ = function(element) { - return this.extractCanonicalImage_( - element, Parameters.WEIGHT_TWITTER, 'name', 'twitter:image', 'content'); -}; - - -/** - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractAppleImage_ = function(element) { - return this.extractCanonicalImage_( - element, Parameters.WEIGHT_APPLE, 'rel', 'apple-touch-icon', 'href'); -}; - - -/** - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractImageSrcImage_ = function(element) { - return this.extractCanonicalImage_( - element, Parameters.WEIGHT_SRC, 'rel', 'image_src', 'href'); -}; - - -/** - * @param {!Element} element - * @param {!number} relevance - * @param {string} attributeName - * @param {string} attribute - * @param {string} urlAttributeName - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractCanonicalImage_ = function( - element, relevance, attributeName, attribute, urlAttributeName) { - goog.asserts.assert(goog.isNumber(relevance)); - goog.asserts.assert(goog.isString(attributeName)); - goog.asserts.assert(goog.isString(attribute)); - - if (goog.string.caseInsensitiveEquals( - goog.string.makeSafe(element.getAttribute(attributeName)), attribute)) { - var url = element.getAttribute(urlAttributeName); - if (!url || goog.string.startsWith(url, 'data:')) { - return null; - } - var width = goog.string.parseInt( - element.getAttribute(CustomAttribute.WIDTH)); - var height = goog.string.parseInt( - element.getAttribute(CustomAttribute.HEIGHT)); - if (width && height) { - // For non-toplevel urls, demote the image if it is not in the document. - var ownerDocument = goog.dom.getOwnerDocument(element); - if (goog.uri.utils.getPath(ownerDocument.documentURI) != '/' && - ownerDocument.body.innerHTML.indexOf(url) == -1) { - relevance *= Parameters.NON_TOPLEVEL_DEMOTION_FACTOR; - } - var size = new goog.math.Size(width, height); - return new DocumentImage(relevance, url, size); - } - } - return null; -}; - - -/** - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractMicrodataImage_ = function(element) { - var itemProp = element.getAttribute('itemprop'); - if (itemProp && itemProp.toLowerCase() == 'thumbnailurl') { - var url = element.getAttribute('href') || element.getAttribute('content'); - if (!url || goog.string.startsWith(url, 'data:')) { - return null; - } - var width = goog.string.parseInt( - element.getAttribute(CustomAttribute.WIDTH)); - var height = goog.string.parseInt( - element.getAttribute(CustomAttribute.HEIGHT)); - if (width && height) { - var size = new goog.math.Size(width, height); - return new DocumentImage(Parameters.WEIGHT_MICRODATA, url, size); - } - } - return null; -}; - - -/** - * @param {!Element} element - * @return {number} - * @private - */ -DocumentImageExtractor.prototype.getElementRelevance_ = function(element) { - var offset = goog.style.getPageOffsetTop(element); - if (offset > Parameters.MAX_OFFSET) { - return 0; - } - return 1 / (1 + Math.exp(Parameters.OFFSET_MULTIPLIER * offset)); -}; - - -/** - * Extracts an image from the <img> HTML element. - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractImage_ = function(element) { - goog.asserts.assert(element.tagName.toLowerCase() == 'img'); - var url = element.src; - // We cannot handle data URIs. - if (url && !goog.string.startsWith(url, 'data:')) { - var naturalSize = new goog.math.Size( - element.naturalWidth, element.naturalHeight); - var displaySize = goog.style.getSize(element); - var size = naturalSize.area() < displaySize.area() ? - naturalSize : displaySize; - if (size.width && size.height) { - var relevance = this.getElementRelevance_(element); - return new DocumentImage(relevance, url, naturalSize, displaySize); - } - } - return null; -}; - - -/** - * Extracts an image specified in 'background-image' property of an element. - * @param {!Element} element - * @return {DocumentImage} - * @private - */ -DocumentImageExtractor.prototype.extractBackgroundImage_ = function(element) { - var backgroundImage = goog.style.getComputedStyle( - element, 'background-image'); - var backgroundRepeat = goog.style.getComputedStyle( - element, 'background-repeat'); - var backgroundSize = goog.style.getComputedStyle( - element, 'background-size'); - if (backgroundImage && - (backgroundRepeat == 'no-repeat' || backgroundSize == 'cover') && - goog.string.startsWith(backgroundImage, 'url(') && - goog.string.endsWith(backgroundImage, ')')) { - var url = backgroundImage.substr(4, backgroundImage.length - 5); - if (url && !goog.string.startsWith(url, 'data:')) { - var size = goog.style.getSize(element); - if (size.width && size.height) { - var relevance = this.getElementRelevance_(element); - var children = goog.dom.getChildren(element); - for (var i = 0; i < children.length; ++i) { - var child = children[i]; - if (goog.style.getComputedStyle(child, 'display') != 'none' && - goog.style.getSize(child).area() > 0.1 * size.area()) { - relevance *= 0.1; - break; - } - } - return new DocumentImage(relevance, url, - undefined /* image size is unknown */, size); - } - } - } - return null; -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/document_video.js b/third_party/document_image_extractor/third_party/src/document_video.js deleted file mode 100644 index 6ecc703..0000000 --- a/third_party/document_image_extractor/third_party/src/document_video.js +++ /dev/null @@ -1,54 +0,0 @@ -goog.provide('image.collections.extension.DocumentVideo'); - -goog.require('image.collections.extension.DocumentFeature'); - -goog.scope(function() { -var DocumentFeature = image.collections.extension.DocumentFeature; - - - -/** - * A class representing a salient video in an HTML document. - * @param {number} relevance - * @param {string} url - * @param {!goog.math.Size} size - * @extends {DocumentFeature} - * @constructor - */ -image.collections.extension.DocumentVideo = function(relevance, url, size) { - DocumentVideo.base(this, 'constructor', relevance); - - /** @private {string} Absolute video url. */ - this.url_ = url; - - /** @private {!goog.math.Size} Video resolution in pixels */ - this.size_ = size; -}; -goog.inherits(image.collections.extension.DocumentVideo, DocumentFeature); -var DocumentVideo = image.collections.extension.DocumentVideo; - - -/** @enum {string} */ -DocumentVideo.CustomAttribute = { - WIDTH: 'data-google-stars-video-width', - HEIGHT: 'data-google-stars-video-height' -}; - - -/** - * Returns the absolute video url. - * @return {string} - */ -DocumentVideo.prototype.getUrl = function() { - return this.url_; -}; - - -/** - * Returns the video resolution in pixels. - * @return {!goog.math.Size} - */ -DocumentVideo.prototype.getSize = function() { - return this.size_; -}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/dom_controller.js b/third_party/document_image_extractor/third_party/src/dom_controller.js deleted file mode 100644 index 97dd3cf..0000000 --- a/third_party/document_image_extractor/third_party/src/dom_controller.js +++ /dev/null @@ -1,264 +0,0 @@ -goog.provide('image.collections.extension.DomController'); - -goog.require('goog.Timer'); -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.events.EventType'); -goog.require('goog.log'); -goog.require('gws.collections.common.Constants'); -goog.require('image.collections.extension.Controller'); -goog.require('image.collections.extension.DocumentImage'); -goog.require('image.collections.extension.DocumentVideo'); -goog.require('image.collections.extension.DomEvent'); - -goog.scope(function() { -var Constants = gws.collections.common.Constants; -var DocumentImage = image.collections.extension.DocumentImage; -var DocumentVideo = image.collections.extension.DocumentVideo; -var DomEvent = image.collections.extension.DomEvent; - - -/** - * This class handles page DOM events and implements DOM manipulation. - * It should be instantiated by a content script. - * TODO(busaryev): preloading may not be the best choice for mobile clients. - * @extends {image.collections.extension.Controller} - * @constructor - */ -image.collections.extension.DomController = function() { - DomController.base(this, 'constructor'); - - /** @private {number} Number of DOM elements left. */ - this.numElementsToProcess_ = 0; - - /** @private {number} The timeout id for goog.Timer.callOnce. */ - this.timeoutId_ = -1; -}; -goog.inherits(image.collections.extension.DomController, - image.collections.extension.Controller); -var DomController = image.collections.extension.DomController; - - -/** @private {goog.log.Logger} */ -DomController.logger_ = goog.log.getLogger( - 'image.collections.extension.DomController'); - - -/** - * @private {number} The number of milliseconds to wait for the load - * event to occur before giving up. This ensures we are not wasting too much - * time trying to get the clip. - */ -DomController.LOAD_TIMEOUT_MS_ = 5000; - - -/** @override */ -DomController.prototype.initialize = function(parentEventTarget) { - DomController.base(this, 'initialize', parentEventTarget); - - this.eventHandler. - listen(parentEventTarget, DomEvent.Type.INITIALIZE_DOM, - this.handleInitializeDom_); -}; - - -/** - * @param {DomEvent} e - * @private - */ -DomController.prototype.handleInitializeDom_ = function(e) { - if (this.numElementsToProcess_ == 0) { - // Find <meta> and <link> tags that specify canonical page images, compute - // image sizes with preloading and store them in element attributes. - var doc = goog.dom.getDocument(); - var metaElements = doc.getElementsByTagName('meta'); - var linkElements = doc.getElementsByTagName('link'); - this.numElementsToProcess_ = metaElements.length + linkElements.length; - if (this.numElementsToProcess_ > 0) { - goog.array.forEach(metaElements, this.processMetaElement_, this); - goog.array.forEach(linkElements, this.processLinkElement_, this); - this.timeoutId_ = goog.Timer.callOnce( - goog.bind(this.dispatchEvent, this, DomEvent.Type.DOM_INITIALIZED), - DomController.LOAD_TIMEOUT_MS_); - } else { - this.dispatchEvent(DomEvent.Type.DOM_INITIALIZED); - } - } -}; - - -/** - * Tries to compute the size of the image specified in a <meta> element. - * @param {Element} element The element to process. - * @param {number} index Index of the element in the array. - * @param {goog.array.ArrayLike} array The array. - * @private - */ -DomController.prototype.processMetaElement_ = function(element, index, array) { - var url = ''; - if (element.hasAttribute('property')) { - switch (element.getAttribute('property').toLowerCase()) { - case 'og:image': - url = element.getAttribute('content'); - var siblings = goog.dom.getChildren(goog.dom.getParentElement(element)); - var width = this.getPropertyContent_(siblings, 'og:image:width'); - var height = this.getPropertyContent_(siblings, 'og:image:height'); - if (width > 0 && height > 0) { - element.setAttribute(DocumentImage.CustomAttribute.WIDTH, width); - element.setAttribute(DocumentImage.CustomAttribute.HEIGHT, height); - } - break; - case 'og:video': - var children = goog.dom.getChildren(goog.dom.getParentElement(element)); - var width = this.getPropertyContent_(children, 'og:video:width'); - var height = this.getPropertyContent_(children, 'og:video:height'); - if (width > 0 && height > 0) { - element.setAttribute(DocumentVideo.CustomAttribute.WIDTH, width); - element.setAttribute(DocumentVideo.CustomAttribute.HEIGHT, height); - } - } - } else if (element.hasAttribute('name')) { - switch (element.getAttribute('name').toLowerCase()) { - case 'msapplication-tileimage': - case 'twitter:image': - url = element.getAttribute('content'); - } - } else if (element.hasAttribute('itemprop')) { - switch (element.getAttribute('itemprop').toLowerCase()) { - case 'thumbnailurl': - url = element.getAttribute('href') || - element.getAttribute('content'); - } - } - this.maybeComputeAndStoreImageSize_(url, element); -}; - - -/** - * Tries to compute the size of the image specified in a <link> element. - * @param {Element} element The element to process. - * @param {number} index Index of the element in the array. - * @param {goog.array.ArrayLike} array The array. - * @private - */ -DomController.prototype.processLinkElement_ = function(element, index, array) { - var url = ''; - if (element.hasAttribute('rel')) { - switch (element.getAttribute('rel').toLowerCase()) { - case 'apple-touch-icon-precomposed': - case 'apple-touch-icon': - case 'image_src': - url = element.getAttribute('href'); - } - } else if (element.hasAttribute('itemprop')) { - switch (element.getAttribute('itemprop').toLowerCase()) { - case 'thumbnailurl': - url = element.getAttribute('href') || - element.getAttribute('content'); - } - } - this.maybeComputeAndStoreImageSize_(url, element); -}; - - -/** - * Given a node list, tries to find an element with a 'property' attribute - * set to a given value and returns the value of its 'content' attribute. - * @param {Array|NodeList} elements Node list. - * @param {string} property Expected property value. - * @return {string} - * @private - */ -DomController.prototype.getPropertyContent_ = function(elements, property) { - for (var i = 0; i < elements.length; ++i) { - var element = elements[i]; - if (element.hasAttribute('property') && - element.getAttribute('property').toLowerCase() == property && - element.hasAttribute('content')) { - return element.getAttribute('content'); - } - } - return ''; -}; - - -/** - * Tries to store the size of the element image in custom element tags. - * @param {string} url Image url (empty if the element defines no image). - * @param {!Element} element Element. - * @private - */ -DomController.prototype.maybeComputeAndStoreImageSize_ = function( - url, element) { - var CustomAttribute = DocumentImage.CustomAttribute; - if (url && (!element.hasAttribute(CustomAttribute.WIDTH) || - !element.hasAttribute(CustomAttribute.HEIGHT))) { - this.computeImageSize_(url, goog.bind(this.storeImageSize_, this, element)); - } else { - this.maybeDispatchDomInitialized_(); - } -}; - - -/** - * Computes the image size with preloading and returns it via a callback. - * @param {string} url Image url. - * @param {!function(number, number)} callback A callback. - * @private - */ -DomController.prototype.computeImageSize_ = function(url, callback) { - var image = new Image(); - this.eventHandler.listenOnce(image, - [goog.events.EventType.LOAD, goog.events.EventType.ERROR], - goog.bind(this.handleImageLoadOrError_, this, callback)); - image.src = url; -}; - - -/** - * Handles image LOAD and ERROR events. - * @param {!function(number, number)} callback A callback. - * @param {goog.events.Event} e Image event. - * @private - */ -DomController.prototype.handleImageLoadOrError_ = function(callback, e) { - var image = /** @type {!Image} */ (e.target); - if (e.type == goog.events.EventType.LOAD) { - callback(image.naturalWidth, image.naturalHeight); - } else { - goog.log.warning(DomController.logger_, - 'Failed to load image ' + image.src); - } - this.maybeDispatchDomInitialized_(); -}; - - -/** - * Dispatches the DOM_INITIALIZED event if all elements have been processed. - * @private - */ -DomController.prototype.maybeDispatchDomInitialized_ = function() { - if (--this.numElementsToProcess_ == 0) { - if (this.timeoutId_ != -1) { - goog.Timer.clear(this.timeoutId_); - this.timeoutId_ = -1; - } - this.dispatchEvent(DomEvent.Type.DOM_INITIALIZED); - } -}; - - -/** - * Stores the image size in custom element attributes. - * @param {!Element} element An element defining the image url. - * @param {number} width Image width. - * @param {number} height Image height. - * @private - */ -DomController.prototype.storeImageSize_ = function(element, width, height) { - var CustomAttribute = DocumentImage.CustomAttribute; - element.setAttribute(CustomAttribute.WIDTH, width); - element.setAttribute(CustomAttribute.HEIGHT, height); -}; - -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/dom_event.js b/third_party/document_image_extractor/third_party/src/dom_event.js deleted file mode 100644 index 9a2bc8d..0000000 --- a/third_party/document_image_extractor/third_party/src/dom_event.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @fileoverview This file provides the DomEvent class. - */ - -goog.provide('image.collections.extension.DomEvent'); - -goog.require('goog.events.Event'); - -goog.scope(function() { - - - -/** - * Represents the content script DOM event. - * @param {!DomEvent.Type} type The type of this event. - * @extends {goog.events.Event} - * @constructor - */ -image.collections.extension.DomEvent = function(type) { - DomEvent.base(this, 'constructor', type); -}; -goog.inherits(image.collections.extension.DomEvent, goog.events.Event); -var DomEvent = image.collections.extension.DomEvent; - - -/** @enum {string} */ -DomEvent.Type = { - DOM_INITIALIZED: 'dom_initialized', - INITIALIZE_DOM: 'initialize_dom' -}; - -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/element_filter.js b/third_party/document_image_extractor/third_party/src/element_filter.js deleted file mode 100644 index c86bf15..0000000 --- a/third_party/document_image_extractor/third_party/src/element_filter.js +++ /dev/null @@ -1,21 +0,0 @@ -goog.provide('image.collections.extension.ElementFilter'); - -goog.scope(function() { - - - -/** - * An element filter interface. - * @interface - */ -image.collections.extension.ElementFilter = function() {}; -var ElementFilter = image.collections.extension.ElementFilter; - - -/** - * Returns true iff the element passes the filter. - * @param {!Element} element - * @return {boolean} - */ -ElementFilter.prototype.filter = function(element) {}; -}); // goog.scope diff --git a/third_party/document_image_extractor/third_party/src/visible_element_filter.js b/third_party/document_image_extractor/third_party/src/visible_element_filter.js deleted file mode 100644 index 7b7704e..0000000 --- a/third_party/document_image_extractor/third_party/src/visible_element_filter.js +++ /dev/null @@ -1,43 +0,0 @@ -goog.provide('image.collections.extension.VisibleElementFilter'); - -goog.require('goog.dom'); -goog.require('goog.style'); -goog.require('image.collections.extension.ElementFilter'); - -goog.scope(function() { -var ElementFilter = image.collections.extension.ElementFilter; - - - -/** - * Filters elements by visibility. - * @implements {ElementFilter} - * @constructor - */ -image.collections.extension.VisibleElementFilter = function() {}; -var VisibleElementFilter = image.collections.extension.VisibleElementFilter; - - -/** @override */ -VisibleElementFilter.prototype.filter = function(element) { - // TODO(busaryev): handle the overflow: hidden case. - var ancestorElement = element; - while (ancestorElement) { - if (goog.style.getComputedStyle(ancestorElement, 'display') == 'none') { - return false; - } - var size = goog.style.getSize(ancestorElement); - var overflow = goog.style.getComputedStyle(ancestorElement, 'overflow'); - if ((overflow == 'hidden') && size.isEmpty()) { - return false; - } - if (goog.style.getComputedStyle(ancestorElement, 'visibility') == - 'hidden') { - return false; - } - - ancestorElement = goog.dom.getParentElement(ancestorElement); - } - return true; -}; -}); // goog.scope |